text
stringlengths
54
60.6k
<commit_before>#include "fontContext.h" #include "platform.h" #define SDF_IMPLEMENTATION #include "sdf.h" #include <memory> #include <regex> #define DEFAULT "fonts/NotoSans-Regular.ttf" #define FONT_AR "fonts/NotoNaskh-Regular.ttf" #define FONT_HE "fonts/NotoSansHebrew-Regular.ttf" #define FONT_JA "fonts/DroidSansJapanese.ttf" #define FALLBACK "fonts/DroidSansFallback.ttf" #if defined(PLATFORM_ANDROID) #define ANDROID_FONT_PATH "/system/fonts/" #endif #define BASE_SIZE 16 #define STEP_SIZE 12 #define MAX_STEPS 3 #define SDF_WIDTH 6 #define MIN_LINE_WIDTH 4 // TODO: more flexibility on this #define BUNDLE_FONT_PATH "fonts/" namespace Tangram { FontContext::FontContext() : m_sdfRadius(SDF_WIDTH), m_atlas(*this, GlyphTexture::size, m_sdfRadius), m_batch(m_atlas, m_scratch) { resourceLoad = 0; // TODO: make this platform independent #if defined(PLATFORM_ANDROID) auto fontPath = systemFontPath("sans-serif", "400", "normal"); LOGD("FONT %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(fontPath), size); } std::string fallback = ""; int importance = 0; while (importance < 100) { fallback = systemFontFallbackPath(importance++, 400); if (fallback.empty()) { break; } if (fallback.find("UI-") != std::string::npos) { continue; } fontPath = ANDROID_FONT_PATH; fontPath += fallback; LOGD("FALLBACK %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(fontPath), size)); } } #elif defined(PLATFORM_IOS) int size = BASE_SIZE; auto loadFonts = [&](const char* path) { size_t dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, dataSize)); if (data) { for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(data, dataSize), size); } free(data); } }; auto addFaces = [&](const char* path) { size_t dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, dataSize)); if (data) { for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(data, dataSize), size)); } free(data); } }; loadFonts(DEFAULT); addFaces(FONT_AR); addFaces(FONT_HE); addFaces(FONT_JA); addFaces(FALLBACK); #else int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(DEFAULT), size); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_AR), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_HE), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_JA), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FALLBACK), size)); } #endif } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) { if (m_textures.size() == max_textures) { LOGE("Way too many glyph textures!"); return; } m_textures.emplace_back(); } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh, const unsigned char* src, uint16_t pad) { if (id >= max_textures) { return; } auto& texData = m_textures[id].texData; auto& texture = m_textures[id].texture; size_t stride = GlyphTexture::size; size_t width = GlyphTexture::size; unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride]; for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) { std::memcpy(dst + (y * stride), src + pos, gw); } dst = &texData[size_t(gx) + (size_t(gy) * width)]; gw += pad * 2; gh += pad * 2; size_t bytes = size_t(gw) * size_t(gh) * sizeof(float) * 3; if (m_sdfBuffer.size() < bytes) { m_sdfBuffer.resize(bytes); } sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius, dst, gw, gh, width, &m_sdfBuffer[0]); texture.setDirty(gy, gh); m_textures[id].dirty = true; } void FontContext::releaseAtlas(std::bitset<max_textures> _refs) { if (!_refs.any()) { return; } std::lock_guard<std::mutex> lock(m_mutex); for (size_t i = 0; i < m_textures.size(); i++) { if (!_refs[i]) { continue; } if (--m_atlasRefCount[i] == 0) { LOGD("CLEAR ATLAS %d", i); m_atlas.clear(i); m_textures[i].texData.assign(GlyphTexture::size * GlyphTexture::size, 0); } } } void FontContext::updateTextures(RenderState& rs) { std::lock_guard<std::mutex> lock(m_mutex); for (auto& gt : m_textures) { if (gt.dirty || !gt.texture.isValid(rs)) { gt.dirty = false; auto td = reinterpret_cast<const GLuint*>(gt.texData.data()); gt.texture.update(rs, 0, td); } } } void FontContext::bindTexture(RenderState& rs, alfons::AtlasID _id, GLuint _unit) { std::lock_guard<std::mutex> lock(m_mutex); m_textures[_id].texture.bind(rs, _unit); } bool FontContext::layoutText(TextStyle::Parameters& _params, const std::string& _text, std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size, std::vector<TextRange>& _textRanges) { std::lock_guard<std::mutex> lock(m_mutex); alfons::LineLayout line = m_shaper.shape(_params.font, _text); if (line.shapes().size() == 0) { LOGD("Empty text line"); return false; } line.setScale(_params.fontScale); // m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs // and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout. m_scratch.quads = &_quads; size_t quadsStart = _quads.size(); alfons::LineMetrics metrics; // Collect possible alignment from anchor fallbacks std::vector<TextLabelProperty::Align> alignments; for (auto anchorFallback : _params.labelOptions.anchorFallback) { TextLabelProperty::Align alignmentFallback = TextLabelProperty::alignFromAnchor(anchorFallback); alignments.push_back(alignmentFallback); } if (_params.wordWrap) { m_textWrapper.clearWraps(); if (line.shapes().size() > 0) { float width = m_textWrapper.getShapeRangeWidth(line, MIN_LINE_WIDTH, _params.maxLineWidth); for (auto& align : alignments) { int rangeStart = m_scratch.quads->size(); m_textWrapper.draw(m_batch, width, line, align, _params.lineSpacing, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges.push_back({align, {rangeStart, rangeEnd - rangeStart}}); LOGD("Text quad range {%d,%d} for label %s", rangeStart, rangeEnd, _text.c_str()); } } } else { glm::vec2 position(0); for (auto& align : alignments) { int rangeStart = m_scratch.quads->size(); m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges.push_back({align, {rangeStart, rangeEnd - rangeStart}}); } } // TextLabel parameter: Dimension float width = metrics.aabb.z - metrics.aabb.x; float height = metrics.aabb.w - metrics.aabb.y; // Offset to center all glyphs around 0/0 glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale, (metrics.aabb.y + height * 0.5) * TextVertex::position_scale); auto it = _quads.begin() + quadsStart; if (it == _quads.end()) { // No glyphs added return false; } while (it != _quads.end()) { if (!_refs[it->atlas]) { _refs[it->atlas] = true; m_atlasRefCount[it->atlas]++; } it->quad[0].pos -= offset; it->quad[1].pos -= offset; it->quad[2].pos -= offset; it->quad[3].pos -= offset; ++it; } _size = glm::vec2(width, height); return true; } void FontContext::fetch(const FontDescription& _ft) { const static std::regex regex("^(http|https):/"); std::smatch match; if (std::regex_search(_ft.uri, match, regex)) { // Load remote resourceLoad++; startUrlRequest(_ft.uri, [&, _ft](std::vector<char>&& rawData) { if (rawData.size() == 0) { LOGE("Bad URL request for font %s at URL %s", _ft.alias.c_str(), _ft.uri.c_str()); } else { std::lock_guard<std::mutex> lock(m_mutex); char* data = reinterpret_cast<char*>(rawData.data()); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { auto font = m_alfons.getFont(_ft.alias, size); font->addFace(m_alfons.addFontFace(alfons::InputSource(data, rawData.size()), size)); } } resourceLoad--; }); } else { // Load from local storage size_t dataSize = 0; unsigned char* data = nullptr; if (loadFontAlloc(_ft.bundleAlias, data, dataSize)) { const char* rdata = reinterpret_cast<const char*>(data); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { auto font = m_alfons.getFont(_ft.alias, size); font->addFace(m_alfons.addFontFace(alfons::InputSource(rdata, dataSize), size)); } free(data); } else { LOGW("Local font at path %s can't be found", _ft.uri.c_str()); } } } bool FontContext::loadFontAlloc(const std::string& _bundleFontPath, unsigned char* _data, size_t& _dataSize) { if (!m_sceneResourceRoot.empty()) { std::string resourceFontPath = m_sceneResourceRoot + _bundleFontPath; _data = bytesFromFile(resourceFontPath.c_str(), _dataSize); if (_data) { return true; } } _data = bytesFromFile(_bundleFontPath.c_str(), _dataSize); if (_data) { return true; } return false; } void FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) { if (atlasGlyph.atlas >= max_textures) { return; } auto& g = *atlasGlyph.glyph; quads->push_back({ atlasGlyph.atlas, {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}}, {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}}, {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}}, {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}}); } std::shared_ptr<alfons::Font> FontContext::getFont(const std::string& _family, const std::string& _style, const std::string& _weight, float _size) { int sizeIndex = 0; // Pick the smallest font that does not scale down too much float fontSize = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++) { sizeIndex = i; if (_size <= fontSize) { break; } fontSize += STEP_SIZE; } std::lock_guard<std::mutex> lock(m_mutex); auto font = m_alfons.getFont(FontDescription::Alias(_family, _style, _weight), fontSize); if (font->hasFaces()) { return font; } size_t dataSize = 0; unsigned char* data = nullptr; // Assuming bundled ttf file follows this convention std::string bundleFontPath = BUNDLE_FONT_PATH + FontDescription::BundleAlias(_family, _weight, _style); if (!loadFontAlloc(bundleFontPath, data, dataSize)) { // Try fallback std::string sysFontPath = systemFontPath(_family, _weight, _style); data = bytesFromFile(sysFontPath.c_str(), dataSize); if (!data) { LOGE("Could not load font file %s", FontDescription::BundleAlias(_family, _weight, _style).c_str()); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } font->addFace(m_alfons.addFontFace(alfons::InputSource(reinterpret_cast<char*>(data), dataSize), fontSize)); free(data); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } <commit_msg>wip: render line-labels again<commit_after>#include "fontContext.h" #include "platform.h" #define SDF_IMPLEMENTATION #include "sdf.h" #include <memory> #include <regex> #define DEFAULT "fonts/NotoSans-Regular.ttf" #define FONT_AR "fonts/NotoNaskh-Regular.ttf" #define FONT_HE "fonts/NotoSansHebrew-Regular.ttf" #define FONT_JA "fonts/DroidSansJapanese.ttf" #define FALLBACK "fonts/DroidSansFallback.ttf" #if defined(PLATFORM_ANDROID) #define ANDROID_FONT_PATH "/system/fonts/" #endif #define BASE_SIZE 16 #define STEP_SIZE 12 #define MAX_STEPS 3 #define SDF_WIDTH 6 #define MIN_LINE_WIDTH 4 // TODO: more flexibility on this #define BUNDLE_FONT_PATH "fonts/" namespace Tangram { FontContext::FontContext() : m_sdfRadius(SDF_WIDTH), m_atlas(*this, GlyphTexture::size, m_sdfRadius), m_batch(m_atlas, m_scratch) { resourceLoad = 0; // TODO: make this platform independent #if defined(PLATFORM_ANDROID) auto fontPath = systemFontPath("sans-serif", "400", "normal"); LOGD("FONT %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(fontPath), size); } std::string fallback = ""; int importance = 0; while (importance < 100) { fallback = systemFontFallbackPath(importance++, 400); if (fallback.empty()) { break; } if (fallback.find("UI-") != std::string::npos) { continue; } fontPath = ANDROID_FONT_PATH; fontPath += fallback; LOGD("FALLBACK %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(fontPath), size)); } } #elif defined(PLATFORM_IOS) int size = BASE_SIZE; auto loadFonts = [&](const char* path) { size_t dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, dataSize)); if (data) { for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(data, dataSize), size); } free(data); } }; auto addFaces = [&](const char* path) { size_t dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, dataSize)); if (data) { for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(data, dataSize), size)); } free(data); } }; loadFonts(DEFAULT); addFaces(FONT_AR); addFaces(FONT_HE); addFaces(FONT_JA); addFaces(FALLBACK); #else int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(DEFAULT), size); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_AR), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_HE), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_JA), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FALLBACK), size)); } #endif } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) { if (m_textures.size() == max_textures) { LOGE("Way too many glyph textures!"); return; } m_textures.emplace_back(); } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh, const unsigned char* src, uint16_t pad) { if (id >= max_textures) { return; } auto& texData = m_textures[id].texData; auto& texture = m_textures[id].texture; size_t stride = GlyphTexture::size; size_t width = GlyphTexture::size; unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride]; for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) { std::memcpy(dst + (y * stride), src + pos, gw); } dst = &texData[size_t(gx) + (size_t(gy) * width)]; gw += pad * 2; gh += pad * 2; size_t bytes = size_t(gw) * size_t(gh) * sizeof(float) * 3; if (m_sdfBuffer.size() < bytes) { m_sdfBuffer.resize(bytes); } sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius, dst, gw, gh, width, &m_sdfBuffer[0]); texture.setDirty(gy, gh); m_textures[id].dirty = true; } void FontContext::releaseAtlas(std::bitset<max_textures> _refs) { if (!_refs.any()) { return; } std::lock_guard<std::mutex> lock(m_mutex); for (size_t i = 0; i < m_textures.size(); i++) { if (!_refs[i]) { continue; } if (--m_atlasRefCount[i] == 0) { LOGD("CLEAR ATLAS %d", i); m_atlas.clear(i); m_textures[i].texData.assign(GlyphTexture::size * GlyphTexture::size, 0); } } } void FontContext::updateTextures(RenderState& rs) { std::lock_guard<std::mutex> lock(m_mutex); for (auto& gt : m_textures) { if (gt.dirty || !gt.texture.isValid(rs)) { gt.dirty = false; auto td = reinterpret_cast<const GLuint*>(gt.texData.data()); gt.texture.update(rs, 0, td); } } } void FontContext::bindTexture(RenderState& rs, alfons::AtlasID _id, GLuint _unit) { std::lock_guard<std::mutex> lock(m_mutex); m_textures[_id].texture.bind(rs, _unit); } bool FontContext::layoutText(TextStyle::Parameters& _params, const std::string& _text, std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size, std::vector<TextRange>& _textRanges) { std::lock_guard<std::mutex> lock(m_mutex); alfons::LineLayout line = m_shaper.shape(_params.font, _text); if (line.shapes().size() == 0) { LOGD("Empty text line"); return false; } line.setScale(_params.fontScale); // m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs // and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout. m_scratch.quads = &_quads; size_t quadsStart = _quads.size(); alfons::LineMetrics metrics; // Collect possible alignment from anchor fallbacks std::vector<TextLabelProperty::Align> alignments; for (auto anchorFallback : _params.labelOptions.anchorFallback) { TextLabelProperty::Align alignmentFallback = TextLabelProperty::alignFromAnchor(anchorFallback); alignments.push_back(alignmentFallback); } if (alignments.empty()) { alignments.push_back(TextLabelProperty::Align::center); } if (_params.wordWrap) { m_textWrapper.clearWraps(); if (line.shapes().size() > 0) { float width = m_textWrapper.getShapeRangeWidth(line, MIN_LINE_WIDTH, _params.maxLineWidth); for (auto& align : alignments) { int rangeStart = m_scratch.quads->size(); m_textWrapper.draw(m_batch, width, line, align, _params.lineSpacing, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges.push_back({align, {rangeStart, rangeEnd - rangeStart}}); LOGD("Text quad range {%d,%d} for label %s", rangeStart, rangeEnd, _text.c_str()); } } } else { glm::vec2 position(0); for (auto& align : alignments) { int rangeStart = m_scratch.quads->size(); m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics); int rangeEnd = m_scratch.quads->size(); _textRanges.push_back({align, {rangeStart, rangeEnd - rangeStart}}); } } // TextLabel parameter: Dimension float width = metrics.aabb.z - metrics.aabb.x; float height = metrics.aabb.w - metrics.aabb.y; // Offset to center all glyphs around 0/0 glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale, (metrics.aabb.y + height * 0.5) * TextVertex::position_scale); auto it = _quads.begin() + quadsStart; if (it == _quads.end()) { // No glyphs added return false; } while (it != _quads.end()) { if (!_refs[it->atlas]) { _refs[it->atlas] = true; m_atlasRefCount[it->atlas]++; } it->quad[0].pos -= offset; it->quad[1].pos -= offset; it->quad[2].pos -= offset; it->quad[3].pos -= offset; ++it; } _size = glm::vec2(width, height); return true; } void FontContext::fetch(const FontDescription& _ft) { const static std::regex regex("^(http|https):/"); std::smatch match; if (std::regex_search(_ft.uri, match, regex)) { // Load remote resourceLoad++; startUrlRequest(_ft.uri, [&, _ft](std::vector<char>&& rawData) { if (rawData.size() == 0) { LOGE("Bad URL request for font %s at URL %s", _ft.alias.c_str(), _ft.uri.c_str()); } else { std::lock_guard<std::mutex> lock(m_mutex); char* data = reinterpret_cast<char*>(rawData.data()); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { auto font = m_alfons.getFont(_ft.alias, size); font->addFace(m_alfons.addFontFace(alfons::InputSource(data, rawData.size()), size)); } } resourceLoad--; }); } else { // Load from local storage size_t dataSize = 0; unsigned char* data = nullptr; if (loadFontAlloc(_ft.bundleAlias, data, dataSize)) { const char* rdata = reinterpret_cast<const char*>(data); int size = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++, size += STEP_SIZE) { auto font = m_alfons.getFont(_ft.alias, size); font->addFace(m_alfons.addFontFace(alfons::InputSource(rdata, dataSize), size)); } free(data); } else { LOGW("Local font at path %s can't be found", _ft.uri.c_str()); } } } bool FontContext::loadFontAlloc(const std::string& _bundleFontPath, unsigned char* _data, size_t& _dataSize) { if (!m_sceneResourceRoot.empty()) { std::string resourceFontPath = m_sceneResourceRoot + _bundleFontPath; _data = bytesFromFile(resourceFontPath.c_str(), _dataSize); if (_data) { return true; } } _data = bytesFromFile(_bundleFontPath.c_str(), _dataSize); if (_data) { return true; } return false; } void FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) { if (atlasGlyph.atlas >= max_textures) { return; } auto& g = *atlasGlyph.glyph; quads->push_back({ atlasGlyph.atlas, {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}}, {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}}, {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}}, {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}}); } std::shared_ptr<alfons::Font> FontContext::getFont(const std::string& _family, const std::string& _style, const std::string& _weight, float _size) { int sizeIndex = 0; // Pick the smallest font that does not scale down too much float fontSize = BASE_SIZE; for (int i = 0; i < MAX_STEPS; i++) { sizeIndex = i; if (_size <= fontSize) { break; } fontSize += STEP_SIZE; } std::lock_guard<std::mutex> lock(m_mutex); auto font = m_alfons.getFont(FontDescription::Alias(_family, _style, _weight), fontSize); if (font->hasFaces()) { return font; } size_t dataSize = 0; unsigned char* data = nullptr; // Assuming bundled ttf file follows this convention std::string bundleFontPath = BUNDLE_FONT_PATH + FontDescription::BundleAlias(_family, _weight, _style); if (!loadFontAlloc(bundleFontPath, data, dataSize)) { // Try fallback std::string sysFontPath = systemFontPath(_family, _weight, _style); data = bytesFromFile(sysFontPath.c_str(), dataSize); if (!data) { LOGE("Could not load font file %s", FontDescription::BundleAlias(_family, _weight, _style).c_str()); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } font->addFace(m_alfons.addFontFace(alfons::InputSource(reinterpret_cast<char*>(data), dataSize), fontSize)); free(data); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } <|endoftext|>
<commit_before>#include "tileManager.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include <chrono> TileManager::TileManager() { } TileManager::TileManager(TileManager&& _other) : m_view(std::move(_other.m_view)), m_tileSet(std::move(_other.m_tileSet)), m_dataSources(std::move(_other.m_dataSources)), m_incomingTiles(std::move(_other.m_incomingTiles)) { } TileManager::~TileManager() { m_dataSources.clear(); m_tileSet.clear(); m_incomingTiles.clear(); } bool TileManager::updateTileSet() { bool tileSetChanged = false; // Check if any incoming tiles are finished { auto incomingTilesIter = m_incomingTiles.begin(); while (incomingTilesIter != m_incomingTiles.end()) { std::future<MapTile*>& tileFuture = *incomingTilesIter; std::chrono::milliseconds span (0); if (tileFuture.wait_for(span) == std::future_status::ready) { MapTile* tile = tileFuture.get(); const TileID& id = tile->getID(); logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y); m_tileSet[id].reset(tile); tileSetChanged = true; incomingTilesIter = m_incomingTiles.erase(incomingTilesIter); } else { incomingTilesIter++; } } } if (!(m_view->viewChanged()) && !tileSetChanged) { // No new tiles have come into view and no tiles have finished loading, // so the tileset is unchanged return false; } const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); auto tileSetIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (tileSetIter != m_tileSet.end() && visTilesIter != visibleTiles.end()) { TileID visTile = *visTilesIter; TileID tileInSet = tileSetIter->first; if (visTile == tileInSet) { // Tiles match here, nothing to do visTilesIter++; tileSetIter++; } else if (visTile < tileInSet) { // tileSet is missing an element present in visibleTiles addTile(visTile); tileSetChanged = true; visTilesIter++; } else { // visibleTiles is missing an element present in tileSet removeTile(tileSetIter); tileSetChanged = true; } } while (tileSetIter != m_tileSet.end()) { // All tiles in tileSet that haven't been covered yet are not in visibleTiles, so remove them removeTile(tileSetIter); tileSetChanged = true; } while (visTilesIter != visibleTiles.end()) { // All tiles in visibleTiles that haven't been covered yet are not in tileSet, so add them addTile(*visTilesIter); visTilesIter++; tileSetChanged = true; } return tileSetChanged; } void TileManager::addTile(const TileID& _tileID) { m_tileSet[_tileID].reset(nullptr); // Emplace a unique_ptr that is null until tile finishes loading std::future<MapTile*> incoming = std::async(std::launch::async, [&](TileID _id) { MapTile* tile = new MapTile(_id, m_view->getMapProjection()); for (const auto& source : m_dataSources) { logMsg("Loading tile [%d, %d, %d]\n", _id.z, _id.x, _id.y); if ( ! source->loadTileData(*tile)) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _id.z, _id.x, _id.y); } std::shared_ptr<TileData> tileData = source->getTileData(_id); for (auto& style : m_scene->getStyles()) { style->addData(*tileData, *tile, m_view->getMapProjection()); } } return tile; }, _tileID); m_incomingTiles.push_back(std::move(incoming)); } void TileManager::removeTile(std::map< TileID, std::unique_ptr<MapTile> >::iterator& _tileIter) { // Remove tile from tileSet and destruct tile _tileIter = m_tileSet.erase(_tileIter); // TODO: if tile is being loaded, cancel loading; For now they continue to load // and will be culled the next time that updateTileSet is called } <commit_msg>Prevent TileManager from trying to get data from a tile that failed to load<commit_after>#include "tileManager.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include <chrono> TileManager::TileManager() { } TileManager::TileManager(TileManager&& _other) : m_view(std::move(_other.m_view)), m_tileSet(std::move(_other.m_tileSet)), m_dataSources(std::move(_other.m_dataSources)), m_incomingTiles(std::move(_other.m_incomingTiles)) { } TileManager::~TileManager() { m_dataSources.clear(); m_tileSet.clear(); m_incomingTiles.clear(); } bool TileManager::updateTileSet() { bool tileSetChanged = false; // Check if any incoming tiles are finished { auto incomingTilesIter = m_incomingTiles.begin(); while (incomingTilesIter != m_incomingTiles.end()) { std::future<MapTile*>& tileFuture = *incomingTilesIter; std::chrono::milliseconds span (0); if (tileFuture.wait_for(span) == std::future_status::ready) { MapTile* tile = tileFuture.get(); const TileID& id = tile->getID(); logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y); m_tileSet[id].reset(tile); tileSetChanged = true; incomingTilesIter = m_incomingTiles.erase(incomingTilesIter); } else { incomingTilesIter++; } } } if (!(m_view->viewChanged()) && !tileSetChanged) { // No new tiles have come into view and no tiles have finished loading, // so the tileset is unchanged return false; } const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); auto tileSetIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (tileSetIter != m_tileSet.end() && visTilesIter != visibleTiles.end()) { TileID visTile = *visTilesIter; TileID tileInSet = tileSetIter->first; if (visTile == tileInSet) { // Tiles match here, nothing to do visTilesIter++; tileSetIter++; } else if (visTile < tileInSet) { // tileSet is missing an element present in visibleTiles addTile(visTile); tileSetChanged = true; visTilesIter++; } else { // visibleTiles is missing an element present in tileSet removeTile(tileSetIter); tileSetChanged = true; } } while (tileSetIter != m_tileSet.end()) { // All tiles in tileSet that haven't been covered yet are not in visibleTiles, so remove them removeTile(tileSetIter); tileSetChanged = true; } while (visTilesIter != visibleTiles.end()) { // All tiles in visibleTiles that haven't been covered yet are not in tileSet, so add them addTile(*visTilesIter); visTilesIter++; tileSetChanged = true; } return tileSetChanged; } void TileManager::addTile(const TileID& _tileID) { m_tileSet[_tileID].reset(nullptr); // Emplace a unique_ptr that is null until tile finishes loading std::future<MapTile*> incoming = std::async(std::launch::async, [&](TileID _id) { MapTile* tile = new MapTile(_id, m_view->getMapProjection()); for (const auto& source : m_dataSources) { logMsg("Loading tile [%d, %d, %d]\n", _id.z, _id.x, _id.y); if ( ! source->loadTileData(*tile)) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _id.z, _id.x, _id.y); } else { std::shared_ptr<TileData> tileData = source->getTileData(_id); for (auto& style : m_scene->getStyles()) { style->addData(*tileData, *tile, m_view->getMapProjection()); } } } return tile; }, _tileID); m_incomingTiles.push_back(std::move(incoming)); } void TileManager::removeTile(std::map< TileID, std::unique_ptr<MapTile> >::iterator& _tileIter) { // Remove tile from tileSet and destruct tile _tileIter = m_tileSet.erase(_tileIter); // TODO: if tile is being loaded, cancel loading; For now they continue to load // and will be culled the next time that updateTileSet is called } <|endoftext|>
<commit_before>#include "tileManager.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include <chrono> #include <algorithm> TileManager::TileManager() { // Instantiate workers for (size_t i = 0; i < MAX_WORKERS; i++) { m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker())); } } TileManager::TileManager(TileManager&& _other) : m_view(std::move(_other.m_view)), m_tileSet(std::move(_other.m_tileSet)), m_dataSources(std::move(_other.m_dataSources)), m_workers(std::move(_other.m_workers)), m_queuedTiles(std::move(_other.m_queuedTiles)) { } TileManager::~TileManager() { for (auto& worker : m_workers) { if (!worker->isFree()) { worker->abort(); worker->getTileResult(); } // We stop all workers before we destroy the resources they use. // TODO: This will wait for any pending network requests to finish, // which could delay closing of the application. } m_dataSources.clear(); m_tileSet.clear(); } void TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, const int _dataSourceID) { std::lock_guard<std::mutex> lock(m_queueTileMutex); m_queuedTiles.push_front(std::unique_ptr<WorkerData>(new WorkerData(std::move(_rawData), _tileId, _dataSourceID))); } void TileManager::updateTileSet() { m_tileSetChanged = false; // Check if any native worker needs to be dispatched i.e. queuedTiles is not empty { auto workersIter = m_workers.begin(); auto queuedTilesIter = m_queuedTiles.begin(); while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) { auto& worker = *workersIter; if (worker->isFree()) { logMsg("Dispatched worker for processing tile: [%d, %d, %d]\n", (*queuedTilesIter)->tileID->x, (*queuedTilesIter)->tileID->y, (*queuedTilesIter)->tileID->z); worker->processTileData(std::move(*queuedTilesIter), m_dataSources, m_scene->getStyles(), *m_view); queuedTilesIter = m_queuedTiles.erase(queuedTilesIter); } ++workersIter; } } // Check if any incoming tiles are finished for (auto& worker : m_workers) { if (!worker->isFree() && worker->isFinished()) { // Get result from worker and move it into tile set auto tile = worker->getTileResult(); const TileID& id = tile->getID(); logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y); std::swap(m_tileSet[id], tile); cleanProxyTiles(id); m_tileSetChanged = true; } } if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) { // No new tiles have come into view and no tiles have finished loading, // so the tileset is unchanged return; } const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); // Loop over visibleTiles and add any needed tiles to tileSet { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (visTilesIter != visibleTiles.end()) { if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles addTile(*visTilesIter); m_tileSetChanged = true; ++visTilesIter; } else if (setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet (handled below) ++setTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } // Loop over tileSet and remove any tiles that are neither visible nor proxies { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (setTilesIter != m_tileSet.end()) { if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet if (setTilesIter->second->getProxyCounter() <= 0) { removeTile(setTilesIter); m_tileSetChanged = true; } else { ++setTilesIter; } } else if (*visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles (shouldn't occur) ++visTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } } void TileManager::addTile(const TileID& _tileID) { std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection())); m_tileSet[_tileID] = std::move(tile); for(size_t dsIndex = 0; dsIndex < m_dataSources.size(); dsIndex++) { // ByPass Network Request if data already loaded/parsed // Create workerData with empty "rawData", parsed data will be fetched in the Worker::processTileData logMsg("Initiate network request for tile: [%d, %d, %d]\n", _tileID.x, _tileID.y, _tileID.z); if(m_dataSources[dsIndex]->hasTileData(_tileID)) { addToWorkerQueue(std::move(std::vector<char>()), _tileID, dsIndex); } else if( !m_dataSources[dsIndex]->loadTileData(_tileID, dsIndex) ) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _tileID.z, _tileID.x, _tileID.y); } } //Add Proxy if corresponding proxy MapTile ready updateProxyTiles(_tileID, m_view->isZoomIn()); } void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) { const TileID& id = _tileIter->first; // Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable for(auto& dataSource : m_dataSources) { dataSource->cancelLoadingTile(id); } // Remove tile from queue, if present const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(), [&](std::unique_ptr<WorkerData>& p) { return ( *(p->tileID) == id); }); if (found != m_queuedTiles.end()) { logMsg("Erasing tile: [%d,%d,%d]\n", id.x, id.y, id.z); m_queuedTiles.erase(found); cleanProxyTiles(id); } // If a worker is processing this tile, abort it for (const auto& worker : m_workers) { if (!worker->isFree() && worker->getTileID() == id) { worker->abort(); // Proxy tiles will be cleaned in update loop } } // Remove labels for tile LabelContainer::GetInstance()->removeLabels(id); // Remove tile from set _tileIter = m_tileSet.erase(_tileIter); } void TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) { if (_zoomingIn) { // zoom in - add parent const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->incProxyCounter(); } } else { for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->incProxyCounter(); } } } } void TileManager::cleanProxyTiles(const TileID& _tileID) { // check if parent proxy is present const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->decProxyCounter(); } // check if child proxies are present for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->decProxyCounter(); } } } <commit_msg>Update tile order processing<commit_after>#include "tileManager.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include <chrono> #include <algorithm> TileManager::TileManager() { // Instantiate workers for (size_t i = 0; i < MAX_WORKERS; i++) { m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker())); } } TileManager::TileManager(TileManager&& _other) : m_view(std::move(_other.m_view)), m_tileSet(std::move(_other.m_tileSet)), m_dataSources(std::move(_other.m_dataSources)), m_workers(std::move(_other.m_workers)), m_queuedTiles(std::move(_other.m_queuedTiles)) { } TileManager::~TileManager() { for (auto& worker : m_workers) { if (!worker->isFree()) { worker->abort(); worker->getTileResult(); } // We stop all workers before we destroy the resources they use. // TODO: This will wait for any pending network requests to finish, // which could delay closing of the application. } m_dataSources.clear(); m_tileSet.clear(); } void TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, const int _dataSourceID) { std::lock_guard<std::mutex> lock(m_queueTileMutex); m_queuedTiles.push_back(std::unique_ptr<WorkerData>(new WorkerData(std::move(_rawData), _tileId, _dataSourceID))); } void TileManager::updateTileSet() { m_tileSetChanged = false; // Check if any native worker needs to be dispatched i.e. queuedTiles is not empty { auto workersIter = m_workers.begin(); auto queuedTilesIter = m_queuedTiles.begin(); while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) { auto& worker = *workersIter; if (worker->isFree()) { logMsg("Dispatched worker for processing tile: [%d, %d, %d]\n", (*queuedTilesIter)->tileID->x, (*queuedTilesIter)->tileID->y, (*queuedTilesIter)->tileID->z); worker->processTileData(std::move(*queuedTilesIter), m_dataSources, m_scene->getStyles(), *m_view); queuedTilesIter = m_queuedTiles.erase(queuedTilesIter); } ++workersIter; } } // Check if any incoming tiles are finished for (auto& worker : m_workers) { if (!worker->isFree() && worker->isFinished()) { // Get result from worker and move it into tile set auto tile = worker->getTileResult(); const TileID& id = tile->getID(); logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y); std::swap(m_tileSet[id], tile); cleanProxyTiles(id); m_tileSetChanged = true; } } if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) { // No new tiles have come into view and no tiles have finished loading, // so the tileset is unchanged return; } const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); // Loop over visibleTiles and add any needed tiles to tileSet { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (visTilesIter != visibleTiles.end()) { if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles addTile(*visTilesIter); m_tileSetChanged = true; ++visTilesIter; } else if (setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet (handled below) ++setTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } // Loop over tileSet and remove any tiles that are neither visible nor proxies { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (setTilesIter != m_tileSet.end()) { if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet if (setTilesIter->second->getProxyCounter() <= 0) { removeTile(setTilesIter); m_tileSetChanged = true; } else { ++setTilesIter; } } else if (*visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles (shouldn't occur) ++visTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } } void TileManager::addTile(const TileID& _tileID) { std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection())); m_tileSet[_tileID] = std::move(tile); for(size_t dsIndex = 0; dsIndex < m_dataSources.size(); dsIndex++) { // ByPass Network Request if data already loaded/parsed // Create workerData with empty "rawData", parsed data will be fetched in the Worker::processTileData logMsg("Initiate network request for tile: [%d, %d, %d]\n", _tileID.x, _tileID.y, _tileID.z); if(m_dataSources[dsIndex]->hasTileData(_tileID)) { addToWorkerQueue(std::move(std::vector<char>()), _tileID, dsIndex); } else if( !m_dataSources[dsIndex]->loadTileData(_tileID, dsIndex) ) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _tileID.z, _tileID.x, _tileID.y); } } //Add Proxy if corresponding proxy MapTile ready updateProxyTiles(_tileID, m_view->isZoomIn()); } void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) { const TileID& id = _tileIter->first; // Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable for(auto& dataSource : m_dataSources) { dataSource->cancelLoadingTile(id); } // Remove tile from queue, if present const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(), [&](std::unique_ptr<WorkerData>& p) { return ( *(p->tileID) == id); }); if (found != m_queuedTiles.end()) { logMsg("Erasing tile: [%d,%d,%d]\n", id.x, id.y, id.z); m_queuedTiles.erase(found); cleanProxyTiles(id); } // If a worker is processing this tile, abort it for (const auto& worker : m_workers) { if (!worker->isFree() && worker->getTileID() == id) { worker->abort(); // Proxy tiles will be cleaned in update loop } } // Remove labels for tile LabelContainer::GetInstance()->removeLabels(id); // Remove tile from set _tileIter = m_tileSet.erase(_tileIter); } void TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) { if (_zoomingIn) { // zoom in - add parent const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->incProxyCounter(); } } else { for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->incProxyCounter(); } } } } void TileManager::cleanProxyTiles(const TileID& _tileID) { // check if parent proxy is present const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->decProxyCounter(); } // check if child proxies are present for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->decProxyCounter(); } } } <|endoftext|>
<commit_before>// Natron /* 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 "AboutWindow.h" #include "Global/Macros.h" CLANG_DIAG_OFF(deprecated) #include <QTextBrowser> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTabWidget> #include <QLabel> #include <QFile> #include <QTextCodec> CLANG_DIAG_ON(deprecated) #include "Global/GlobalDefines.h" #include "Global/GitVersion.h" #include "Gui/Button.h" #include "Gui/Gui.h" AboutWindow::AboutWindow(Gui* gui, QWidget* parent) : QDialog(parent) , _gui(gui) { setWindowTitle(QObject::tr("About ") + NATRON_APPLICATION_NAME); _mainLayout = new QVBoxLayout(this); setLayout(_mainLayout); _iconLabel = new QLabel(this); _iconLabel->setPixmap( QPixmap(NATRON_APPLICATION_ICON_PATH).scaled(128, 128) ); _mainLayout->addWidget(_iconLabel); _tabWidget = new QTabWidget(this); _mainLayout->addWidget(_tabWidget); _buttonContainer = new QWidget(this); _buttonLayout = new QHBoxLayout(_buttonContainer); _buttonLayout->addStretch(); _closeButton = new Button(QObject::tr("Close"),_buttonContainer); QObject::connect( _closeButton, SIGNAL( clicked() ), this, SLOT( accept() ) ); _buttonLayout->addWidget(_closeButton); _mainLayout->addWidget(_buttonContainer); ///filling tabs now _aboutText = new QTextBrowser(_tabWidget); _aboutText->setOpenExternalLinks(true); QString aboutText; QString customBuild(NATRON_CUSTOM_BUILD_USER_NAME); if (!customBuild.isEmpty()) { aboutText = QString("<p>%1 custom build for %2 %3.</p>") .arg(NATRON_APPLICATION_NAME) .arg(customBuild) #ifdef DEBUG .arg("(debug)"); #else #ifdef NDEBUG // release with asserts disabled (should be the *real* release) .arg(""); #else // release with asserts enabled .arg("(opt)"); #endif #endif } else { aboutText = QString("<p>%1 version %2 %3 %4.</p>") .arg(NATRON_APPLICATION_NAME) .arg(NATRON_VERSION_STRING) .arg(NATRON_DEVELOPMENT_STATUS) #ifdef DEBUG .arg("(debug)"); #else #ifdef NDEBUG // release with asserts disabled (should be the *real* release) .arg(""); #else // release with asserts enabled .arg("(opt)"); #endif #endif } QString endAbout = QString("<p>This version was generated from the source code branch %3" " at commit %4.</p>" "<p>Copyright (C) 2013 the %1 developers.</p>" "<p>This is free software. You may redistribute copies of it " "under the terms of the <a href=\"http://www.mozilla.org/MPL/2.0/\">" "<font color=\"orange\">MPL Mozilla Public License</font></a>. " "There is NO WARRANTY, to the extent permitted by law.</p>" "<p>See <a href=\"%2\"><font color=\"orange\">%1 's website </font></a>" "for more information on this software.</p>") .arg(NATRON_APPLICATION_NAME) // %1 .arg("https://natron.inria.fr") // %2 .arg(GIT_BRANCH) // %3 .arg(GIT_COMMIT); // %4 aboutText.append(endAbout); if (!strcmp(NATRON_DEVELOPMENT_STATUS, NATRON_DEVELOPMENT_ALPHA)) { QString toAppend = QString("<p>Note: This software is currently in alpha version, meaning there are missing features," " bugs and untested stuffs. If you feel like reporting a bug, please do so " "on the <a href=\"%1\"><font color=\"orange\"> issue tracker.</font></a></p>") .arg("https://github.com/MrKepzie/Natron/issues"); // %1 ; } else if (!strcmp(NATRON_DEVELOPMENT_STATUS, NATRON_DEVELOPMENT_BETA)) { QString toAppend = QString("<p>Note: This software is currently under beta testing, meaning there are " " bugs and untested stuffs. If you feel like reporting a bug, please do so " "on the <a href=\"%1\"><font color=\"orange\"> issue tracker.</font></a></p>") .arg("https://github.com/MrKepzie/Natron/issues"); // %1 ; } else if (!strcmp(NATRON_DEVELOPMENT_STATUS, NATRON_DEVELOPMENT_RELEASE_CANDIDATE)) { QString toAppend = QString("The version of this sofware is a release candidate, which means it has the potential of becoming " "the future stable release but might still have some bugs."); aboutText.append(toAppend); } _aboutText->setText(aboutText); _tabWidget->addTab( _aboutText, QObject::tr("About") ); _libsText = new QTextBrowser(_tabWidget); _libsText->setOpenExternalLinks(true); QString libsText = QString("<p> Qt %1 </p>" "<p> Boost %2 </p>" "<p> GLEW %3 </p>" "<p> OpenGL %4 </p>" "<p> Cairo %5 </p>") .arg( gui->getQtVersion() ) .arg( gui->getBoostVersion() ) .arg( gui->getGlewVersion() ) .arg( gui->getOpenGLVersion() ) .arg( gui->getCairoVersion() ); _libsText->setText(libsText); _tabWidget->addTab( _libsText, QObject::tr("Libraries") ); _teamText = new QTextBrowser(_tabWidget); _teamText->setOpenExternalLinks(false); { QFile team_file(":CONTRIBUTORS.txt"); team_file.open(QIODevice::ReadOnly | QIODevice::Text); _teamText->setText( QTextCodec::codecForName("UTF-8")->toUnicode( team_file.readAll() ) ); _tabWidget->addTab( _teamText, QObject::tr("Contributors") ); _licenseText = new QTextBrowser(_tabWidget); _licenseText->setOpenExternalLinks(false); } { QFile license(":LICENSE.txt"); license.open(QIODevice::ReadOnly | QIODevice::Text); _licenseText->setText( QTextCodec::codecForName("UTF-8")->toUnicode( license.readAll() ) ); _tabWidget->addTab( _licenseText, QObject::tr("License") ); } } void AboutWindow::updateLibrariesVersions() { QString libsText = QString("<p> Qt %1 </p>" "<p> Boost %2 </p>" "<p> Glew %3 </p>" "<p> OpenGL %4 </p>" "<p> Cairo %5 </p>") .arg( _gui->getQtVersion() ) .arg( _gui->getBoostVersion() ) .arg( _gui->getGlewVersion() ) .arg( _gui->getOpenGLVersion() ) .arg( _gui->getCairoVersion() ); _libsText->setText(libsText); } <commit_msg>We’re in 2014!<commit_after>// Natron /* 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 "AboutWindow.h" #include "Global/Macros.h" CLANG_DIAG_OFF(deprecated) #include <QTextBrowser> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTabWidget> #include <QLabel> #include <QFile> #include <QTextCodec> CLANG_DIAG_ON(deprecated) #include "Global/GlobalDefines.h" #include "Global/GitVersion.h" #include "Gui/Button.h" #include "Gui/Gui.h" AboutWindow::AboutWindow(Gui* gui, QWidget* parent) : QDialog(parent) , _gui(gui) { setWindowTitle(QObject::tr("About ") + NATRON_APPLICATION_NAME); _mainLayout = new QVBoxLayout(this); setLayout(_mainLayout); _iconLabel = new QLabel(this); _iconLabel->setPixmap( QPixmap(NATRON_APPLICATION_ICON_PATH).scaled(128, 128) ); _mainLayout->addWidget(_iconLabel); _tabWidget = new QTabWidget(this); _mainLayout->addWidget(_tabWidget); _buttonContainer = new QWidget(this); _buttonLayout = new QHBoxLayout(_buttonContainer); _buttonLayout->addStretch(); _closeButton = new Button(QObject::tr("Close"),_buttonContainer); QObject::connect( _closeButton, SIGNAL( clicked() ), this, SLOT( accept() ) ); _buttonLayout->addWidget(_closeButton); _mainLayout->addWidget(_buttonContainer); ///filling tabs now _aboutText = new QTextBrowser(_tabWidget); _aboutText->setOpenExternalLinks(true); QString aboutText; QString customBuild(NATRON_CUSTOM_BUILD_USER_NAME); if (!customBuild.isEmpty()) { aboutText = QString("<p>%1 custom build for %2 %3.</p>") .arg(NATRON_APPLICATION_NAME) .arg(customBuild) #ifdef DEBUG .arg("(debug)"); #else #ifdef NDEBUG // release with asserts disabled (should be the *real* release) .arg(""); #else // release with asserts enabled .arg("(opt)"); #endif #endif } else { aboutText = QString("<p>%1 version %2 %3 %4.</p>") .arg(NATRON_APPLICATION_NAME) .arg(NATRON_VERSION_STRING) .arg(NATRON_DEVELOPMENT_STATUS) #ifdef DEBUG .arg("(debug)"); #else #ifdef NDEBUG // release with asserts disabled (should be the *real* release) .arg(""); #else // release with asserts enabled .arg("(opt)"); #endif #endif } QString endAbout = QString("<p>This version was generated from the source code branch %3" " at commit %4.</p>" "<p>Copyright (C) 2014 the %1 developers.</p>" "<p>This is free software. You may redistribute copies of it " "under the terms of the <a href=\"http://www.mozilla.org/MPL/2.0/\">" "<font color=\"orange\">MPL Mozilla Public License</font></a>. " "There is NO WARRANTY, to the extent permitted by law.</p>" "<p>See <a href=\"%2\"><font color=\"orange\">%1 's website </font></a>" "for more information on this software.</p>") .arg(NATRON_APPLICATION_NAME) // %1 .arg("https://natron.inria.fr") // %2 .arg(GIT_BRANCH) // %3 .arg(GIT_COMMIT); // %4 aboutText.append(endAbout); if (!strcmp(NATRON_DEVELOPMENT_STATUS, NATRON_DEVELOPMENT_ALPHA)) { QString toAppend = QString("<p>Note: This software is currently in alpha version, meaning there are missing features," " bugs and untested stuffs. If you feel like reporting a bug, please do so " "on the <a href=\"%1\"><font color=\"orange\"> issue tracker.</font></a></p>") .arg("https://github.com/MrKepzie/Natron/issues"); // %1 ; } else if (!strcmp(NATRON_DEVELOPMENT_STATUS, NATRON_DEVELOPMENT_BETA)) { QString toAppend = QString("<p>Note: This software is currently under beta testing, meaning there are " " bugs and untested stuffs. If you feel like reporting a bug, please do so " "on the <a href=\"%1\"><font color=\"orange\"> issue tracker.</font></a></p>") .arg("https://github.com/MrKepzie/Natron/issues"); // %1 ; } else if (!strcmp(NATRON_DEVELOPMENT_STATUS, NATRON_DEVELOPMENT_RELEASE_CANDIDATE)) { QString toAppend = QString("The version of this sofware is a release candidate, which means it has the potential of becoming " "the future stable release but might still have some bugs."); aboutText.append(toAppend); } _aboutText->setText(aboutText); _tabWidget->addTab( _aboutText, QObject::tr("About") ); _libsText = new QTextBrowser(_tabWidget); _libsText->setOpenExternalLinks(true); QString libsText = QString("<p> Qt %1 </p>" "<p> Boost %2 </p>" "<p> GLEW %3 </p>" "<p> OpenGL %4 </p>" "<p> Cairo %5 </p>") .arg( gui->getQtVersion() ) .arg( gui->getBoostVersion() ) .arg( gui->getGlewVersion() ) .arg( gui->getOpenGLVersion() ) .arg( gui->getCairoVersion() ); _libsText->setText(libsText); _tabWidget->addTab( _libsText, QObject::tr("Libraries") ); _teamText = new QTextBrowser(_tabWidget); _teamText->setOpenExternalLinks(false); { QFile team_file(":CONTRIBUTORS.txt"); team_file.open(QIODevice::ReadOnly | QIODevice::Text); _teamText->setText( QTextCodec::codecForName("UTF-8")->toUnicode( team_file.readAll() ) ); _tabWidget->addTab( _teamText, QObject::tr("Contributors") ); _licenseText = new QTextBrowser(_tabWidget); _licenseText->setOpenExternalLinks(false); } { QFile license(":LICENSE.txt"); license.open(QIODevice::ReadOnly | QIODevice::Text); _licenseText->setText( QTextCodec::codecForName("UTF-8")->toUnicode( license.readAll() ) ); _tabWidget->addTab( _licenseText, QObject::tr("License") ); } } void AboutWindow::updateLibrariesVersions() { QString libsText = QString("<p> Qt %1 </p>" "<p> Boost %2 </p>" "<p> Glew %3 </p>" "<p> OpenGL %4 </p>" "<p> Cairo %5 </p>") .arg( _gui->getQtVersion() ) .arg( _gui->getBoostVersion() ) .arg( _gui->getGlewVersion() ) .arg( _gui->getOpenGLVersion() ) .arg( _gui->getCairoVersion() ); _libsText->setText(libsText); } <|endoftext|>
<commit_before>#include "kernel.h" #include "geometries.h" #include "ilwisdata.h" #include "ellipsoid.h" #include "geodeticdatum.h" #include "projection.h" #include "coordinatesystem.h" #include "conventionalcoordinatesystem.h" #include "proj4parameters.h" using namespace Ilwis; ConventionalCoordinateSystem::ConventionalCoordinateSystem() : _unit("meter") { } ConventionalCoordinateSystem::ConventionalCoordinateSystem(const Resource &resource) : CoordinateSystem(resource) { } ConventionalCoordinateSystem::~ConventionalCoordinateSystem() { _projection.set(0); _ellipsoid.set(0); } Coordinate ConventionalCoordinateSystem::coord2coord(const ICoordinateSystem &sourceCs, const Coordinate &crdSource) const { if (sourceCs->id() == id()) // the 'real'isEqual test is too expensive here, as this method can be called 100000's of times (resample) return crdSource; LatLon ll = sourceCs->isLatLon() ? LatLon(crdSource.y,crdSource.x) : sourceCs->coord2latlon(crdSource); if ( ll.isValid()) { return latlon2coord(ll); } return Coordinate(); } LatLon ConventionalCoordinateSystem::coord2latlon(const Coordinate &crdSource) const { LatLon pl = _projection->coord2latlon(crdSource); if (!pl.isValid()) return llUNDEF; if (abs(pl.lon()) > 90) return llUNDEF; return pl; } Coordinate ConventionalCoordinateSystem::latlon2coord(const LatLon &ll) const { Coordinate xy = _projection->latlon2coord(ll); if (xy == crdUNDEF) return crdUNDEF; return xy; } bool ConventionalCoordinateSystem::isEqual(const IlwisObject *obj) const { if ( !obj || !hasType(obj->ilwisType(), itCONVENTIONALCOORDSYSTEM)) return false; if(id() == obj->id()) return true; const ConventionalCoordinateSystem *csy = static_cast<const ConventionalCoordinateSystem *>(obj); if ( !csy->isValid()) return false; if ( ellipsoid().isValid() && ellipsoid()->isEqual(csy->ellipsoid())) { if ( csy->projection().isValid() && projection().isValid()){ // special case; in general datums will be checked first if (csy->projection()->code() == "longlat" && projection()->code() == "longlat") return true; } if ( datum() && csy->datum()) { if (datum()->code() == csy->datum()->code()) return true; } else { if ( csy->projection().isValid() && projection().isValid()) { return csy->projection()->isEqual(projection().ptr()); } } } return false; } const std::unique_ptr<GeodeticDatum>& ConventionalCoordinateSystem::datum() const { return _datum; } void ConventionalCoordinateSystem::setDatum(GeodeticDatum *datum) { _datum.reset(datum); } IEllipsoid ConventionalCoordinateSystem::ellipsoid() const { return _ellipsoid; } void ConventionalCoordinateSystem::setEllipsoid(const IEllipsoid &ell) { _ellipsoid = ell; } bool ConventionalCoordinateSystem::isLatLon() const { return _unit == "degree"; } IlwisTypes ConventionalCoordinateSystem::ilwisType() const { return itCONVENTIONALCOORDSYSTEM; } bool ConventionalCoordinateSystem::isValid() const { bool ok1 = _projection.isValid(); bool ok2 =_ellipsoid.isValid(); return ok1 && ok2; } void ConventionalCoordinateSystem::setProjection(const IProjection &proj) { _projection = proj; if ( proj->code().contains("longlat") || proj->code().contains("latlon")) _unit = "degree"; } IProjection ConventionalCoordinateSystem::projection() const { return _projection; } bool ConventionalCoordinateSystem::prepare() { return CoordinateSystem::prepare(); } bool ConventionalCoordinateSystem::prepare(const QString &parms) { Proj4Parameters proj4(parms); QString ell = proj4["ellps"]; _ellipsoid = new Ellipsoid(); if ( ell != sUNDEF) { _ellipsoid.prepare("code=" + ell); } else { QString laxis = proj4["a"]; if ( laxis != sUNDEF) { QString saxis = proj4["b"]; bool ok; double a = laxis.toDouble(&ok); if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name()); double b = saxis.toDouble(&ok); if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name()); double f = (a - b) / a; _ellipsoid->setEllipsoid(a, f); _ellipsoid->setName("Custom Ellipsoid for " + name()); } } if ( proj4.hasDatum()) { _datum.reset(new GeodeticDatum()); if ( proj4["dx"] != sUNDEF) { _datum->set7TransformationParameters(proj4["dx"].toDouble(), proj4["dy"].toDouble(), proj4["dz"].toDouble(), proj4["rx"].toDouble(), proj4["ry"].toDouble(), proj4["rz"].toDouble(), proj4["dscale"].toDouble()); } } QString code = proj4["proj"]; if ( code == sUNDEF) { kernel()->issues()->log(TR(ERR_INVALID_PROPERTY_FOR_2).arg("projection name", name())); return false; } code = "code=" + code; Resource prj = mastercatalog()->name2Resource(code, itPROJECTION); if ( !prj.isValid()) { return ERROR1(ERR_COULDNT_CREATE_OBJECT_FOR_1,"projection " + code ); } bool ok =_projection.prepare(prj.id()); _projection->setCoordinateSystem(this); if ( _projection.isValid()) { ok = _projection->prepare(parms); } if ( ok && (_projection->code().contains("longlat") || _projection->code().contains("latlon"))) _unit = "degrees"; return ok; } <commit_msg>fixed #26 "degree" -> "degrees" in conventionalcoordinatesystem<commit_after>#include "kernel.h" #include "geometries.h" #include "ilwisdata.h" #include "ellipsoid.h" #include "geodeticdatum.h" #include "projection.h" #include "coordinatesystem.h" #include "conventionalcoordinatesystem.h" #include "proj4parameters.h" using namespace Ilwis; ConventionalCoordinateSystem::ConventionalCoordinateSystem() : _unit("meter") { } ConventionalCoordinateSystem::ConventionalCoordinateSystem(const Resource &resource) : CoordinateSystem(resource) { } ConventionalCoordinateSystem::~ConventionalCoordinateSystem() { _projection.set(0); _ellipsoid.set(0); } Coordinate ConventionalCoordinateSystem::coord2coord(const ICoordinateSystem &sourceCs, const Coordinate &crdSource) const { if (sourceCs->id() == id()) // the 'real'isEqual test is too expensive here, as this method can be called 100000's of times (resample) return crdSource; LatLon ll = sourceCs->isLatLon() ? LatLon(crdSource.y,crdSource.x) : sourceCs->coord2latlon(crdSource); if ( ll.isValid()) { return latlon2coord(ll); } return Coordinate(); } LatLon ConventionalCoordinateSystem::coord2latlon(const Coordinate &crdSource) const { LatLon pl = _projection->coord2latlon(crdSource); if (!pl.isValid()) return llUNDEF; if (abs(pl.lon()) > 90) return llUNDEF; return pl; } Coordinate ConventionalCoordinateSystem::latlon2coord(const LatLon &ll) const { Coordinate xy = _projection->latlon2coord(ll); if (xy == crdUNDEF) return crdUNDEF; return xy; } bool ConventionalCoordinateSystem::isEqual(const IlwisObject *obj) const { if ( !obj || !hasType(obj->ilwisType(), itCONVENTIONALCOORDSYSTEM)) return false; if(id() == obj->id()) return true; const ConventionalCoordinateSystem *csy = static_cast<const ConventionalCoordinateSystem *>(obj); if ( !csy->isValid()) return false; if ( ellipsoid().isValid() && ellipsoid()->isEqual(csy->ellipsoid())) { if ( csy->projection().isValid() && projection().isValid()){ // special case; in general datums will be checked first if (csy->projection()->code() == "longlat" && projection()->code() == "longlat") return true; } if ( datum() && csy->datum()) { if (datum()->code() == csy->datum()->code()) return true; } else { if ( csy->projection().isValid() && projection().isValid()) { return csy->projection()->isEqual(projection().ptr()); } } } return false; } const std::unique_ptr<GeodeticDatum>& ConventionalCoordinateSystem::datum() const { return _datum; } void ConventionalCoordinateSystem::setDatum(GeodeticDatum *datum) { _datum.reset(datum); } IEllipsoid ConventionalCoordinateSystem::ellipsoid() const { return _ellipsoid; } void ConventionalCoordinateSystem::setEllipsoid(const IEllipsoid &ell) { _ellipsoid = ell; } bool ConventionalCoordinateSystem::isLatLon() const { return _unit == "degrees"; } IlwisTypes ConventionalCoordinateSystem::ilwisType() const { return itCONVENTIONALCOORDSYSTEM; } bool ConventionalCoordinateSystem::isValid() const { bool ok1 = _projection.isValid(); bool ok2 =_ellipsoid.isValid(); return ok1 && ok2; } void ConventionalCoordinateSystem::setProjection(const IProjection &proj) { _projection = proj; if ( proj->code().contains("longlat") || proj->code().contains("latlon")) _unit = "degrees"; } IProjection ConventionalCoordinateSystem::projection() const { return _projection; } bool ConventionalCoordinateSystem::prepare() { return CoordinateSystem::prepare(); } bool ConventionalCoordinateSystem::prepare(const QString &parms) { Proj4Parameters proj4(parms); QString ell = proj4["ellps"]; _ellipsoid = new Ellipsoid(); if ( ell != sUNDEF) { _ellipsoid.prepare("code=" + ell); } else { QString laxis = proj4["a"]; if ( laxis != sUNDEF) { QString saxis = proj4["b"]; bool ok; double a = laxis.toDouble(&ok); if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name()); double b = saxis.toDouble(&ok); if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name()); double f = (a - b) / a; _ellipsoid->setEllipsoid(a, f); _ellipsoid->setName("Custom Ellipsoid for " + name()); } } if ( proj4.hasDatum()) { _datum.reset(new GeodeticDatum()); if ( proj4["dx"] != sUNDEF) { _datum->set7TransformationParameters(proj4["dx"].toDouble(), proj4["dy"].toDouble(), proj4["dz"].toDouble(), proj4["rx"].toDouble(), proj4["ry"].toDouble(), proj4["rz"].toDouble(), proj4["dscale"].toDouble()); } } QString code = proj4["proj"]; if ( code == sUNDEF) { kernel()->issues()->log(TR(ERR_INVALID_PROPERTY_FOR_2).arg("projection name", name())); return false; } code = "code=" + code; Resource prj = mastercatalog()->name2Resource(code, itPROJECTION); if ( !prj.isValid()) { return ERROR1(ERR_COULDNT_CREATE_OBJECT_FOR_1,"projection " + code ); } bool ok =_projection.prepare(prj.id()); _projection->setCoordinateSystem(this); if ( _projection.isValid()) { ok = _projection->prepare(parms); } if ( ok && (_projection->code().contains("longlat") || _projection->code().contains("latlon"))) _unit = "degrees"; return ok; } <|endoftext|>
<commit_before>// // MFM.cpp // Clock Signal // // Created by Thomas Harte on 18/09/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #include "Encoder.hpp" #include "Constants.hpp" #include "../../Track/PCMTrack.hpp" #include "../../../../NumberTheory/CRC.hpp" #include <cassert> #include <set> using namespace Storage::Encodings::MFM; enum class SurfaceItem { Mark, Data }; class MFMEncoder: public Encoder { public: MFMEncoder(std::vector<bool> &target) : Encoder(target) {} virtual ~MFMEncoder() {} void add_byte(uint8_t input) { crc_generator_.add(input); uint16_t spread_value = static_cast<uint16_t>( ((input & 0x01) << 0) | ((input & 0x02) << 1) | ((input & 0x04) << 2) | ((input & 0x08) << 3) | ((input & 0x10) << 4) | ((input & 0x20) << 5) | ((input & 0x40) << 6) | ((input & 0x80) << 7) ); uint16_t or_bits = static_cast<uint16_t>((spread_value << 1) | (spread_value >> 1) | (last_output_ << 15)); uint16_t output = spread_value | ((~or_bits) & 0xaaaa); output_short(output); } void add_index_address_mark() { for(int c = 0; c < 3; c++) output_short(MFMIndexSync); add_byte(IndexAddressByte); } void add_ID_address_mark() { output_sync(); add_byte(IDAddressByte); } void add_data_address_mark() { output_sync(); add_byte(DataAddressByte); } void add_deleted_data_address_mark() { output_sync(); add_byte(DeletedDataAddressByte); } size_t item_size(SurfaceItem item) { switch(item) { case SurfaceItem::Mark: return 8; // Three syncs plus the mark type. case SurfaceItem::Data: return 2; // Just a single encoded byte. default: assert(false); } } private: uint16_t last_output_; void output_short(uint16_t value) { last_output_ = value; Encoder::output_short(value); } void output_sync() { for(int c = 0; c < 3; c++) output_short(MFMSync); crc_generator_.set_value(MFMPostSyncCRCValue); } }; class FMEncoder: public Encoder { // encodes each 16-bit part as clock, data, clock, data [...] public: FMEncoder(std::vector<bool> &target) : Encoder(target) {} void add_byte(uint8_t input) { crc_generator_.add(input); output_short( static_cast<uint16_t>( ((input & 0x01) << 0) | ((input & 0x02) << 1) | ((input & 0x04) << 2) | ((input & 0x08) << 3) | ((input & 0x10) << 4) | ((input & 0x20) << 5) | ((input & 0x40) << 6) | ((input & 0x80) << 7) | 0xaaaa )); } void add_index_address_mark() { crc_generator_.reset(); crc_generator_.add(IndexAddressByte); output_short(FMIndexAddressMark); } void add_ID_address_mark() { crc_generator_.reset(); crc_generator_.add(IDAddressByte); output_short(FMIDAddressMark); } void add_data_address_mark() { crc_generator_.reset(); crc_generator_.add(DataAddressByte); output_short(FMDataAddressMark); } void add_deleted_data_address_mark() { crc_generator_.reset(); crc_generator_.add(DeletedDataAddressByte); output_short(FMDeletedDataAddressMark); } size_t item_size(SurfaceItem item) { // Marks are just slightly-invalid bytes, so everything is the same length. return 2; } }; template<class T> std::shared_ptr<Storage::Disk::Track> GetTrackWithSectors( const std::vector<const Sector *> &sectors, std::size_t post_index_address_mark_bytes, uint8_t post_index_address_mark_value, std::size_t pre_address_mark_bytes, std::size_t post_address_mark_bytes, uint8_t post_address_mark_value, std::size_t pre_data_mark_bytes, std::size_t post_data_bytes, uint8_t post_data_value, std::size_t expected_track_bytes) { Storage::Disk::PCMSegment segment; segment.data.reserve(expected_track_bytes * 8); T shifter(segment.data); // Make a pre-estimate of output size, in case any of the idealised gaps // provided need to be shortened. const size_t data_size = shifter.item_size(SurfaceItem::Data); const size_t mark_size = shifter.item_size(SurfaceItem::Mark); const size_t max_size = (expected_track_bytes + (expected_track_bytes / 10)) * 8; size_t total_sector_bytes = 0; for(const auto sector : sectors) { total_sector_bytes += size_t(128 << sector->size) + 2; } while(true) { const size_t size = mark_size + post_index_address_mark_bytes * data_size + total_sector_bytes * data_size + sectors.size() * ( (pre_address_mark_bytes + 6 + post_address_mark_bytes + pre_data_mark_bytes + post_data_bytes) * data_size + 2 * mark_size ); // If this track already fits, do nothing. if(size*8 < max_size) break; // If all gaps are already zero, do nothing. if(!post_index_address_mark_bytes && !pre_address_mark_bytes && !post_address_mark_bytes && !pre_data_mark_bytes && !post_data_bytes) break; // Very simple solution: try halving all gaps. post_index_address_mark_bytes >>= 1; pre_address_mark_bytes >>= 1; post_address_mark_bytes >>= 1; pre_data_mark_bytes >>= 1; post_data_bytes >>= 1; } // Output the index mark. shifter.add_index_address_mark(); // Add the post-index mark. for(std::size_t c = 0; c < post_index_address_mark_bytes; c++) shifter.add_byte(post_index_address_mark_value); // Add sectors. for(const Sector *sector : sectors) { // Gap. for(std::size_t c = 0; c < pre_address_mark_bytes; c++) shifter.add_byte(0x00); // Sector header. shifter.add_ID_address_mark(); shifter.add_byte(sector->address.track); shifter.add_byte(sector->address.side); shifter.add_byte(sector->address.sector); shifter.add_byte(sector->size); shifter.add_crc(sector->has_header_crc_error); // Gap. for(std::size_t c = 0; c < post_address_mark_bytes; c++) shifter.add_byte(post_address_mark_value); for(std::size_t c = 0; c < pre_data_mark_bytes; c++) shifter.add_byte(0x00); // Data, if attached. // TODO: allow for weak/fuzzy data. if(!sector->samples.empty()) { if(sector->is_deleted) shifter.add_deleted_data_address_mark(); else shifter.add_data_address_mark(); std::size_t c = 0; std::size_t declared_length = static_cast<std::size_t>(128 << sector->size); for(c = 0; c < sector->samples[0].size() && c < declared_length; c++) { shifter.add_byte(sector->samples[0][c]); } for(; c < declared_length; c++) { shifter.add_byte(0x00); } shifter.add_crc(sector->has_data_crc_error); } // Gap. for(std::size_t c = 0; c < post_data_bytes; c++) shifter.add_byte(post_data_value); } while(segment.data.size() < expected_track_bytes*8) shifter.add_byte(0x00); // Allow the amount of data written to be up to 10% more than the expected size. Which is generous. if(segment.data.size() > max_size) segment.data.resize(max_size); return std::make_shared<Storage::Disk::PCMTrack>(std::move(segment)); } Encoder::Encoder(std::vector<bool> &target) : target_(target) {} void Encoder::output_short(uint16_t value) { uint16_t mask = 0x8000; while(mask) { target_.push_back(!!(value & mask)); mask >>= 1; } } void Encoder::add_crc(bool incorrectly) { uint16_t crc_value = crc_generator_.get_value(); add_byte(crc_value >> 8); add_byte((crc_value & 0xff) ^ (incorrectly ? 1 : 0)); } const std::size_t Storage::Encodings::MFM::DefaultSectorGapLength = std::numeric_limits<std::size_t>::max(); static std::vector<const Sector *> sector_pointers(const std::vector<Sector> &sectors) { std::vector<const Sector *> pointers; for(const Sector &sector: sectors) { pointers.push_back(&sector); } return pointers; } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetFMTrackWithSectors(const std::vector<Sector> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<FMEncoder>( sector_pointers(sectors), 26, 0xff, 6, 11, 0xff, 6, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 27, 0xff, 6250); // i.e. 250kbps (including clocks) * 60 = 15000kpm, at 300 rpm => 50 kbits/rotation => 6250 bytes/rotation } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetFMTrackWithSectors(const std::vector<const Sector *> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<FMEncoder>( sectors, 26, 0xff, 6, 11, 0xff, 6, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 27, 0xff, 6250); // i.e. 250kbps (including clocks) * 60 = 15000kpm, at 300 rpm => 50 kbits/rotation => 6250 bytes/rotation } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetMFMTrackWithSectors(const std::vector<Sector> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<MFMEncoder>( sector_pointers(sectors), 50, 0x4e, 12, 22, 0x4e, 12, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 54, 0xff, 12500); // unintelligently: double the single-density bytes/rotation (or: 500kbps @ 300 rpm) } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetMFMTrackWithSectors(const std::vector<const Sector *> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<MFMEncoder>( sectors, 50, 0x4e, 12, 22, 0x4e, 12, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 54, 0xff, 12500); // unintelligently: double the single-density bytes/rotation (or: 500kbps @ 300 rpm) } std::unique_ptr<Encoder> Storage::Encodings::MFM::GetMFMEncoder(std::vector<bool> &target) { return std::make_unique<MFMEncoder>(target); } std::unique_ptr<Encoder> Storage::Encodings::MFM::GetFMEncoder(std::vector<bool> &target) { return std::make_unique<FMEncoder>(target); } <commit_msg>Ensure no possible return without value.<commit_after>// // MFM.cpp // Clock Signal // // Created by Thomas Harte on 18/09/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #include "Encoder.hpp" #include "Constants.hpp" #include "../../Track/PCMTrack.hpp" #include "../../../../NumberTheory/CRC.hpp" #include <cassert> #include <set> using namespace Storage::Encodings::MFM; enum class SurfaceItem { Mark, Data }; class MFMEncoder: public Encoder { public: MFMEncoder(std::vector<bool> &target) : Encoder(target) {} virtual ~MFMEncoder() {} void add_byte(uint8_t input) { crc_generator_.add(input); uint16_t spread_value = static_cast<uint16_t>( ((input & 0x01) << 0) | ((input & 0x02) << 1) | ((input & 0x04) << 2) | ((input & 0x08) << 3) | ((input & 0x10) << 4) | ((input & 0x20) << 5) | ((input & 0x40) << 6) | ((input & 0x80) << 7) ); uint16_t or_bits = static_cast<uint16_t>((spread_value << 1) | (spread_value >> 1) | (last_output_ << 15)); uint16_t output = spread_value | ((~or_bits) & 0xaaaa); output_short(output); } void add_index_address_mark() { for(int c = 0; c < 3; c++) output_short(MFMIndexSync); add_byte(IndexAddressByte); } void add_ID_address_mark() { output_sync(); add_byte(IDAddressByte); } void add_data_address_mark() { output_sync(); add_byte(DataAddressByte); } void add_deleted_data_address_mark() { output_sync(); add_byte(DeletedDataAddressByte); } size_t item_size(SurfaceItem item) { switch(item) { case SurfaceItem::Mark: return 8; // Three syncs plus the mark type. case SurfaceItem::Data: return 2; // Just a single encoded byte. default: assert(false); } return 0; // Should be impossible to reach in debug builds. } private: uint16_t last_output_; void output_short(uint16_t value) { last_output_ = value; Encoder::output_short(value); } void output_sync() { for(int c = 0; c < 3; c++) output_short(MFMSync); crc_generator_.set_value(MFMPostSyncCRCValue); } }; class FMEncoder: public Encoder { // encodes each 16-bit part as clock, data, clock, data [...] public: FMEncoder(std::vector<bool> &target) : Encoder(target) {} void add_byte(uint8_t input) { crc_generator_.add(input); output_short( static_cast<uint16_t>( ((input & 0x01) << 0) | ((input & 0x02) << 1) | ((input & 0x04) << 2) | ((input & 0x08) << 3) | ((input & 0x10) << 4) | ((input & 0x20) << 5) | ((input & 0x40) << 6) | ((input & 0x80) << 7) | 0xaaaa )); } void add_index_address_mark() { crc_generator_.reset(); crc_generator_.add(IndexAddressByte); output_short(FMIndexAddressMark); } void add_ID_address_mark() { crc_generator_.reset(); crc_generator_.add(IDAddressByte); output_short(FMIDAddressMark); } void add_data_address_mark() { crc_generator_.reset(); crc_generator_.add(DataAddressByte); output_short(FMDataAddressMark); } void add_deleted_data_address_mark() { crc_generator_.reset(); crc_generator_.add(DeletedDataAddressByte); output_short(FMDeletedDataAddressMark); } size_t item_size(SurfaceItem item) { // Marks are just slightly-invalid bytes, so everything is the same length. return 2; } }; template<class T> std::shared_ptr<Storage::Disk::Track> GetTrackWithSectors( const std::vector<const Sector *> &sectors, std::size_t post_index_address_mark_bytes, uint8_t post_index_address_mark_value, std::size_t pre_address_mark_bytes, std::size_t post_address_mark_bytes, uint8_t post_address_mark_value, std::size_t pre_data_mark_bytes, std::size_t post_data_bytes, uint8_t post_data_value, std::size_t expected_track_bytes) { Storage::Disk::PCMSegment segment; segment.data.reserve(expected_track_bytes * 8); T shifter(segment.data); // Make a pre-estimate of output size, in case any of the idealised gaps // provided need to be shortened. const size_t data_size = shifter.item_size(SurfaceItem::Data); const size_t mark_size = shifter.item_size(SurfaceItem::Mark); const size_t max_size = (expected_track_bytes + (expected_track_bytes / 10)) * 8; size_t total_sector_bytes = 0; for(const auto sector : sectors) { total_sector_bytes += size_t(128 << sector->size) + 2; } while(true) { const size_t size = mark_size + post_index_address_mark_bytes * data_size + total_sector_bytes * data_size + sectors.size() * ( (pre_address_mark_bytes + 6 + post_address_mark_bytes + pre_data_mark_bytes + post_data_bytes) * data_size + 2 * mark_size ); // If this track already fits, do nothing. if(size*8 < max_size) break; // If all gaps are already zero, do nothing. if(!post_index_address_mark_bytes && !pre_address_mark_bytes && !post_address_mark_bytes && !pre_data_mark_bytes && !post_data_bytes) break; // Very simple solution: try halving all gaps. post_index_address_mark_bytes >>= 1; pre_address_mark_bytes >>= 1; post_address_mark_bytes >>= 1; pre_data_mark_bytes >>= 1; post_data_bytes >>= 1; } // Output the index mark. shifter.add_index_address_mark(); // Add the post-index mark. for(std::size_t c = 0; c < post_index_address_mark_bytes; c++) shifter.add_byte(post_index_address_mark_value); // Add sectors. for(const Sector *sector : sectors) { // Gap. for(std::size_t c = 0; c < pre_address_mark_bytes; c++) shifter.add_byte(0x00); // Sector header. shifter.add_ID_address_mark(); shifter.add_byte(sector->address.track); shifter.add_byte(sector->address.side); shifter.add_byte(sector->address.sector); shifter.add_byte(sector->size); shifter.add_crc(sector->has_header_crc_error); // Gap. for(std::size_t c = 0; c < post_address_mark_bytes; c++) shifter.add_byte(post_address_mark_value); for(std::size_t c = 0; c < pre_data_mark_bytes; c++) shifter.add_byte(0x00); // Data, if attached. // TODO: allow for weak/fuzzy data. if(!sector->samples.empty()) { if(sector->is_deleted) shifter.add_deleted_data_address_mark(); else shifter.add_data_address_mark(); std::size_t c = 0; std::size_t declared_length = static_cast<std::size_t>(128 << sector->size); for(c = 0; c < sector->samples[0].size() && c < declared_length; c++) { shifter.add_byte(sector->samples[0][c]); } for(; c < declared_length; c++) { shifter.add_byte(0x00); } shifter.add_crc(sector->has_data_crc_error); } // Gap. for(std::size_t c = 0; c < post_data_bytes; c++) shifter.add_byte(post_data_value); } while(segment.data.size() < expected_track_bytes*8) shifter.add_byte(0x00); // Allow the amount of data written to be up to 10% more than the expected size. Which is generous. if(segment.data.size() > max_size) segment.data.resize(max_size); return std::make_shared<Storage::Disk::PCMTrack>(std::move(segment)); } Encoder::Encoder(std::vector<bool> &target) : target_(target) {} void Encoder::output_short(uint16_t value) { uint16_t mask = 0x8000; while(mask) { target_.push_back(!!(value & mask)); mask >>= 1; } } void Encoder::add_crc(bool incorrectly) { uint16_t crc_value = crc_generator_.get_value(); add_byte(crc_value >> 8); add_byte((crc_value & 0xff) ^ (incorrectly ? 1 : 0)); } const std::size_t Storage::Encodings::MFM::DefaultSectorGapLength = std::numeric_limits<std::size_t>::max(); static std::vector<const Sector *> sector_pointers(const std::vector<Sector> &sectors) { std::vector<const Sector *> pointers; for(const Sector &sector: sectors) { pointers.push_back(&sector); } return pointers; } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetFMTrackWithSectors(const std::vector<Sector> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<FMEncoder>( sector_pointers(sectors), 26, 0xff, 6, 11, 0xff, 6, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 27, 0xff, 6250); // i.e. 250kbps (including clocks) * 60 = 15000kpm, at 300 rpm => 50 kbits/rotation => 6250 bytes/rotation } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetFMTrackWithSectors(const std::vector<const Sector *> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<FMEncoder>( sectors, 26, 0xff, 6, 11, 0xff, 6, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 27, 0xff, 6250); // i.e. 250kbps (including clocks) * 60 = 15000kpm, at 300 rpm => 50 kbits/rotation => 6250 bytes/rotation } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetMFMTrackWithSectors(const std::vector<Sector> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<MFMEncoder>( sector_pointers(sectors), 50, 0x4e, 12, 22, 0x4e, 12, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 54, 0xff, 12500); // unintelligently: double the single-density bytes/rotation (or: 500kbps @ 300 rpm) } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetMFMTrackWithSectors(const std::vector<const Sector *> &sectors, std::size_t sector_gap_length, uint8_t sector_gap_filler_byte) { return GetTrackWithSectors<MFMEncoder>( sectors, 50, 0x4e, 12, 22, 0x4e, 12, (sector_gap_length != DefaultSectorGapLength) ? sector_gap_length : 54, 0xff, 12500); // unintelligently: double the single-density bytes/rotation (or: 500kbps @ 300 rpm) } std::unique_ptr<Encoder> Storage::Encodings::MFM::GetMFMEncoder(std::vector<bool> &target) { return std::make_unique<MFMEncoder>(target); } std::unique_ptr<Encoder> Storage::Encodings::MFM::GetFMEncoder(std::vector<bool> &target) { return std::make_unique<FMEncoder>(target); } <|endoftext|>
<commit_before>//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef CHROMOSOME_HPP #define CHROMOSOME_HPP namespace galgo { //================================================================================================= template <typename T, int N = 16> class Chromosome { static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend."); static_assert(N > 0 && N <= 64, "number of bits cannot be ouside interval [1,64], please choose an integer within this interval."); public: // constructor Chromosome(const GeneticAlgorithm<T,N>& ga); // copy constructor Chromosome(const Chromosome<T,N>& rhs); // create new chromosome void create(); // initialize chromosome void initialize(); // evaluate chromosome void evaluate(); // reset chromosome void reset(); // set or replace kth gene by a new one void setGene(int k); // initialize or replace kth gene by a know value void initGene(int k, T value); // add bit to chromosome void addBit(char bit); // initialize or replace an existing chromosome bit void setBit(char bit, int pos); // flip an existing chromosome bit void flipBit(int pos); // get chromosome bit char getBit(int pos) const; // initialize or replace a portion of bits with a portion of another chromosome void setPortion(const Chromosome<T,N>& x, int start, int end); // initialize or replace a portion of bits with a portion of another chromosome void setPortion(const Chromosome<T,N>& x, int start); // get parameter value(s) from chromosome const std::vector<T>& getParam() const; // get objective function result const std::vector<T>& getResult() const; // get the total sum of all objective function(s) result T getTotal() const; // get constraint value(s) const std::vector<T> getConstraint() const; // return chromosome size in number of bits int size() const; // return number of chromosome bits to mutate T mutrate() const; // return number of genes in chromosome int nbgene() const; // return numero of generation this chromosome belongs to int nogen() const; // return lower bound(s) const std::vector<T>& lowerBound() const; // return upper bound(s) const std::vector<T>& upperBound() const; private: std::vector<T> param; // estimated parameters std::vector<T> result; // chromosome objective function(s) result std::string chr; // string of bits representing chromosome const GeneticAlgorithm<T,N>* ptr = nullptr; // pointer to genetic algorithm public: T fitness; // chromosome fitness, objective function(s) result that can be modified (adapted to constraint(s), set to positive values, etc...) private: T total; // total sum of objective function(s) result int chrsize; // chromosome size (in number of bits) int numgen; // numero of generation }; /*-------------------------------------------------------------------------------------------------*/ // constructor template <typename T, int N> Chromosome<T,N>::Chromosome(const GeneticAlgorithm<T,N>& ga) { param.resize(ga.nbparam); ptr = &ga; chrsize = ga.nbparam * N; numgen = ga.nogen; } /*-------------------------------------------------------------------------------------------------*/ // copy constructor template <typename T, int N> Chromosome<T,N>::Chromosome(const Chromosome<T,N>& rhs) { param = rhs.param; result = rhs.result; chr = rhs.chr; // re-initializing fitness to its original value fitness = rhs.total; total = rhs.total; ptr = rhs.ptr; chrsize = rhs.chrsize; numgen = rhs.numgen; } /*-------------------------------------------------------------------------------------------------*/ // create new chromosome template <typename T, int N> inline void Chromosome<T,N>::create() { chr.clear(); // encoding chromosome: constructing chromosome string from a long long unsigned integer for (int i = 0; i < ptr->nbparam; ++i) { std::string s = GetBinary(ptr->udistrib(rng)); chr.append(s.substr(s.size() - N, N)); } } /*-------------------------------------------------------------------------------------------------*/ // initialize chromosome (from known parameter values) template <typename T, int N> inline void Chromosome<T,N>::initialize() { chr.clear(); // encoding chromosome: constructing chromosome string from a long long unsigned integer for (int i = 0; i < ptr->nbparam; ++i) { uint64_t value = ptr->MAXVAL * (ptr->initialSet[i] - ptr->lowerBound[i]) / (ptr->upperBound[i] - ptr->lowerBound[i]); chr.append(GetBinary(value)); } } /*-------------------------------------------------------------------------------------------------*/ // evaluate chromosome fitness template <typename T, int N> inline void Chromosome<T,N>::evaluate() { // decoding chromosome: converting chromosome string to real parameters for (int i = 0; i < ptr->nbparam; ++i) { uint64_t value = GetValue(chr.substr(i * N, N)); param[i] = ptr->lowerBound[i] + (value / (T)ptr->MAXVAL) * (ptr->upperBound[i] - ptr->lowerBound[i]); } // computing objective result(s) result = ptr->Objective(param); // computing sum of all results (in case there is not only one objective functions) total = std::accumulate(result.begin(), result.end(), 0.0); // initializing fitness to this total fitness = total; } /*-------------------------------------------------------------------------------------------------*/ // reset chromosome template <typename T, int N> inline void Chromosome<T,N>::reset() { chr.clear(); result = 0.0; total = 0.0; fitness = 0.0; } /*-------------------------------------------------------------------------------------------------*/ // set or replace kth gene by a new one template <typename T, int N> inline void Chromosome<T,N>::setGene(int k) { #ifndef NDEBUG if (k < 0 || k >= ptr->nbparam) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::setGene(int), argument cannot be outside interval [0,nbparam-1], please amend."); } #endif // generating a new gene std::string s = GetBinary(ptr->udistrib(rng)); // adding or replacing gene in chromosome chr.replace(k * N, N, s.substr(s.size() - N, N), 0, N); } /*-------------------------------------------------------------------------------------------------*/ // initialize or replace kth gene by a know value template <typename T, int N> inline void Chromosome<T,N>::initGene(int k, T x) { #ifndef NDEBUG if (k < 0 || k >= ptr->nbparam) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::initGene(int), first argument cannot be outside interval [0,nbparam-1], please amend."); } #endif uint64_t value = ptr->MAXVAL * (x - ptr->lowerBound[k]) / (ptr->upperBound[k] - ptr->lowerBound[k]); // encoding gene std::string s = GetBinary(value); // adding or replacing gene in chromosome chr.replace(k * N, N, s.substr(s.size() - N, N), 0, N); } /*-------------------------------------------------------------------------------------------------*/ // add chromosome bit to chromosome (when constructing a new one) template <typename T, int N> inline void Chromosome<T,N>::addBit(char bit) { chr.push_back(bit); #ifndef NDEBUG if (chr.size() > chrsize) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::setBit(char), exceeding chromosome size."); } #endif } /*-------------------------------------------------------------------------------------------------*/ // initialize or replace an existing chromosome bit template <typename T, int N> inline void Chromosome<T,N>::setBit(char bit, int pos) { #ifndef NDEBUG if (pos >= chrsize) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::replaceBit(char, int), second argument cannot be equal or greater than chromosome size."); } #endif std::stringstream ss; std::string str; ss << bit; ss >> str; chr.replace(pos, 1, str); std::cout << chr << "\n"; } /*-------------------------------------------------------------------------------------------------*/ // flip an existing chromosome bit template <typename T, int N> inline void Chromosome<T,N>::flipBit(int pos) { #ifndef NDEBUG if (pos >= chrsize) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::flipBit(int), argument cannot be equal or greater than chromosome size."); } #endif if (chr[pos] == '0') { chr.replace(pos, 1, "1"); } else { chr.replace(pos, 1, "0"); } } /*-------------------------------------------------------------------------------------------------*/ // get a chromosome bit template <typename T, int N> inline char Chromosome<T,N>::getBit(int pos) const { #ifndef NDEBUG if (pos >= chrsize) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::getBit(int), argument cannot be equal or greater than chromosome size."); } #endif return chr[pos]; } /*-------------------------------------------------------------------------------------------------*/ // initialize or replace a portion of bits with a portion of another chromosome (from position start to position end included) template <typename T, int N> inline void Chromosome<T,N>::setPortion(const Chromosome<T,N>& x, int start, int end) { #ifndef NDEBUG if (start > chrsize) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::setPortion(const Chromosome<T>&, int, int), second argument cannot be greater than chromosome size."); } #endif chr.replace(start, end - start + 1, x.chr, start, end - start + 1); } /*-------------------------------------------------------------------------------------------------*/ // initialize or replace a portion of bits with a portion of another chromosome (from position start to the end of he chromosome) template <typename T, int N> inline void Chromosome<T,N>::setPortion(const Chromosome<T,N>& x, int start) { #ifndef NDEBUG if (start > chrsize) { throw std::invalid_argument("Error: in galgo::Chromosome<T>::setPortion(const Chromosome<T>&, int), second argument cannot be greater than chromosome size."); } #endif chr.replace(start, chrsize, x.chr, start, x.chrsize); } /*-------------------------------------------------------------------------------------------------*/ // get parameter value(s) from chromosome template <typename T, int N> inline const std::vector<T>& Chromosome<T,N>::getParam() const { return param; } /*-------------------------------------------------------------------------------------------------*/ // get objective function result template <typename T, int N> inline const std::vector<T>& Chromosome<T,N>::getResult() const { return result; } /*-------------------------------------------------------------------------------------------------*/ // get the total sum of all objective function(s) result template <typename T, int N> inline T Chromosome<T,N>::getTotal() const { return total; } /*-------------------------------------------------------------------------------------------------*/ // get constraint value(s) for this chromosome template <typename T, int N> inline const std::vector<T> Chromosome<T,N>::getConstraint() const { return ptr->Constraint(param); } /*-------------------------------------------------------------------------------------------------*/ // return chromosome size in number of bits template <typename T, int N> inline int Chromosome<T,N>::size() const { return chrsize; } /*-------------------------------------------------------------------------------------------------*/ // return mutation rate template <typename T, int N> inline T Chromosome<T,N>::mutrate() const { return ptr->mutrate; } /*-------------------------------------------------------------------------------------------------*/ // return number of genes in chromosome template <typename T, int N> inline int Chromosome<T,N>::nbgene() const { return ptr->nbparam; } /*-------------------------------------------------------------------------------------------------*/ // return numero of generation this chromosome belongs to template <typename T, int N> inline int Chromosome<T,N>::nogen() const { return numgen; } /*-------------------------------------------------------------------------------------------------*/ // return lower bound(s) template <typename T, int N> inline const std::vector<T>& Chromosome<T,N>::lowerBound() const { return ptr->lowerBound; } /*-------------------------------------------------------------------------------------------------*/ // return upper bound(s) template <typename T, int N> inline const std::vector<T>& Chromosome<T,N>::upperBound() const { return ptr->upperBound; } //================================================================================================= } #endif <commit_msg>Delete Chromosome.hpp<commit_after><|endoftext|>
<commit_before>// // vtTerrainScene - Container class for all of the terrains loaded // // Copyright (c) 2001-2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "vtdata/vtLog.h" #include "TerrainScene.h" #include "Light.h" #include "SkyDome.h" #include "Terrain.h" #include "TimeEngines.h" /////////////////////////////////////////////////////////////////////// /** * A small engine that allows the SkyDome to stay around the Camera. */ class vtSkyTrackEngine : public vtEngine { public: vtSkyTrackEngine(); virtual void Eval(); vtCamera *m_pCamera; }; vtSkyTrackEngine::vtSkyTrackEngine() : vtEngine() { m_pCamera = NULL; } void vtSkyTrackEngine::Eval() { // get the location of the camera and the target (skydome) vtTransform *pTarget = (vtTransform *) GetTarget(); if (!pTarget || !m_pCamera) return; FPoint3 pos1 = m_pCamera->GetTrans(); FPoint3 pos2 = pTarget->GetTrans(); // move the target (skydome) to be centers in XZ on the camera pos2.x = pos1.x; pos2.z = pos1.z; pTarget->SetTrans(pos2); } /////////////////////////////////////////////////////////////////////// // // vtTerrainScene class // vtTerrainScene::vtTerrainScene() { horizon_color.Set(0.70f, 0.85f, 1.0f); azimuth_color.Set(0.12f, 0.32f, 0.70f); m_pTop = NULL; m_pSkyDome = NULL; m_pFirstTerrain = NULL; m_pCurrentTerrain = NULL; m_pTime = NULL; m_pSkyTrack = NULL; m_pSunLight = NULL; m_pAtmosphereGroup = NULL; } vtTerrainScene::~vtTerrainScene() { } void vtTerrainScene::CleanupScene() { vtGetScene()->RemoveEngine(m_pTime); vtGetScene()->RemoveEngine(m_pSkyTrack); delete m_pTime; delete m_pSkyTrack; // no need to do this explicitly, it is done by releasing the scenegraph // if (m_pSkyDome) // m_pSkyDome->Destroy(); while (m_pFirstTerrain) { vtTerrain *del = m_pFirstTerrain; m_pFirstTerrain = m_pFirstTerrain->GetNext(); delete del; } m_pFirstTerrain = NULL; m_pCurrentTerrain = NULL; // get anything left at the top of the scene graph if (m_pTop) m_pTop->Release(); // free some statics vtStructure3d::ReleaseSharedMaterials(); vtRoute::ReleaseMaterials(); } void vtTerrainScene::_CreateSky(const vtStringArray &datapath) { // create the sun VTLOG(" Creating Main Light\n"); vtLight *pLight = new vtLight(); pLight->SetName2("Main Light"); m_pSunLight = new vtMovLight(pLight); m_pSunLight->SetName2("SunLight"); m_pTop->AddChild(m_pSunLight); VTLOG(" Creating SkyDome\n"); m_pAtmosphereGroup = new vtGroup(); m_pAtmosphereGroup->SetName2("Atmosphere Group"); m_pTop->AddChild(m_pAtmosphereGroup); // 'bsc' is the Bright Star Catalog vtString bsc = FindFileOnPaths(datapath, "Sky/bsc.data"); vtString sun = FindFileOnPaths(datapath, "Sky/glow2.png"); vtString moon = FindFileOnPaths(datapath, "Sky/moon5_256.png"); VTLOG(" Stars: '%s'\n", (const char *) bsc); VTLOG(" Sun: '%s'\n", (const char *) sun); VTLOG(" Moon: '%s'\n", (const char *) moon); // create a day-night dome m_pSkyDome = new vtSkyDome(); m_pSkyDome->Create(bsc, 3, 1.0f, sun, moon); // initially unit radius m_pSkyDome->SetDayColors(horizon_color, azimuth_color); m_pSkyDome->SetName2("The Sky"); m_pSkyDome->SetSunLight(GetSunLight()); m_pAtmosphereGroup->AddChild(m_pSkyDome); m_pSkyTrack = new vtSkyTrackEngine(); m_pSkyTrack->SetName2("Sky-Camera-Following"); m_pSkyTrack->m_pCamera = vtGetScene()->GetCamera(); m_pSkyTrack->SetTarget(m_pSkyDome); vtGetScene()->AddEngine(m_pSkyTrack); vtGetScene()->SetBgColor(horizon_color); } /** * Find a terrain whose name begins with a given string. */ vtTerrain *vtTerrainScene::FindTerrainByName(const char *name) { for (vtTerrain *pTerr = m_pFirstTerrain; pTerr; pTerr=pTerr->GetNext()) { if (pTerr->GetName() == name) return pTerr; } return NULL; } void vtTerrainScene::_CreateEngines() { // Set Time in motion m_pTime = new TimeEngine(); m_pTime->SetTarget((TimeTarget *)this); m_pTime->SetName2("Terrain Time"); m_pTime->SetEnabled(false); vtGetScene()->AddEngine(m_pTime); } /** * Call this method once before adding any terrains, to initialize * the vtTerrainScene object. */ vtGroup *vtTerrainScene::BeginTerrainScene() { VTLOG("BeginTerrainScene:\n"); _CreateEngines(); m_pTop = new vtGroup(); m_pTop->SetName2("All Terrain"); // create sky group - this holds all celestial objects _CreateSky(vtTerrain::s_DataPaths); return m_pTop; } /** * Adds a terrain to the scene. */ void vtTerrainScene::AppendTerrain(vtTerrain *pTerrain) { // add to linked list pTerrain->SetNext(m_pFirstTerrain); m_pFirstTerrain = pTerrain; } /** * BuildTerrain constructs all geometry, textures and objects for a given terrain. * * \param bDummy : Ignore this parameter. * \param iError : Returns by reference an error value, or 0 for no error. * \returns A vtGroup which is the top of the terrain scene graph. */ vtGroup *vtTerrainScene::BuildTerrain(vtTerrain *pTerrain) { if (!pTerrain->CreateStep1()) return NULL; // Set time to that of the new terrain m_pSkyDome->SetTime(pTerrain->GetInitialTime()); // Tell the skydome where on the planet we are DPoint2 geo = pTerrain->GetCenterGeoLocation(); m_pSkyDome->SetGeoLocation(geo); if (!pTerrain->CreateStep2(GetSunLight())) return NULL; if (!pTerrain->CreateStep3()) return NULL; if (!pTerrain->CreateStep4()) return NULL; if (!pTerrain->CreateStep5()) return NULL; return pTerrain->GetTopGroup(); } /** * Set the current Terrain for the scene. There can only be one terrain * active a at time. If you have more than one terrain, you can use this * method to switch between them. */ void vtTerrainScene::SetCurrentTerrain(vtTerrain *pTerrain) { if (m_pCurrentTerrain != NULL) { // turn off the scene graph of the previous terrain m_pCurrentTerrain->Enable(false); // turn off the engines specific to the previous terrain m_pCurrentTerrain->ActivateEngines(false); } m_pCurrentTerrain = pTerrain; // if setting to no terrain nothing more to do if (!pTerrain) { m_pSkyDome->SetEnabled(false); m_pTime->SetEnabled(false); return; } // switch m_pTop->AddChild(m_pCurrentTerrain->GetTopGroup()); m_pCurrentTerrain->Enable(true); TParams &param = m_pCurrentTerrain->GetParams(); // switch to the projection of this terrain m_pCurrentTerrain->SetGlobalProjection(); // Set background color to match the ocean vtGetScene()->SetBgColor(m_pCurrentTerrain->GetOceanColor()); // Turn on the engines specific to the new terrain m_pCurrentTerrain->ActivateEngines(true); // Setup the time engine for the new terrain vtTime localtime = pTerrain->GetInitialTime(); // handle the atmosphere _UpdateSkydomeForTerrain(pTerrain); m_pCurrentTerrain->SetFog(param.GetValueBool(STR_FOG)); // Update the time engine, which also calls us back to update the skydome m_pTime->SetTime(localtime); if (param.GetValueBool(STR_TIMEON)) m_pTime->SetSpeed(param.GetValueFloat(STR_TIMESPEED)); else m_pTime->SetSpeed(0.0f); m_pTime->SetEnabled(true); } void vtTerrainScene::_UpdateSkydomeForTerrain(vtTerrain *pTerrain) { TParams &param = m_pCurrentTerrain->GetParams(); // move the sky to fit the new current terrain // use 5x larger than terrain's maximum dimension vtHeightField3d *hf = pTerrain->GetHeightField(); FRECT world_ext = hf->m_WorldExtents; float radius; float width = world_ext.Width(); float depth = world_ext.Height(); float minheight, maxheight; hf->GetHeightExtents(minheight, maxheight); radius = width; if (radius < depth) radius = depth; if (radius < maxheight) radius = maxheight; radius *= 5; float max_radius = 450000; if (radius > max_radius) radius = max_radius; m_pSkyDome->Identity(); m_pSkyDome->Scale3(radius, radius, radius); // Tell the skydome where on the planet we are DPoint2 geo = pTerrain->GetCenterGeoLocation(); m_pSkyDome->SetGeoLocation(geo); // Does this terrain want to show the skydome? bool bDoSky = param.GetValueBool(STR_SKY); m_pSkyDome->SetEnabled(bDoSky); if (bDoSky) { vtString fname = param.GetValueString(STR_SKYTEXTURE, true); if (fname != "") { vtString filename = "Sky/"; filename += fname; vtString skytex = FindFileOnPaths(vtTerrain::s_DataPaths, filename); if (skytex != "") m_pSkyDome->SetTexture(skytex); } } } void vtTerrainScene::SetTime(const vtTime &time) { if (m_pSkyDome) { // TODO? Convert to local time? m_pSkyDome->SetTime(time); // m_pSkyDome->ApplyDayColors(); // TODO? Update the fog color to match the color of the horizon. } } <commit_msg>fixed src docs<commit_after>// // vtTerrainScene - Container class for all of the terrains loaded // // Copyright (c) 2001-2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "vtdata/vtLog.h" #include "TerrainScene.h" #include "Light.h" #include "SkyDome.h" #include "Terrain.h" #include "TimeEngines.h" /////////////////////////////////////////////////////////////////////// /** * A small engine that allows the SkyDome to stay around the Camera. */ class vtSkyTrackEngine : public vtEngine { public: vtSkyTrackEngine(); virtual void Eval(); vtCamera *m_pCamera; }; vtSkyTrackEngine::vtSkyTrackEngine() : vtEngine() { m_pCamera = NULL; } void vtSkyTrackEngine::Eval() { // get the location of the camera and the target (skydome) vtTransform *pTarget = (vtTransform *) GetTarget(); if (!pTarget || !m_pCamera) return; FPoint3 pos1 = m_pCamera->GetTrans(); FPoint3 pos2 = pTarget->GetTrans(); // move the target (skydome) to be centers in XZ on the camera pos2.x = pos1.x; pos2.z = pos1.z; pTarget->SetTrans(pos2); } /////////////////////////////////////////////////////////////////////// // // vtTerrainScene class // vtTerrainScene::vtTerrainScene() { horizon_color.Set(0.70f, 0.85f, 1.0f); azimuth_color.Set(0.12f, 0.32f, 0.70f); m_pTop = NULL; m_pSkyDome = NULL; m_pFirstTerrain = NULL; m_pCurrentTerrain = NULL; m_pTime = NULL; m_pSkyTrack = NULL; m_pSunLight = NULL; m_pAtmosphereGroup = NULL; } vtTerrainScene::~vtTerrainScene() { } void vtTerrainScene::CleanupScene() { vtGetScene()->RemoveEngine(m_pTime); vtGetScene()->RemoveEngine(m_pSkyTrack); delete m_pTime; delete m_pSkyTrack; // no need to do this explicitly, it is done by releasing the scenegraph // if (m_pSkyDome) // m_pSkyDome->Destroy(); while (m_pFirstTerrain) { vtTerrain *del = m_pFirstTerrain; m_pFirstTerrain = m_pFirstTerrain->GetNext(); delete del; } m_pFirstTerrain = NULL; m_pCurrentTerrain = NULL; // get anything left at the top of the scene graph if (m_pTop) m_pTop->Release(); // free some statics vtStructure3d::ReleaseSharedMaterials(); vtRoute::ReleaseMaterials(); } void vtTerrainScene::_CreateSky(const vtStringArray &datapath) { // create the sun VTLOG(" Creating Main Light\n"); vtLight *pLight = new vtLight(); pLight->SetName2("Main Light"); m_pSunLight = new vtMovLight(pLight); m_pSunLight->SetName2("SunLight"); m_pTop->AddChild(m_pSunLight); VTLOG(" Creating SkyDome\n"); m_pAtmosphereGroup = new vtGroup(); m_pAtmosphereGroup->SetName2("Atmosphere Group"); m_pTop->AddChild(m_pAtmosphereGroup); // 'bsc' is the Bright Star Catalog vtString bsc = FindFileOnPaths(datapath, "Sky/bsc.data"); vtString sun = FindFileOnPaths(datapath, "Sky/glow2.png"); vtString moon = FindFileOnPaths(datapath, "Sky/moon5_256.png"); VTLOG(" Stars: '%s'\n", (const char *) bsc); VTLOG(" Sun: '%s'\n", (const char *) sun); VTLOG(" Moon: '%s'\n", (const char *) moon); // create a day-night dome m_pSkyDome = new vtSkyDome(); m_pSkyDome->Create(bsc, 3, 1.0f, sun, moon); // initially unit radius m_pSkyDome->SetDayColors(horizon_color, azimuth_color); m_pSkyDome->SetName2("The Sky"); m_pSkyDome->SetSunLight(GetSunLight()); m_pAtmosphereGroup->AddChild(m_pSkyDome); m_pSkyTrack = new vtSkyTrackEngine(); m_pSkyTrack->SetName2("Sky-Camera-Following"); m_pSkyTrack->m_pCamera = vtGetScene()->GetCamera(); m_pSkyTrack->SetTarget(m_pSkyDome); vtGetScene()->AddEngine(m_pSkyTrack); vtGetScene()->SetBgColor(horizon_color); } /** * Find a terrain whose name begins with a given string. */ vtTerrain *vtTerrainScene::FindTerrainByName(const char *name) { for (vtTerrain *pTerr = m_pFirstTerrain; pTerr; pTerr=pTerr->GetNext()) { if (pTerr->GetName() == name) return pTerr; } return NULL; } void vtTerrainScene::_CreateEngines() { // Set Time in motion m_pTime = new TimeEngine(); m_pTime->SetTarget((TimeTarget *)this); m_pTime->SetName2("Terrain Time"); m_pTime->SetEnabled(false); vtGetScene()->AddEngine(m_pTime); } /** * Call this method once before adding any terrains, to initialize * the vtTerrainScene object. */ vtGroup *vtTerrainScene::BeginTerrainScene() { VTLOG("BeginTerrainScene:\n"); _CreateEngines(); m_pTop = new vtGroup(); m_pTop->SetName2("All Terrain"); // create sky group - this holds all celestial objects _CreateSky(vtTerrain::s_DataPaths); return m_pTop; } /** * Adds a terrain to the scene. */ void vtTerrainScene::AppendTerrain(vtTerrain *pTerrain) { // add to linked list pTerrain->SetNext(m_pFirstTerrain); m_pFirstTerrain = pTerrain; } /** * BuildTerrain constructs all geometry, textures and objects for a given terrain. * * \param pTerrain The terrain to build. * \returns A vtGroup which is the top of the terrain's scene graph. */ vtGroup *vtTerrainScene::BuildTerrain(vtTerrain *pTerrain) { if (!pTerrain->CreateStep1()) return NULL; // Set time to that of the new terrain m_pSkyDome->SetTime(pTerrain->GetInitialTime()); // Tell the skydome where on the planet we are DPoint2 geo = pTerrain->GetCenterGeoLocation(); m_pSkyDome->SetGeoLocation(geo); if (!pTerrain->CreateStep2(GetSunLight())) return NULL; if (!pTerrain->CreateStep3()) return NULL; if (!pTerrain->CreateStep4()) return NULL; if (!pTerrain->CreateStep5()) return NULL; return pTerrain->GetTopGroup(); } /** * Set the current Terrain for the scene. There can only be one terrain * active a at time. If you have more than one terrain, you can use this * method to switch between them. */ void vtTerrainScene::SetCurrentTerrain(vtTerrain *pTerrain) { if (m_pCurrentTerrain != NULL) { // turn off the scene graph of the previous terrain m_pCurrentTerrain->Enable(false); // turn off the engines specific to the previous terrain m_pCurrentTerrain->ActivateEngines(false); } m_pCurrentTerrain = pTerrain; // if setting to no terrain nothing more to do if (!pTerrain) { m_pSkyDome->SetEnabled(false); m_pTime->SetEnabled(false); return; } // switch m_pTop->AddChild(m_pCurrentTerrain->GetTopGroup()); m_pCurrentTerrain->Enable(true); TParams &param = m_pCurrentTerrain->GetParams(); // switch to the projection of this terrain m_pCurrentTerrain->SetGlobalProjection(); // Set background color to match the ocean vtGetScene()->SetBgColor(m_pCurrentTerrain->GetOceanColor()); // Turn on the engines specific to the new terrain m_pCurrentTerrain->ActivateEngines(true); // Setup the time engine for the new terrain vtTime localtime = pTerrain->GetInitialTime(); // handle the atmosphere _UpdateSkydomeForTerrain(pTerrain); m_pCurrentTerrain->SetFog(param.GetValueBool(STR_FOG)); // Update the time engine, which also calls us back to update the skydome m_pTime->SetTime(localtime); if (param.GetValueBool(STR_TIMEON)) m_pTime->SetSpeed(param.GetValueFloat(STR_TIMESPEED)); else m_pTime->SetSpeed(0.0f); m_pTime->SetEnabled(true); } void vtTerrainScene::_UpdateSkydomeForTerrain(vtTerrain *pTerrain) { TParams &param = m_pCurrentTerrain->GetParams(); // move the sky to fit the new current terrain // use 5x larger than terrain's maximum dimension vtHeightField3d *hf = pTerrain->GetHeightField(); FRECT world_ext = hf->m_WorldExtents; float radius; float width = world_ext.Width(); float depth = world_ext.Height(); float minheight, maxheight; hf->GetHeightExtents(minheight, maxheight); radius = width; if (radius < depth) radius = depth; if (radius < maxheight) radius = maxheight; radius *= 5; float max_radius = 450000; if (radius > max_radius) radius = max_radius; m_pSkyDome->Identity(); m_pSkyDome->Scale3(radius, radius, radius); // Tell the skydome where on the planet we are DPoint2 geo = pTerrain->GetCenterGeoLocation(); m_pSkyDome->SetGeoLocation(geo); // Does this terrain want to show the skydome? bool bDoSky = param.GetValueBool(STR_SKY); m_pSkyDome->SetEnabled(bDoSky); if (bDoSky) { vtString fname = param.GetValueString(STR_SKYTEXTURE, true); if (fname != "") { vtString filename = "Sky/"; filename += fname; vtString skytex = FindFileOnPaths(vtTerrain::s_DataPaths, filename); if (skytex != "") m_pSkyDome->SetTexture(skytex); } } } void vtTerrainScene::SetTime(const vtTime &time) { if (m_pSkyDome) { // TODO? Convert to local time? m_pSkyDome->SetTime(time); // m_pSkyDome->ApplyDayColors(); // TODO? Update the fog color to match the color of the horizon. } } <|endoftext|>
<commit_before>#include "atlas/utils/Scene.hpp" #include "atlas/math/Math.hpp" #include "atlas/core/Macros.hpp" #include "atlas/gl/GL.hpp" #include "atlas/utils/Application.hpp" #include "atlas/core/GLM.hpp" namespace atlas { namespace utils { Scene::Scene() { } Scene::~Scene() { } void Scene::mousePressEvent(int button, int action, int modifiers, double xPos, double yPos) { UNUSED(button); UNUSED(action); UNUSED(modifiers); UNUSED(xPos); UNUSED(yPos); } void Scene::mouseMoveEvent(double xPos, double yPos) { UNUSED(xPos); UNUSED(yPos); } void Scene::mouseScrollEvent(double xOffset, double yOffset) { UNUSED(xOffset); UNUSED(yOffset); } void Scene::keyPressEvent(int key, int scancode, int action, int mods) { UNUSED(key); UNUSED(scancode); UNUSED(action); UNUSED(mods); } void Scene::screenResizeEvent(int width, int height) { USING_GLM_NS; glViewport(0, 0, width, height); mProjection = perspective(radians(45.0), (double)width / height, 1.0, 1000.0); } void Scene::onSceneEnter() { } void Scene::onSceneExit() { } void Scene::updateScene(double time) { UNUSED(time); } void Scene::renderScene() { float grey = 161.0f / 255.0f; glClearColor(grey, grey, grey, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); } bool Scene::sceneEnded() { return true; } void Scene::setCursorEnabled(bool enabled) { int en = (enabled) ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED; glfwSetInputMode(Application::getInstance().getCurrentWindow(), GLFW_CURSOR, en); } } }<commit_msg>[brief] Removes GLM macro and header.<commit_after>#include "atlas/utils/Scene.hpp" #include "atlas/math/Math.hpp" #include "atlas/core/Macros.hpp" #include "atlas/gl/GL.hpp" #include "atlas/utils/Application.hpp" namespace atlas { namespace utils { Scene::Scene() { } Scene::~Scene() { } void Scene::mousePressEvent(int button, int action, int modifiers, double xPos, double yPos) { UNUSED(button); UNUSED(action); UNUSED(modifiers); UNUSED(xPos); UNUSED(yPos); } void Scene::mouseMoveEvent(double xPos, double yPos) { UNUSED(xPos); UNUSED(yPos); } void Scene::mouseScrollEvent(double xOffset, double yOffset) { UNUSED(xOffset); UNUSED(yOffset); } void Scene::keyPressEvent(int key, int scancode, int action, int mods) { UNUSED(key); UNUSED(scancode); UNUSED(action); UNUSED(mods); } void Scene::screenResizeEvent(int width, int height) { glViewport(0, 0, width, height); mProjection = glm::perspective(glm::radians(45.0), (double)width / height, 1.0, 1000.0); } void Scene::onSceneEnter() { } void Scene::onSceneExit() { } void Scene::updateScene(double time) { UNUSED(time); } void Scene::renderScene() { float grey = 161.0f / 255.0f; glClearColor(grey, grey, grey, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); } bool Scene::sceneEnded() { return true; } void Scene::setCursorEnabled(bool enabled) { int en = (enabled) ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED; glfwSetInputMode(Application::getInstance().getCurrentWindow(), GLFW_CURSOR, en); } } }<|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. #ifdef __ANDROID__ #include "rust_android_dummy.h" #include <math.h> #include <errno.h> int backtrace(void **array, int size) { return 0; } char **backtrace_symbols(void *const *array, int size) { return 0; } void backtrace_symbols_fd (void *const *array, int size, int fd) {} extern "C" volatile int* __errno_location() { return &errno; } extern "C" float log2f(float f) { return logf( f ) / logf( 2 ); } extern "C" double log2( double n ) { return log( n ) / log( 2 ); } extern "C" void telldir() { } extern "C" void seekdir() { } extern "C" void mkfifo() { } extern "C" void abs() { } extern "C" void labs() { } extern "C" void rand() { } extern "C" void srand() { } extern "C" void atof() { } extern "C" void tgammaf() { } extern "C" int glob(const char *pattern, int flags, int (*errfunc) (const char *epath, int eerrno), glob_t *pglob) { return 0; } extern "C" void globfree(glob_t *pglob) { } #endif <commit_msg>auto merge of #7054 : yichoi/rust/after_jemalloc, r=brson<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. #ifdef __ANDROID__ #include "rust_android_dummy.h" #include <math.h> #include <errno.h> int backtrace(void **array, int size) { return 0; } char **backtrace_symbols(void *const *array, int size) { return 0; } void backtrace_symbols_fd (void *const *array, int size, int fd) {} extern "C" volatile int* __errno_location() { return &errno; } extern "C" float log2f(float f) { return logf( f ) / logf( 2 ); } extern "C" double log2( double n ) { return log( n ) / log( 2 ); } extern "C" void telldir() { } extern "C" void seekdir() { } extern "C" void mkfifo() { } extern "C" void abs() { } extern "C" void labs() { } extern "C" void rand() { } extern "C" void srand() { } extern "C" void atof() { } extern "C" void tgammaf() { } extern "C" int glob(const char *pattern, int flags, int (*errfunc) (const char *epath, int eerrno), glob_t *pglob) { return 0; } extern "C" void globfree(glob_t *pglob) { } extern "C" int pthread_atfork(void (*prefork)(void), void (*postfork_parent)(void), void (*postfork_child)(void)) { return 0; } #endif <|endoftext|>
<commit_before>// MediaInfo - All info about media files // Copyright (C) 2002-2008 Jerome Martinez, [email protected] // // This library is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // 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, see <http://www.gnu.org/licenses/>. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // For user: you can disable or enable it #define MEDIAINFO_DEBUG //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Compilation conditions #include <MediaInfo/Setup.h> #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/MediaInfo.h" #include "MediaInfo/MediaInfo_Internal.h" using namespace ZenLib; //--------------------------------------------------------------------------- namespace MediaInfoLib { //--------------------------------------------------------------------------- //To clarify the code #ifdef MEDIAINFO_DEBUG #include <stdio.h> FILE* F; std::string Debug; #undef MEDIAINFO_DEBUG #define MEDIAINFO_DEBUG(_TOAPPEND) \ F=fopen("MediaInfo_Debug.txt", "a+t"); \ Debug.clear(); \ _TOAPPEND; \ Debug+="\r\n"; \ fwrite(Debug.c_str(), Debug.size(), 1, F); \ fclose(F); #else // MEDIAINFO_DEBUG #define MEDIAINFO_DEBUG(_TOAPPEND) #endif // MEDIAINFO_DEBUG #ifndef MEDIAINFO_DEBUG #define EXECUTE_VOID(_METHOD,_DEBUGB) \ ((MediaInfo_Internal*)Internal)->_METHOD; #else //MEDIAINFO_DEBUG #define EXECUTE_VOID(_METHOD,_DEBUGB) \ ((MediaInfo_Internal*)Internal)->_METHOD; \ MEDIAINFO_DEBUG(_DEBUGB) #endif //MEDIAINFO_DEBUG #ifndef MEDIAINFO_DEBUG #define EXECUTE_INT(_METHOD,_DEBUGB) \ return ((MediaInfo_Internal*)Internal)->_METHOD; #else //MEDIAINFO_DEBUG #define EXECUTE_INT(_METHOD, _DEBUGB) \ size_t ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \ MEDIAINFO_DEBUG(_DEBUGB) \ return ToReturn; #endif //MEDIAINFO_DEBUG #ifndef MEDIAINFO_DEBUG #define EXECUTE_STRING(_METHOD,_DEBUGB) \ return ((MediaInfo_Internal*)Internal)->_METHOD; #else //MEDIAINFO_DEBUG #define EXECUTE_STRING(_METHOD,_DEBUGB) \ Ztring ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \ MEDIAINFO_DEBUG(_DEBUGB) \ return ToReturn; #endif //MEDIAINFO_DEBUG inline std::string ToString(int64u Integer) { return Ztring::ToZtring(Integer).To_Local(); } inline std::string ToString(size_t Integer) { return Ztring::ToZtring(Integer).To_Local(); } //*************************************************************************** // Constructor/destructor //*************************************************************************** //--------------------------------------------------------------------------- MediaInfo::MediaInfo() { Internal=new MediaInfo_Internal(); } //--------------------------------------------------------------------------- MediaInfo::~MediaInfo() { delete (MediaInfo_Internal*)Internal; //Internal=NULL; } //*************************************************************************** // Files //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfo::Open(const String &File_Name_) { return ((MediaInfo_Internal*)Internal)->Open(File_Name_); } //--------------------------------------------------------------------------- size_t MediaInfo::Open (const int8u* Begin_, size_t Begin_Size_, const int8u*, size_t, int64u FileSize_) { return ((MediaInfo_Internal*)Internal)->Open(Begin_, Begin_Size_); } //--------------------------------------------------------------------------- size_t MediaInfo::Open_Buffer_Init (int64u File_Size, int64u File_Offset) { MEDIAINFO_DEBUG(Debug+="Open_Buffer_Init, File_Size=";Debug+=ToString(File_Size);Debug+=", File_Offset=";Debug+=ToString(File_Offset);) EXECUTE_INT(Open_Buffer_Init(File_Size, File_Offset), Debug+="Open_Buffer, will return ";Debug+=ToString(ToReturn);) } //--------------------------------------------------------------------------- size_t MediaInfo::Open_Buffer_Continue (const int8u* ToAdd, size_t ToAdd_Size) { size_t ToReturn=((MediaInfo_Internal*)Internal)->Open_Buffer_Continue(ToAdd, ToAdd_Size); if (ToReturn==0) { MEDIAINFO_DEBUG(Debug+="Open_Buffer_Continue, will return ";Debug+=ToString(ToReturn);Debug+=", forcing a Get() :";) Get(Stream_General, 0, _T("Format")); } return ToReturn; } //--------------------------------------------------------------------------- int64u MediaInfo::Open_Buffer_Continue_GoTo_Get () { return ((MediaInfo_Internal*)Internal)->Open_Buffer_Continue_GoTo_Get(); } //--------------------------------------------------------------------------- size_t MediaInfo::Open_Buffer_Finalize () { MEDIAINFO_DEBUG(Debug+="Open_Buffer_Finalize";) EXECUTE_INT(Open_Buffer_Continue_GoTo_Get(), Debug+="Open_Buffer_Finalize, will return ";Debug+=ToString(ToReturn);) } //--------------------------------------------------------------------------- size_t MediaInfo::Save() { return 0; //Not yet implemented } //--------------------------------------------------------------------------- void MediaInfo::Close() { MEDIAINFO_DEBUG(Debug+="Close";) return ((MediaInfo_Internal*)Internal)->Close(); } //*************************************************************************** // Get File info //*************************************************************************** //--------------------------------------------------------------------------- String MediaInfo::Inform(size_t) { MEDIAINFO_DEBUG(Debug+="Inform";) EXECUTE_STRING(Inform(), Debug+="Inform, will return ";Debug+=ToReturn.To_Local();) } //--------------------------------------------------------------------------- String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, size_t Parameter, info_t KindOfInfo) { MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=ToString(Parameter);) EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();) } //--------------------------------------------------------------------------- String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, const String &Parameter, info_t KindOfInfo, info_t KindOfSearch) { MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=Ztring(Parameter).To_Local();) //Legacy if (Parameter.find(_T("_String"))!=Error) { Ztring S1=Parameter; S1.FindAndReplace(_T("_String"), _T("/String")); return Get(StreamKind, StreamPos, S1, KindOfInfo, KindOfSearch); } if (Parameter==_T("Channels")) return Get(StreamKind, StreamPos, _T("Channel(s)"), KindOfInfo, KindOfSearch); if (Parameter==_T("Artist")) return Get(StreamKind, StreamPos, _T("Performer"), KindOfInfo, KindOfSearch); if (Parameter==_T("AspectRatio")) return Get(StreamKind, StreamPos, _T("DisplayAspectRatio"), KindOfInfo, KindOfSearch); if (Parameter==_T("AspectRatio/String")) return Get(StreamKind, StreamPos, _T("DisplayAspectRatio/String"), KindOfInfo, KindOfSearch); if (Parameter==_T("Chroma")) return Get(StreamKind, StreamPos, _T("Colourimetry"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime")) return Get(StreamKind, StreamPos, _T("Duration"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String")) return Get(StreamKind, StreamPos, _T("Duration/String"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String1")) return Get(StreamKind, StreamPos, _T("Duration/String1"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String2")) return Get(StreamKind, StreamPos, _T("Duration/String2"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String3")) return Get(StreamKind, StreamPos, _T("Duration/String3"), KindOfInfo, KindOfSearch); EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();) } //*************************************************************************** // Set File info //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, size_t Parameter, const String &OldValue) { return 0; //Not yet implemented } //--------------------------------------------------------------------------- size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, const String &Parameter, const String &OldValue) { return 0; //Not yet implemented } //*************************************************************************** // Output buffer //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfo::Output_Buffer_Get (const String &Value) { return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Value); } //--------------------------------------------------------------------------- size_t MediaInfo::Output_Buffer_Get (size_t Pos) { return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Pos); } //*************************************************************************** // Information //*************************************************************************** //--------------------------------------------------------------------------- String MediaInfo::Option (const String &Option, const String &Value) { MEDIAINFO_DEBUG(Debug+="Option, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();) EXECUTE_STRING(Option(Option, Value), Debug+="Option, will return ";Debug+=ToReturn.To_Local();) } //--------------------------------------------------------------------------- String MediaInfo::Option_Static (const String &Option, const String &Value) { MEDIAINFO_DEBUG(Debug+="Option_Static, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();) MediaInfoLib::Config.Init(); //Initialize Configuration if (Option==_T("Info_Capacities")) { return _T("Option desactivated for this version, will come back soon!"); MediaInfo_Internal MI; return MI.Option(Option); } else if (Option==_T("Info_Version")) { Ztring ToReturn=MediaInfoLib::Config.Info_Version_Get(); #if defined(MediaInfo_Internal_VIDEO_NO) || defined(MediaInfo_Internal_AUDIO_NO) || defined(MediaInfo_Internal_RIFF_NO) || defined(MediaInfo_Internal_OGG_NO) || defined(MediaInfo_Internal_MPEGPS_NO) || defined(MediaInfo_Internal_MPEGA_NO) || defined(MediaInfo_Internal_WM_NO) || defined(MediaInfo_Internal_QT_NO) || defined(MediaInfo_Internal_RM_NO) || defined(MediaInfo_Internal_DVDIF_NO) || defined(MediaInfo_Internal_DVDV_NO) || defined(MediaInfo_Internal_AAC_NO) || defined(MediaInfo_Internal_MK_NO) || defined(MediaInfo_Internal_APE_NO) || defined(MediaInfo_Internal_FLAC_NO) || defined(MediaInfo_Internal_SNDFILE_NO) || defined(MediaInfo_Internal_FLV_NO) || defined(MediaInfo_Internal_SWF_NO) ToReturn+=_T(" modified"); #endif return ToReturn; } else return MediaInfoLib::Config.Option(Option, Value); } //--------------------------------------------------------------------------- size_t MediaInfo::Count_Get (stream_t StreamKind, size_t StreamPos) { return ((MediaInfo_Internal*)Internal)->Count_Get(StreamKind, StreamPos); } //--------------------------------------------------------------------------- size_t MediaInfo::State_Get () { return 0; //Not yet implemented } } //NameSpace <commit_msg><commit_after>// MediaInfo - All info about media files // Copyright (C) 2002-2008 Jerome Martinez, [email protected] // // This library is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // 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, see <http://www.gnu.org/licenses/>. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // For user: you can disable or enable it //#define MEDIAINFO_DEBUG //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Compilation conditions #include <MediaInfo/Setup.h> #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/MediaInfo.h" #include "MediaInfo/MediaInfo_Internal.h" using namespace ZenLib; //--------------------------------------------------------------------------- namespace MediaInfoLib { //--------------------------------------------------------------------------- //To clarify the code #ifdef MEDIAINFO_DEBUG #include <stdio.h> FILE* F; std::string Debug; #undef MEDIAINFO_DEBUG #define MEDIAINFO_DEBUG(_TOAPPEND) \ F=fopen("MediaInfo_Debug.txt", "a+t"); \ Debug.clear(); \ _TOAPPEND; \ Debug+="\r\n"; \ fwrite(Debug.c_str(), Debug.size(), 1, F); \ fclose(F); #else // MEDIAINFO_DEBUG #define MEDIAINFO_DEBUG(_TOAPPEND) #endif // MEDIAINFO_DEBUG #ifndef MEDIAINFO_DEBUG #define EXECUTE_VOID(_METHOD,_DEBUGB) \ ((MediaInfo_Internal*)Internal)->_METHOD; #else //MEDIAINFO_DEBUG #define EXECUTE_VOID(_METHOD,_DEBUGB) \ ((MediaInfo_Internal*)Internal)->_METHOD; \ MEDIAINFO_DEBUG(_DEBUGB) #endif //MEDIAINFO_DEBUG #ifndef MEDIAINFO_DEBUG #define EXECUTE_INT(_METHOD,_DEBUGB) \ return ((MediaInfo_Internal*)Internal)->_METHOD; #else //MEDIAINFO_DEBUG #define EXECUTE_INT(_METHOD, _DEBUGB) \ size_t ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \ MEDIAINFO_DEBUG(_DEBUGB) \ return ToReturn; #endif //MEDIAINFO_DEBUG #ifndef MEDIAINFO_DEBUG #define EXECUTE_STRING(_METHOD,_DEBUGB) \ return ((MediaInfo_Internal*)Internal)->_METHOD; #else //MEDIAINFO_DEBUG #define EXECUTE_STRING(_METHOD,_DEBUGB) \ Ztring ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \ MEDIAINFO_DEBUG(_DEBUGB) \ return ToReturn; #endif //MEDIAINFO_DEBUG inline std::string ToString(int64u Integer) { return Ztring::ToZtring(Integer).To_Local(); } inline std::string ToString(size_t Integer) { return Ztring::ToZtring(Integer).To_Local(); } //*************************************************************************** // Constructor/destructor //*************************************************************************** //--------------------------------------------------------------------------- MediaInfo::MediaInfo() { Internal=new MediaInfo_Internal(); } //--------------------------------------------------------------------------- MediaInfo::~MediaInfo() { delete (MediaInfo_Internal*)Internal; //Internal=NULL; } //*************************************************************************** // Files //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfo::Open(const String &File_Name_) { return ((MediaInfo_Internal*)Internal)->Open(File_Name_); } //--------------------------------------------------------------------------- size_t MediaInfo::Open (const int8u* Begin_, size_t Begin_Size_, const int8u*, size_t, int64u FileSize_) { return ((MediaInfo_Internal*)Internal)->Open(Begin_, Begin_Size_); } //--------------------------------------------------------------------------- size_t MediaInfo::Open_Buffer_Init (int64u File_Size, int64u File_Offset) { MEDIAINFO_DEBUG(Debug+="Open_Buffer_Init, File_Size=";Debug+=ToString(File_Size);Debug+=", File_Offset=";Debug+=ToString(File_Offset);) EXECUTE_INT(Open_Buffer_Init(File_Size, File_Offset), Debug+="Open_Buffer, will return ";Debug+=ToString(ToReturn);) } //--------------------------------------------------------------------------- size_t MediaInfo::Open_Buffer_Continue (const int8u* ToAdd, size_t ToAdd_Size) { size_t ToReturn=((MediaInfo_Internal*)Internal)->Open_Buffer_Continue(ToAdd, ToAdd_Size); if (ToReturn==0) { MEDIAINFO_DEBUG(Debug+="Open_Buffer_Continue, will return ";Debug+=ToString(ToReturn);Debug+=", forcing a Get() :";) Get(Stream_General, 0, _T("Format")); } return ToReturn; } //--------------------------------------------------------------------------- int64u MediaInfo::Open_Buffer_Continue_GoTo_Get () { return ((MediaInfo_Internal*)Internal)->Open_Buffer_Continue_GoTo_Get(); } //--------------------------------------------------------------------------- size_t MediaInfo::Open_Buffer_Finalize () { MEDIAINFO_DEBUG(Debug+="Open_Buffer_Finalize";) EXECUTE_INT(Open_Buffer_Continue_GoTo_Get(), Debug+="Open_Buffer_Finalize, will return ";Debug+=ToString(ToReturn);) } //--------------------------------------------------------------------------- size_t MediaInfo::Save() { return 0; //Not yet implemented } //--------------------------------------------------------------------------- void MediaInfo::Close() { MEDIAINFO_DEBUG(Debug+="Close";) return ((MediaInfo_Internal*)Internal)->Close(); } //*************************************************************************** // Get File info //*************************************************************************** //--------------------------------------------------------------------------- String MediaInfo::Inform(size_t) { MEDIAINFO_DEBUG(Debug+="Inform";) EXECUTE_STRING(Inform(), Debug+="Inform, will return ";Debug+=ToReturn.To_Local();) } //--------------------------------------------------------------------------- String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, size_t Parameter, info_t KindOfInfo) { MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=ToString(Parameter);) EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();) } //--------------------------------------------------------------------------- String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, const String &Parameter, info_t KindOfInfo, info_t KindOfSearch) { MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=Ztring(Parameter).To_Local();) //Legacy if (Parameter.find(_T("_String"))!=Error) { Ztring S1=Parameter; S1.FindAndReplace(_T("_String"), _T("/String")); return Get(StreamKind, StreamPos, S1, KindOfInfo, KindOfSearch); } if (Parameter==_T("Channels")) return Get(StreamKind, StreamPos, _T("Channel(s)"), KindOfInfo, KindOfSearch); if (Parameter==_T("Artist")) return Get(StreamKind, StreamPos, _T("Performer"), KindOfInfo, KindOfSearch); if (Parameter==_T("AspectRatio")) return Get(StreamKind, StreamPos, _T("DisplayAspectRatio"), KindOfInfo, KindOfSearch); if (Parameter==_T("AspectRatio/String")) return Get(StreamKind, StreamPos, _T("DisplayAspectRatio/String"), KindOfInfo, KindOfSearch); if (Parameter==_T("Chroma")) return Get(StreamKind, StreamPos, _T("Colourimetry"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime")) return Get(StreamKind, StreamPos, _T("Duration"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String")) return Get(StreamKind, StreamPos, _T("Duration/String"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String1")) return Get(StreamKind, StreamPos, _T("Duration/String1"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String2")) return Get(StreamKind, StreamPos, _T("Duration/String2"), KindOfInfo, KindOfSearch); if (Parameter==_T("PlayTime/String3")) return Get(StreamKind, StreamPos, _T("Duration/String3"), KindOfInfo, KindOfSearch); EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();) } //*************************************************************************** // Set File info //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, size_t Parameter, const String &OldValue) { return 0; //Not yet implemented } //--------------------------------------------------------------------------- size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, const String &Parameter, const String &OldValue) { return 0; //Not yet implemented } //*************************************************************************** // Output buffer //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfo::Output_Buffer_Get (const String &Value) { return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Value); } //--------------------------------------------------------------------------- size_t MediaInfo::Output_Buffer_Get (size_t Pos) { return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Pos); } //*************************************************************************** // Information //*************************************************************************** //--------------------------------------------------------------------------- String MediaInfo::Option (const String &Option, const String &Value) { MEDIAINFO_DEBUG(Debug+="Option, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();) EXECUTE_STRING(Option(Option, Value), Debug+="Option, will return ";Debug+=ToReturn.To_Local();) } //--------------------------------------------------------------------------- String MediaInfo::Option_Static (const String &Option, const String &Value) { MEDIAINFO_DEBUG(Debug+="Option_Static, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();) MediaInfoLib::Config.Init(); //Initialize Configuration if (Option==_T("Info_Capacities")) { return _T("Option desactivated for this version, will come back soon!"); MediaInfo_Internal MI; return MI.Option(Option); } else if (Option==_T("Info_Version")) { Ztring ToReturn=MediaInfoLib::Config.Info_Version_Get(); #if defined(MediaInfo_Internal_VIDEO_NO) || defined(MediaInfo_Internal_AUDIO_NO) || defined(MediaInfo_Internal_RIFF_NO) || defined(MediaInfo_Internal_OGG_NO) || defined(MediaInfo_Internal_MPEGPS_NO) || defined(MediaInfo_Internal_MPEGA_NO) || defined(MediaInfo_Internal_WM_NO) || defined(MediaInfo_Internal_QT_NO) || defined(MediaInfo_Internal_RM_NO) || defined(MediaInfo_Internal_DVDIF_NO) || defined(MediaInfo_Internal_DVDV_NO) || defined(MediaInfo_Internal_AAC_NO) || defined(MediaInfo_Internal_MK_NO) || defined(MediaInfo_Internal_APE_NO) || defined(MediaInfo_Internal_FLAC_NO) || defined(MediaInfo_Internal_SNDFILE_NO) || defined(MediaInfo_Internal_FLV_NO) || defined(MediaInfo_Internal_SWF_NO) ToReturn+=_T(" modified"); #endif return ToReturn; } else return MediaInfoLib::Config.Option(Option, Value); } //--------------------------------------------------------------------------- size_t MediaInfo::Count_Get (stream_t StreamKind, size_t StreamPos) { return ((MediaInfo_Internal*)Internal)->Count_Get(StreamKind, StreamPos); } //--------------------------------------------------------------------------- size_t MediaInfo::State_Get () { return 0; //Not yet implemented } } //NameSpace <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Lefteris Karapetsas <[email protected]> * @date 2014 * Unit tests for the solidity compiler JSON Interface output. */ #include <boost/test/unit_test.hpp> #include <libsolidity/CompilerStack.h> #include <jsonrpc/json/json.h> #include <libdevcore/Exceptions.h> namespace dev { namespace solidity { namespace test { class DocumentationChecker { public: void checkNatspec(std::string const& _code, std::string const& _expectedDocumentationString, bool _userDocumentation) { std::string generatedDocumentationString; try { m_compilerStack.parse(_code); } catch (const std::exception& e) { std::string const* extra = boost::get_error_info<errinfo_comment>(e); std::string msg = std::string("Parsing contract failed with: ") + e.what() + std::string("\n"); if (extra) msg += *extra; BOOST_FAIL(msg); } if (_userDocumentation) generatedDocumentationString = *m_compilerStack.getJsonDocumentation(NATSPEC_USER); else generatedDocumentationString = *m_compilerStack.getJsonDocumentation(NATSPEC_DEV); Json::Value generatedDocumentation; m_reader.parse(generatedDocumentationString, generatedDocumentation); Json::Value expectedDocumentation; m_reader.parse(_expectedDocumentationString, expectedDocumentation); BOOST_CHECK_MESSAGE(expectedDocumentation == generatedDocumentation, "Expected " << _expectedDocumentationString << "\n but got:\n" << generatedDocumentationString); } private: CompilerStack m_compilerStack; Json::Reader m_reader; }; BOOST_FIXTURE_TEST_SUITE(SolidityNatspecJSON, DocumentationChecker) BOOST_AUTO_TEST_CASE(user_basic_test) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7\n" " function mul(uint a) returns(uint d) { return a * 7; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \"notice\": \"Multiplies `a` by 7\"}" "}}"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(dev_and_user_basic_test) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7\n" " /// @dev Multiplies a number by 7\n" " function mul(uint a) returns(uint d) { return a * 7; }\n" "}\n"; char const* devNatspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7\"\n" " }\n" " }\n" "}}"; char const* userNatspec = "{" "\"methods\":{" " \"mul\":{ \"notice\": \"Multiplies `a` by 7\"}" "}}"; checkNatspec(sourceCode, devNatspec, false); checkNatspec(sourceCode, userNatspec, true); } BOOST_AUTO_TEST_CASE(user_multiline_comment) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7\n" " /// and then adds `b`\n" " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" " {\n" " return (a * 7) + b;\n" " }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul_and_add\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}" "}}"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(user_multiple_functions) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7 and then adds `b`\n" " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" " {\n" " return (a * 7) + b;\n" " }\n" "\n" " /// @notice Divides `input` by `div`\n" " function divide(uint input, uint div) returns(uint d)\n" " {\n" " return input / div;\n" " }\n" " /// @notice Subtracts 3 from `input`\n" " function sub(int input) returns(int d)\n" " {\n" " return input - 3;\n" " }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul_and_add\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}," " \"divide\":{ \"notice\": \"Divides `input` by `div`\"}," " \"sub\":{ \"notice\": \"Subtracts 3 from `input`\"}" "}}"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(user_empty_contract) { char const* sourceCode = "contract test {\n" "}\n"; char const* natspec = "{\"methods\":{} }"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(dev_and_user_no_doc) { char const* sourceCode = "contract test {\n" " function mul(uint a) returns(uint d) { return a * 7; }\n" " function sub(int input) returns(int d)\n" " {\n" " return input - 3;\n" " }\n" "}\n"; char const* devNatspec = "{\"methods\":{}}"; char const* userNatspec = "{\"methods\":{}}"; checkNatspec(sourceCode, devNatspec, false); checkNatspec(sourceCode, userNatspec, true); } BOOST_AUTO_TEST_CASE(dev_multiple_params) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter\n" " /// @param second Documentation for the second parameter\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter\",\n" " \"second\": \"Documentation for the second parameter\"\n" " }\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_mutiline_param_description) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter starts here.\n" " /// Since it's a really complicated parameter we need 2 lines\n" " /// @param second Documentation for the second parameter\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" " \"second\": \"Documentation for the second parameter\"\n" " }\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_multiple_functions) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter\n" " /// @param second Documentation for the second parameter\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" " \n" " /// @dev Divides 2 numbers\n" " /// @param input Documentation for the input parameter\n" " /// @param div Documentation for the div parameter\n" " function divide(uint input, uint div) returns(uint d)\n" " {\n" " return input / div;\n" " }\n" " /// @dev Subtracts 3 from `input`\n" " /// @param input Documentation for the input parameter\n" " function sub(int input) returns(int d)\n" " {\n" " return input - 3;\n" " }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter\",\n" " \"second\": \"Documentation for the second parameter\"\n" " }\n" " },\n" " \"divide\":{ \n" " \"details\": \"Divides 2 numbers\",\n" " \"params\": {\n" " \"input\": \"Documentation for the input parameter\",\n" " \"div\": \"Documentation for the div parameter\"\n" " }\n" " },\n" " \"sub\":{ \n" " \"details\": \"Subtracts 3 from `input`\",\n" " \"params\": {\n" " \"input\": \"Documentation for the input parameter\"\n" " }\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_return) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter starts here.\n" " /// Since it's a really complicated parameter we need 2 lines\n" " /// @param second Documentation for the second parameter\n" " /// @return The result of the multiplication\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" " \"second\": \"Documentation for the second parameter\"\n" " },\n" " \"return\": \"The result of the multiplication\"\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_multiline_return) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter starts here.\n" " /// Since it's a really complicated parameter we need 2 lines\n" " /// @param second Documentation for the second parameter\n" " /// @return The result of the multiplication\n" " /// and cookies with nutella\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" " \"second\": \"Documentation for the second parameter\"\n" " },\n" " \"return\": \"The result of the multiplication and cookies with nutella\"\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_SUITE_END() } } } <commit_msg>Newline right after doctag is now a valid natspec entry<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Lefteris Karapetsas <[email protected]> * @date 2014 * Unit tests for the solidity compiler JSON Interface output. */ #include <boost/test/unit_test.hpp> #include <libsolidity/CompilerStack.h> #include <jsonrpc/json/json.h> #include <libdevcore/Exceptions.h> namespace dev { namespace solidity { namespace test { class DocumentationChecker { public: void checkNatspec(std::string const& _code, std::string const& _expectedDocumentationString, bool _userDocumentation) { std::string generatedDocumentationString; try { m_compilerStack.parse(_code); } catch (const std::exception& e) { std::string const* extra = boost::get_error_info<errinfo_comment>(e); std::string msg = std::string("Parsing contract failed with: ") + e.what() + std::string("\n"); if (extra) msg += *extra; BOOST_FAIL(msg); } if (_userDocumentation) generatedDocumentationString = *m_compilerStack.getJsonDocumentation(NATSPEC_USER); else generatedDocumentationString = *m_compilerStack.getJsonDocumentation(NATSPEC_DEV); Json::Value generatedDocumentation; m_reader.parse(generatedDocumentationString, generatedDocumentation); Json::Value expectedDocumentation; m_reader.parse(_expectedDocumentationString, expectedDocumentation); BOOST_CHECK_MESSAGE(expectedDocumentation == generatedDocumentation, "Expected " << _expectedDocumentationString << "\n but got:\n" << generatedDocumentationString); } private: CompilerStack m_compilerStack; Json::Reader m_reader; }; BOOST_FIXTURE_TEST_SUITE(SolidityNatspecJSON, DocumentationChecker) BOOST_AUTO_TEST_CASE(user_basic_test) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7\n" " function mul(uint a) returns(uint d) { return a * 7; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \"notice\": \"Multiplies `a` by 7\"}" "}}"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(dev_and_user_basic_test) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7\n" " /// @dev Multiplies a number by 7\n" " function mul(uint a) returns(uint d) { return a * 7; }\n" "}\n"; char const* devNatspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7\"\n" " }\n" " }\n" "}}"; char const* userNatspec = "{" "\"methods\":{" " \"mul\":{ \"notice\": \"Multiplies `a` by 7\"}" "}}"; checkNatspec(sourceCode, devNatspec, false); checkNatspec(sourceCode, userNatspec, true); } BOOST_AUTO_TEST_CASE(user_multiline_comment) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7\n" " /// and then adds `b`\n" " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" " {\n" " return (a * 7) + b;\n" " }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul_and_add\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}" "}}"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(user_multiple_functions) { char const* sourceCode = "contract test {\n" " /// @notice Multiplies `a` by 7 and then adds `b`\n" " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" " {\n" " return (a * 7) + b;\n" " }\n" "\n" " /// @notice Divides `input` by `div`\n" " function divide(uint input, uint div) returns(uint d)\n" " {\n" " return input / div;\n" " }\n" " /// @notice Subtracts 3 from `input`\n" " function sub(int input) returns(int d)\n" " {\n" " return input - 3;\n" " }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul_and_add\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}," " \"divide\":{ \"notice\": \"Divides `input` by `div`\"}," " \"sub\":{ \"notice\": \"Subtracts 3 from `input`\"}" "}}"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(user_empty_contract) { char const* sourceCode = "contract test {\n" "}\n"; char const* natspec = "{\"methods\":{} }"; checkNatspec(sourceCode, natspec, true); } BOOST_AUTO_TEST_CASE(dev_and_user_no_doc) { char const* sourceCode = "contract test {\n" " function mul(uint a) returns(uint d) { return a * 7; }\n" " function sub(int input) returns(int d)\n" " {\n" " return input - 3;\n" " }\n" "}\n"; char const* devNatspec = "{\"methods\":{}}"; char const* userNatspec = "{\"methods\":{}}"; checkNatspec(sourceCode, devNatspec, false); checkNatspec(sourceCode, userNatspec, true); } BOOST_AUTO_TEST_CASE(dev_desc_after_nl) { char const* sourceCode = "contract test {\n" " /// @dev\n" " /// Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter\n" " /// @param second Documentation for the second parameter\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \" Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter\",\n" " \"second\": \"Documentation for the second parameter\"\n" " }\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_multiple_params) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter\n" " /// @param second Documentation for the second parameter\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter\",\n" " \"second\": \"Documentation for the second parameter\"\n" " }\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_mutiline_param_description) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter starts here.\n" " /// Since it's a really complicated parameter we need 2 lines\n" " /// @param second Documentation for the second parameter\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" " \"second\": \"Documentation for the second parameter\"\n" " }\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_multiple_functions) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter\n" " /// @param second Documentation for the second parameter\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" " \n" " /// @dev Divides 2 numbers\n" " /// @param input Documentation for the input parameter\n" " /// @param div Documentation for the div parameter\n" " function divide(uint input, uint div) returns(uint d)\n" " {\n" " return input / div;\n" " }\n" " /// @dev Subtracts 3 from `input`\n" " /// @param input Documentation for the input parameter\n" " function sub(int input) returns(int d)\n" " {\n" " return input - 3;\n" " }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter\",\n" " \"second\": \"Documentation for the second parameter\"\n" " }\n" " },\n" " \"divide\":{ \n" " \"details\": \"Divides 2 numbers\",\n" " \"params\": {\n" " \"input\": \"Documentation for the input parameter\",\n" " \"div\": \"Documentation for the div parameter\"\n" " }\n" " },\n" " \"sub\":{ \n" " \"details\": \"Subtracts 3 from `input`\",\n" " \"params\": {\n" " \"input\": \"Documentation for the input parameter\"\n" " }\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_return) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter starts here.\n" " /// Since it's a really complicated parameter we need 2 lines\n" " /// @param second Documentation for the second parameter\n" " /// @return The result of the multiplication\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" " \"second\": \"Documentation for the second parameter\"\n" " },\n" " \"return\": \"The result of the multiplication\"\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_return_desc_after_nl) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter starts here.\n" " /// Since it's a really complicated parameter we need 2 lines\n" " /// @param second Documentation for the second parameter\n" " /// @return\n" " /// The result of the multiplication\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" " \"second\": \"Documentation for the second parameter\"\n" " },\n" " \"return\": \" The result of the multiplication\"\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_CASE(dev_multiline_return) { char const* sourceCode = "contract test {\n" " /// @dev Multiplies a number by 7 and adds second parameter\n" " /// @param a Documentation for the first parameter starts here.\n" " /// Since it's a really complicated parameter we need 2 lines\n" " /// @param second Documentation for the second parameter\n" " /// @return The result of the multiplication\n" " /// and cookies with nutella\n" " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" "}\n"; char const* natspec = "{" "\"methods\":{" " \"mul\":{ \n" " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" " \"params\": {\n" " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" " \"second\": \"Documentation for the second parameter\"\n" " },\n" " \"return\": \"The result of the multiplication and cookies with nutella\"\n" " }\n" "}}"; checkNatspec(sourceCode, natspec, false); } BOOST_AUTO_TEST_SUITE_END() } } } <|endoftext|>
<commit_before>/* * Copyright 2015 BrewPi / Elco Jacobs * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Pid.h" Pid::Pid(TempSensorBasic * input, ActuatorRange * output, SetPoint * setPoint) { setConstants(temp_t(0.0), 0, 0); p = decltype(p)::base_type(0); i = decltype(i)::base_type(0); d = decltype(p)::base_type(0); inputError = decltype(inputError)::base_type(0); derivative = decltype(derivative)::base_type(0); integral = decltype(integral)::base_type(0); failedReadCount = 255; // start at 255, so inputFilter is refreshed at first valid read setInputSensor(input); setOutputActuator(output); setSetPoint(setPoint); setInputFilter(0); // some filtering necessary due to quantization causing steps in the temperature setDerivativeFilter(2); actuatorIsNegative = false; enabled = true; // autotune = false; // tuning = false; // outputLag = 0; // maxDerivative = 0.0; } void Pid::setConstants(temp_long_t kp, uint16_t ti, uint16_t td) { Kp = kp; Ti = ti; Td = td; } void Pid::update() { temp_t inputVal; bool validSetPoint = true; bool validSensor = true; if( setPoint->read().isDisabledOrInvalid()){ validSetPoint = false; } inputVal = inputSensor -> read(); if (inputVal.isDisabledOrInvalid()){ // Could not read from input sensor if (failedReadCount < 255){ // limit failedReadCount++; } if (failedReadCount > 20){ validSensor = false; // disable PID if sensor is lost for more than 20 seconds } } else{ if (failedReadCount > 60){ // filters are stale, re-initialize them inputFilter.init(inputVal); derivativeFilter.init(temp_precise_t(0.0)); } failedReadCount = 0; } if(validSensor){ inputFilter.add(inputVal); temp_precise_t delta = inputFilter.readOutput() - inputFilter.readPrevOutput(); // prevent overflow in shift. Add to derivative filter shifted, because of limited precision for such low values temp_precise_t deltaClipped = delta; temp_precise_t max = temp_precise_t::max() >> uint8_t(10); temp_precise_t min = temp_precise_t::min() >> uint8_t(10); if(deltaClipped > max){ deltaClipped = max; } else if(deltaClipped < min){ deltaClipped = min; } derivativeFilter.add(deltaClipped << uint8_t(10)); if(validSetPoint){ inputError = inputFilter.readOutput() - setPoint->read(); } } derivative = derivativeFilter.readOutput() >> uint8_t(10); if(!enabled || !validSensor || !validSetPoint){ p = decltype(p)::base_type(0); i = decltype(i)::base_type(0); d = decltype(p)::base_type(0); return; } // calculate PID parts. p = Kp * -inputError; i = (Ti != 0) ? (integral/Ti) : temp_long_t(0.0); d = -Kp * (derivative * Td); temp_long_t pidResult = temp_long_t(p) + temp_long_t(i) + temp_long_t(d); // Get output to send to actuator. When actuator is a 'cooler', invert the result temp_t output = (actuatorIsNegative) ? -pidResult : pidResult; outputActuator -> setValue(output); // get the value that is clipped to the actuator's range output = outputActuator->getValue(); // When actuator is a 'cooler', invert the output again output = (actuatorIsNegative) ? -output : output; // get the actual achieved value in actuator. This could differ due to slowness time/mutex limits temp_t achievedOutput = outputActuator->readValue(); // When actuator is a 'cooler', invert the output again achievedOutput = (actuatorIsNegative) ? -achievedOutput : achievedOutput; if(Ti == 0){ // 0 has been chosen to indicate that the integrator is disabled. This also prevents divide by zero. integral = decltype(integral)::base_type(0); } else{ temp_long_t zero(temp_long_t::base_type(0)); // if derivative part is canceling more than half the proportional part, disable integration // otherwise add input error to integral // this prevents integrator windup when the input is changing quickly // the integrator is for correcting steady state errors, so if we are not in steady state, don't increase the integral if( ((p + (d + d)) > zero && (p > zero)) || ((p + (d + d)) < zero && (p < zero)) ){ integral = integral + p; } // update integral with anti-windup back calculation // pidResult - output is zero when actuator is not saturated // when the actuator is close the to pidResult (setpoint), disable anti-windup // this prevens small fluctuations from keeping the integrator at zero temp_long_t antiWindup(temp_long_t::base_type(0)); if(pidResult != temp_long_t(output)){ // clipped to actuator min or max set in target actuator antiWindup = pidResult - output; antiWindup *= 5; // Anti windup gain is 5 when clipping to min/max } else{ // actuator could be not reaching set value due to physics or limits in its target actuator temp_long_t closeThreshold = Kp; temp_t noAntiWindupMin = output - closeThreshold; temp_t noAntiWindupMax = output + closeThreshold; // do not apply anti-windup if close to target. Always apply when actuator is at zero. if(achievedOutput == temp_t(0.0) || achievedOutput < noAntiWindupMin || achievedOutput > noAntiWindupMax){ antiWindup = pidResult - achievedOutput; // antiWindup *= 1; // Anti windup gain is 1 for this kind of windup } } // only apply anti-windup if it will decrease the integral and prevent crossing through zero if(integral.sign() * antiWindup.sign() == 1){ if((integral - antiWindup).sign() != integral.sign()){ integral = decltype(integral)::base_type(0); } else{ integral -= antiWindup; } } } } void Pid::setFiltering(uint8_t b){ inputFilter.setFiltering(b); derivativeFilter.setFiltering(b); } uint8_t Pid::getFiltering(){ return inputFilter.getFiltering(); } void Pid::setInputFilter(uint8_t b) { inputFilter.setFiltering(b); } void Pid::setDerivativeFilter(uint8_t b) { derivativeFilter.setFiltering(b); } bool Pid::setInputSensor(TempSensorBasic * s) { inputSensor = s; temp_t t = s -> read(); if (t.isDisabledOrInvalid()){ return false; // could not read from sensor } inputFilter.init(t); derivativeFilter.init(0.0); return true; } bool Pid::setOutputActuator(ActuatorRange * a) { outputActuator = a; return true; } /* // Tune the PID with the Ziegler-Nichols Open-Loop Tuning Method or Process Reaction Method // This determines the dead time and the reaction rate (max derivative) and calculates the PID parameters from that. void Pid::tune(temp output, temp previousOutput){ static uint16_t lagTimer = 0; static temp tuningStartTemp = inputFilter.readOutput(); temp min = outputActuator->min(); temp max = outputActuator->max(); temp tuningThreshold = (max >> uint8_t(1)) + (min >> uint8_t(1)); // (min + max) / 2 if(output == outputActuator->max() && previousOutput < tuningThreshold){ tuning = true; // only start tuning at a big step to the maximum output } // cancel tuning when the output is under the tuning threshold before maximum derivative is detected if(output < tuningThreshold){ if(lagTimer > 2*(derivativeFilter.getDelay() + inputFilter.getDelay())){ tuning = false; // only stop tuning if filters have had time to settle } } // TODO: when this happens, check the filter delay and see if the maximum still has to come // Detect when at max derivative, the time until this happens is the lag time // Together with the maximum derivative, this is used to determine the PID parameters if(tuning){ // only for heating now // if the derivative of the input starts falling, we have hit an inflection point // Also check that the derivative is positive if(derivativeFilter.isFalling() && (derivativeFilter.readOutput() > temp_precise(0))){ maxDerivative = derivativeFilter.readOutput(); // we're at the peak or past it uint16_t filterDelay = derivativeFilter.getDelay(); uint16_t timeToMaxDerivative = (lagTimer <filterDelay) ? 0 : lagTimer - filterDelay; // set PID constants to have no overshoot temp_long deadTime = temp_long(timeToMaxDerivative) / temp_long(60.0); // derivative and integral are per minute, scale back here temp_long riseTime = (inputFilter.readOutput() - tuningStartTemp) / derivative; if(riseTime < temp_long(0)){ riseTime = 0.0; } deadTime = (deadTime > riseTime) ? deadTime - riseTime : temp_long(0); // rise time is not part of the dead time, eliminate it outputLag = uint16_t(deadTime * temp_long(60)); // store outputlag in seconds temp_long RL = derivative * deadTime; if (RL < temp_long(0.25)){ // prevent divide by zero Kp = 160.0; } else{ Kp = temp_long(100.0*0.4) / RL; // not aggressive. Quarter decay is 1.2 instead of 0.4. We don't want overshoot } if(deadTime > temp_long(1)){ Ki = Kp/(deadTime+deadTime); } else{ Ki = Kp*temp_long(0.5); } Kd = Kp*deadTime*temp_long(0.33); tuning = false; // tuning ready } else{ if(lagTimer < UINT16_MAX){ lagTimer++; } } } else{ lagTimer= 0; tuningStartTemp = inputFilter.readOutput(); } } */ <commit_msg>Removed check to disable integrator when derivative part > 1/2 proportional part. This does not work well for low Kp.<commit_after>/* * Copyright 2015 BrewPi / Elco Jacobs * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Pid.h" Pid::Pid(TempSensorBasic * input, ActuatorRange * output, SetPoint * setPoint) { setConstants(temp_t(0.0), 0, 0); p = decltype(p)::base_type(0); i = decltype(i)::base_type(0); d = decltype(p)::base_type(0); inputError = decltype(inputError)::base_type(0); derivative = decltype(derivative)::base_type(0); integral = decltype(integral)::base_type(0); failedReadCount = 255; // start at 255, so inputFilter is refreshed at first valid read setInputSensor(input); setOutputActuator(output); setSetPoint(setPoint); setInputFilter(0); // some filtering necessary due to quantization causing steps in the temperature setDerivativeFilter(2); actuatorIsNegative = false; enabled = true; // autotune = false; // tuning = false; // outputLag = 0; // maxDerivative = 0.0; } void Pid::setConstants(temp_long_t kp, uint16_t ti, uint16_t td) { Kp = kp; Ti = ti; Td = td; } void Pid::update() { temp_t inputVal; bool validSetPoint = true; bool validSensor = true; if( setPoint->read().isDisabledOrInvalid()){ validSetPoint = false; } inputVal = inputSensor -> read(); if (inputVal.isDisabledOrInvalid()){ // Could not read from input sensor if (failedReadCount < 255){ // limit failedReadCount++; } if (failedReadCount > 20){ validSensor = false; // disable PID if sensor is lost for more than 20 seconds } } else{ if (failedReadCount > 60){ // filters are stale, re-initialize them inputFilter.init(inputVal); derivativeFilter.init(temp_precise_t(0.0)); } failedReadCount = 0; } if(validSensor){ inputFilter.add(inputVal); temp_precise_t delta = inputFilter.readOutput() - inputFilter.readPrevOutput(); // prevent overflow in shift. Add to derivative filter shifted, because of limited precision for such low values temp_precise_t deltaClipped = delta; temp_precise_t max = temp_precise_t::max() >> uint8_t(10); temp_precise_t min = temp_precise_t::min() >> uint8_t(10); if(deltaClipped > max){ deltaClipped = max; } else if(deltaClipped < min){ deltaClipped = min; } derivativeFilter.add(deltaClipped << uint8_t(10)); if(validSetPoint){ inputError = inputFilter.readOutput() - setPoint->read(); } } derivative = derivativeFilter.readOutput() >> uint8_t(10); if(!enabled || !validSensor || !validSetPoint){ p = decltype(p)::base_type(0); i = decltype(i)::base_type(0); d = decltype(p)::base_type(0); return; } // calculate PID parts. p = Kp * -inputError; i = (Ti != 0) ? (integral/Ti) : temp_long_t(0.0); d = -Kp * (derivative * Td); temp_long_t pidResult = temp_long_t(p) + temp_long_t(i) + temp_long_t(d); // Get output to send to actuator. When actuator is a 'cooler', invert the result temp_t output = (actuatorIsNegative) ? -pidResult : pidResult; outputActuator -> setValue(output); // get the value that is clipped to the actuator's range output = outputActuator->getValue(); // When actuator is a 'cooler', invert the output again output = (actuatorIsNegative) ? -output : output; // get the actual achieved value in actuator. This could differ due to slowness time/mutex limits temp_t achievedOutput = outputActuator->readValue(); // When actuator is a 'cooler', invert the output again achievedOutput = (actuatorIsNegative) ? -achievedOutput : achievedOutput; if(Ti == 0){ // 0 has been chosen to indicate that the integrator is disabled. This also prevents divide by zero. integral = decltype(integral)::base_type(0); } else{ // update integral with anti-windup back calculation // pidResult - output is zero when actuator is not saturated // when the actuator is close the to pidResult (setpoint), disable anti-windup // this prevens small fluctuations from keeping the integrator at zero integral = integral + p; temp_long_t antiWindup(temp_long_t::base_type(0)); if(pidResult != temp_long_t(output)){ // clipped to actuator min or max set in target actuator antiWindup = pidResult - output; antiWindup *= 5; // Anti windup gain is 5 when clipping to min/max } else{ // actuator could be not reaching set value due to physics or limits in its target actuator temp_long_t closeThreshold = Kp; temp_t noAntiWindupMin = output - closeThreshold; temp_t noAntiWindupMax = output + closeThreshold; // do not apply anti-windup if close to target. Always apply when actuator is at zero. if(achievedOutput == temp_t(0.0) || achievedOutput < noAntiWindupMin || achievedOutput > noAntiWindupMax){ antiWindup = pidResult - achievedOutput; // antiWindup *= 1; // Anti windup gain is 1 for this kind of windup } } // only apply anti-windup if it will decrease the integral and prevent crossing through zero if(integral.sign() * antiWindup.sign() == 1){ if((integral - antiWindup).sign() != integral.sign()){ integral = decltype(integral)::base_type(0); } else{ integral -= antiWindup; } } } } void Pid::setFiltering(uint8_t b){ inputFilter.setFiltering(b); derivativeFilter.setFiltering(b); } uint8_t Pid::getFiltering(){ return inputFilter.getFiltering(); } void Pid::setInputFilter(uint8_t b) { inputFilter.setFiltering(b); } void Pid::setDerivativeFilter(uint8_t b) { derivativeFilter.setFiltering(b); } bool Pid::setInputSensor(TempSensorBasic * s) { inputSensor = s; temp_t t = s -> read(); if (t.isDisabledOrInvalid()){ return false; // could not read from sensor } inputFilter.init(t); derivativeFilter.init(0.0); return true; } bool Pid::setOutputActuator(ActuatorRange * a) { outputActuator = a; return true; } /* // Tune the PID with the Ziegler-Nichols Open-Loop Tuning Method or Process Reaction Method // This determines the dead time and the reaction rate (max derivative) and calculates the PID parameters from that. void Pid::tune(temp output, temp previousOutput){ static uint16_t lagTimer = 0; static temp tuningStartTemp = inputFilter.readOutput(); temp min = outputActuator->min(); temp max = outputActuator->max(); temp tuningThreshold = (max >> uint8_t(1)) + (min >> uint8_t(1)); // (min + max) / 2 if(output == outputActuator->max() && previousOutput < tuningThreshold){ tuning = true; // only start tuning at a big step to the maximum output } // cancel tuning when the output is under the tuning threshold before maximum derivative is detected if(output < tuningThreshold){ if(lagTimer > 2*(derivativeFilter.getDelay() + inputFilter.getDelay())){ tuning = false; // only stop tuning if filters have had time to settle } } // TODO: when this happens, check the filter delay and see if the maximum still has to come // Detect when at max derivative, the time until this happens is the lag time // Together with the maximum derivative, this is used to determine the PID parameters if(tuning){ // only for heating now // if the derivative of the input starts falling, we have hit an inflection point // Also check that the derivative is positive if(derivativeFilter.isFalling() && (derivativeFilter.readOutput() > temp_precise(0))){ maxDerivative = derivativeFilter.readOutput(); // we're at the peak or past it uint16_t filterDelay = derivativeFilter.getDelay(); uint16_t timeToMaxDerivative = (lagTimer <filterDelay) ? 0 : lagTimer - filterDelay; // set PID constants to have no overshoot temp_long deadTime = temp_long(timeToMaxDerivative) / temp_long(60.0); // derivative and integral are per minute, scale back here temp_long riseTime = (inputFilter.readOutput() - tuningStartTemp) / derivative; if(riseTime < temp_long(0)){ riseTime = 0.0; } deadTime = (deadTime > riseTime) ? deadTime - riseTime : temp_long(0); // rise time is not part of the dead time, eliminate it outputLag = uint16_t(deadTime * temp_long(60)); // store outputlag in seconds temp_long RL = derivative * deadTime; if (RL < temp_long(0.25)){ // prevent divide by zero Kp = 160.0; } else{ Kp = temp_long(100.0*0.4) / RL; // not aggressive. Quarter decay is 1.2 instead of 0.4. We don't want overshoot } if(deadTime > temp_long(1)){ Ki = Kp/(deadTime+deadTime); } else{ Ki = Kp*temp_long(0.5); } Kd = Kp*deadTime*temp_long(0.33); tuning = false; // tuning ready } else{ if(lagTimer < UINT16_MAX){ lagTimer++; } } } else{ lagTimer= 0; tuningStartTemp = inputFilter.readOutput(); } } */ <|endoftext|>
<commit_before>#include <stdio.h> #include "../SynCommonLib/RelationsIterator.h" #include "../common/SyntaxHolder.h" void GetAnanlytForms(const CSentence& Sentence, string& Res) { for( int WordNo = 0; WordNo<Sentence.m_Words.size(); WordNo++ ) { const CSynWord& W = Sentence.m_Words[WordNo]; if (!W.m_MainVerbs.empty()) { Res += string("\t<analyt> ")+ W.m_strWord.c_str(); for (size_t i=0; i< W.m_MainVerbs.size(); i++) { Res += string(" ") + Sentence.m_Words[W.m_MainVerbs[i]].m_strWord; const CSynWord& W_1 = Sentence.m_Words[W.m_MainVerbs[i]]; for (size_t j=0; j< W_1.m_MainVerbs.size(); j++) Res += string(" ") + Sentence.m_Words[W_1.m_MainVerbs[j]].m_strWord; }; Res += "</analyt>\n"; } } } string GetWords(const CSentence& Sentence, const CPeriod& P) { string S; for (int WordNo = P.m_iFirstWord; WordNo <= P.m_iLastWord; WordNo++) { S += Sentence.m_Words[WordNo].m_strWord; if (WordNo < P.m_iLastWord) S += " "; }; return S; } void GetGroups(const CSentence& Sentence, const CAgramtab& A, string& Res) { int nClausesCount = Sentence.GetClausesCount(); for( int ClauseNo = 0; ClauseNo<nClausesCount; ClauseNo++ ) { const CClause& Clause = Sentence.GetClause(ClauseNo); int nCvar = Clause.m_SynVariants.size(); if (Clause.m_SynVariants.empty()) continue; int nVmax = Clause.m_SynVariants.begin()->m_iWeight; for( CSVI pSynVar=Clause.m_SynVariants.begin(); pSynVar != Clause.m_SynVariants.end(); pSynVar++ ) { if( pSynVar->m_iWeight < nVmax ) break; const CMorphVariant& V = *pSynVar; Res += Format("\t<synvar>\n"); // print the clause { int ClauseType = (V.m_ClauseTypeNo == -1) ? UnknownSyntaxElement : Clause.m_vectorTypes[V.m_ClauseTypeNo].m_Type;; string Type; if (ClauseType != UnknownSyntaxElement) Type = (const char*)A.GetClauseNameByType(ClauseType); else Type = "EMPTY"; Res += Format("\t\t<clause type=\"%s\">%s</clause>\n", Type.c_str(), GetWords(Sentence, Clause).c_str()); } for (int GroupNo = 0; GroupNo < V.m_vectorGroups.GetGroups().size(); GroupNo++) { const CGroup& G = V.m_vectorGroups.GetGroups()[GroupNo]; Res += Format("\t\t<group type=\"%s\">%s</group>\n", Sentence.GetOpt()->GetGroupNameByIndex(G.m_GroupType), GetWords(Sentence, G).c_str()); }; Res += Format("\t</synvar>\n"); } } } string GetNodeStr(const CSentence& Sentence, const CRelationsIterator& RelIt, int GroupNo, int WordNo) { if (GroupNo != -1) return GetWords(Sentence, RelIt.GetFirmGroups()[GroupNo]); else return Sentence.m_Words[WordNo].m_strWord; } void GetRelations(const CSentence& Sentence, string& Result) { CRelationsIterator RelIt; RelIt.SetSentence(&Sentence); for( int i = 0; i<Sentence.m_vectorPrClauseNo.size(); i++ ) RelIt.AddClauseNoAndVariantNo(Sentence.m_vectorPrClauseNo[i], 0); RelIt.BuildRelations(); for(long RelNo = 0 ; RelNo < RelIt.GetRelations().size() ; RelNo++ ) { const CSynOutputRelation& piRel = RelIt.GetRelations()[RelNo]; string RelName = Sentence.GetOpt()->GetGroupNameByIndex(piRel.m_Relation.type); string Src = GetNodeStr(Sentence, RelIt,piRel.m_iSourceGroup, piRel.m_Relation.m_iFirstWord); string Trg = GetNodeStr(Sentence, RelIt,piRel.m_iTargetGroup, piRel.m_Relation.m_iLastWord); Result += Format("\t<rel name=\"%s\"> %s -> %s </rel>\n", RelName.c_str(), Src.c_str(), Trg.c_str() ); } } string GetStringBySyntax(const CSentencesCollection& SC, const CAgramtab& A, string input) { string Result; Result += Format("<chunk>\n"); Result += Format("<input>%s</input>\n",input.c_str()); for (size_t nSent=0; nSent < SC.m_vectorSents.size(); nSent++) { const CSentence& Sentence = *SC.m_vectorSents[nSent]; int iWord=0,iClau=0,iCvar=0; Result += "<sent>\n"; GetAnanlytForms(Sentence, Result); GetGroups(Sentence, A, Result); GetRelations(Sentence, Result); Result += "</sent>\n"; } Result += Format("</chunk>\n"); fprintf (stderr, "sentences count: %i\n", SC.m_vectorSents.size()); return Result; }; void PrintUsage() { printf ("Dialing DWDS Command Line Syntax Parser(www.aot.ru, www.dwds.de)\n"); printf ("Usage: TestSynan (RUSSIAN|GERMAN) [filename.txt] - \n"); printf ("Example: TestSynan Russian\n"); exit(1); }; int main(int argc, char* argv[]) { try { MorphLanguageEnum langua = morphUnknown; string FileName; for (size_t i=1; i<argc; i++) { string s = argv[i]; EngMakeLower(s); if ( (s == "-help") || (s == "--help") || (s == "/?") ) PrintUsage(); else { if (langua == morphUnknown) { if (!GetLanguageByString(s, langua)) PrintUsage(); } else { FileName = argv[i]; if (!FileExists(FileName.c_str())) { fprintf (stderr, "cannot open file %s\n", FileName.c_str()); exit(1); } } } } if ((langua == morphUnknown)) PrintUsage(); CSyntaxHolder H; if (!H.LoadSyntax(langua)) { fprintf (stderr, "initialization error\n"); return 1; }; fprintf (stderr, "ok\n"); if (!FileName.empty()) { vector<string> Files; if ((FileName.length() > 4) && FileName.substr(FileName.length() -4) == ".lst") { FILE* fp = fopen(FileName.c_str(), "r"); if (!fp) { fprintf( stderr, "cannot open %s\n", FileName.c_str()); return 1; } char buffer[1024]; while (fgets (buffer, 1024, fp)) { rtrim (buffer); Files.push_back(buffer); } fclose (fp); } else Files.push_back(FileName); for (size_t i=0; i < Files.size(); i++) { fprintf( stderr, "File %s\n", Files[i].c_str()); fflush (stderr); H.m_bTimeStatis = true; H.GetSentencesFromSynAn(Files[i], true); string s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, Files[i].c_str()); printf ("%s\n\n", s.c_str()); } return 0; } // =============== WORKING =============== char buffer[10000] ; while (fgets(buffer, 10000, stdin)) { string s = buffer; Trim(s); if (s.empty()) continue; H.GetSentencesFromSynAn(s, false); s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, s); printf ("%s", s.c_str()); fflush(stdout); }; } catch(...) { fprintf (stderr, "an exception occurred!\n"); return 1; }; return 0; }; <commit_msg>add relation grammems<commit_after>#include <stdio.h> #include "../SynCommonLib/RelationsIterator.h" #include "../common/SyntaxHolder.h" void GetAnanlytForms(const CSentence& Sentence, string& Res) { for( int WordNo = 0; WordNo<Sentence.m_Words.size(); WordNo++ ) { const CSynWord& W = Sentence.m_Words[WordNo]; if (!W.m_MainVerbs.empty()) { Res += string("\t<analyt> ")+ W.m_strWord.c_str(); for (size_t i=0; i< W.m_MainVerbs.size(); i++) { Res += string(" ") + Sentence.m_Words[W.m_MainVerbs[i]].m_strWord; const CSynWord& W_1 = Sentence.m_Words[W.m_MainVerbs[i]]; for (size_t j=0; j< W_1.m_MainVerbs.size(); j++) Res += string(" ") + Sentence.m_Words[W_1.m_MainVerbs[j]].m_strWord; }; Res += "</analyt>\n"; } } } string GetWords(const CSentence& Sentence, const CPeriod& P) { string S; for (int WordNo = P.m_iFirstWord; WordNo <= P.m_iLastWord; WordNo++) { S += Sentence.m_Words[WordNo].m_strWord; if (WordNo < P.m_iLastWord) S += " "; }; return S; } void GetGroups(const CSentence& Sentence, const CAgramtab& A, string& Res) { int nClausesCount = Sentence.GetClausesCount(); for( int ClauseNo = 0; ClauseNo<nClausesCount; ClauseNo++ ) { const CClause& Clause = Sentence.GetClause(ClauseNo); int nCvar = Clause.m_SynVariants.size(); if (Clause.m_SynVariants.empty()) continue; int nVmax = Clause.m_SynVariants.begin()->m_iWeight; for( CSVI pSynVar=Clause.m_SynVariants.begin(); pSynVar != Clause.m_SynVariants.end(); pSynVar++ ) { if( pSynVar->m_iWeight < nVmax ) break; const CMorphVariant& V = *pSynVar; Res += Format("\t<synvar>\n"); // print the clause { int ClauseType = (V.m_ClauseTypeNo == -1) ? UnknownSyntaxElement : Clause.m_vectorTypes[V.m_ClauseTypeNo].m_Type;; string Type; if (ClauseType != UnknownSyntaxElement) Type = (const char*)A.GetClauseNameByType(ClauseType); else Type = "EMPTY"; Res += Format("\t\t<clause type=\"%s\">%s</clause>\n", Type.c_str(), GetWords(Sentence, Clause).c_str()); } for (int GroupNo = 0; GroupNo < V.m_vectorGroups.GetGroups().size(); GroupNo++) { const CGroup& G = V.m_vectorGroups.GetGroups()[GroupNo]; Res += Format("\t\t<group type=\"%s\">%s</group>\n", Sentence.GetOpt()->GetGroupNameByIndex(G.m_GroupType), GetWords(Sentence, G).c_str()); }; Res += Format("\t</synvar>\n"); } } } string GetNodeStr(const CSentence& Sentence, const CRelationsIterator& RelIt, int GroupNo, int WordNo) { if (GroupNo != -1) return GetWords(Sentence, RelIt.GetFirmGroups()[GroupNo]); else return Sentence.m_Words[WordNo].m_strWord; } void GetRelations(const CSentence& Sentence, string& Result) { CRelationsIterator RelIt; RelIt.SetSentence(&Sentence); for( int i = 0; i<Sentence.m_vectorPrClauseNo.size(); i++ ) RelIt.AddClauseNoAndVariantNo(Sentence.m_vectorPrClauseNo[i], 0); RelIt.BuildRelations(); for(long RelNo = 0 ; RelNo < RelIt.GetRelations().size() ; RelNo++ ) { const CSynOutputRelation& piRel = RelIt.GetRelations()[RelNo]; string RelName = Sentence.GetOpt()->GetGroupNameByIndex(piRel.m_Relation.type); string Src = GetNodeStr(Sentence, RelIt,piRel.m_iSourceGroup, piRel.m_Relation.m_iFirstWord); string Trg = GetNodeStr(Sentence, RelIt,piRel.m_iTargetGroup, piRel.m_Relation.m_iLastWord); string GramRel = Sentence.GetOpt()->GetGramTab()->GrammemsToStr(piRel.m_Relation.m_iGrammems); Result += Format("\t<rel name=\"%s\" gram=\"%s\"> %s -> %s </rel>\n", RelName.c_str(), GramRel.c_str(), Src.c_str(), Trg.c_str() ); } } string GetStringBySyntax(const CSentencesCollection& SC, const CAgramtab& A, string input) { string Result; Result += Format("<chunk>\n"); Result += Format("<input>%s</input>\n",input.c_str()); for (size_t nSent=0; nSent < SC.m_vectorSents.size(); nSent++) { const CSentence& Sentence = *SC.m_vectorSents[nSent]; int iWord=0,iClau=0,iCvar=0; Result += "<sent>\n"; GetAnanlytForms(Sentence, Result); GetGroups(Sentence, A, Result); GetRelations(Sentence, Result); Result += "</sent>\n"; } Result += Format("</chunk>\n"); fprintf (stderr, "sentences count: %i\n", SC.m_vectorSents.size()); return Result; }; void PrintUsage() { printf ("Dialing DWDS Command Line Syntax Parser(www.aot.ru, www.dwds.de)\n"); printf ("Usage: TestSynan (RUSSIAN|GERMAN) [filename.txt] - \n"); printf ("Example: TestSynan Russian\n"); exit(1); }; int main(int argc, char* argv[]) { try { MorphLanguageEnum langua = morphUnknown; string FileName; for (size_t i=1; i<argc; i++) { string s = argv[i]; EngMakeLower(s); if ( (s == "-help") || (s == "--help") || (s == "/?") ) PrintUsage(); else { if (langua == morphUnknown) { if (!GetLanguageByString(s, langua)) PrintUsage(); } else { FileName = argv[i]; if (!FileExists(FileName.c_str())) { fprintf (stderr, "cannot open file %s\n", FileName.c_str()); exit(1); } } } } if ((langua == morphUnknown)) PrintUsage(); CSyntaxHolder H; if (!H.LoadSyntax(langua)) { fprintf (stderr, "initialization error\n"); return 1; }; fprintf (stderr, "ok\n"); if (!FileName.empty()) { vector<string> Files; if ((FileName.length() > 4) && FileName.substr(FileName.length() -4) == ".lst") { FILE* fp = fopen(FileName.c_str(), "r"); if (!fp) { fprintf( stderr, "cannot open %s\n", FileName.c_str()); return 1; } char buffer[1024]; while (fgets (buffer, 1024, fp)) { rtrim (buffer); Files.push_back(buffer); } fclose (fp); } else Files.push_back(FileName); for (size_t i=0; i < Files.size(); i++) { fprintf( stderr, "File %s\n", Files[i].c_str()); fflush (stderr); H.m_bTimeStatis = true; H.GetSentencesFromSynAn(Files[i], true); string s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, Files[i].c_str()); printf ("%s\n\n", s.c_str()); } return 0; } // =============== WORKING =============== char buffer[10000] ; while (fgets(buffer, 10000, stdin)) { string s = buffer; Trim(s); if (s.empty()) continue; H.GetSentencesFromSynAn(s, false); s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, s); printf ("%s", s.c_str()); fflush(stdout); }; } catch(...) { fprintf (stderr, "an exception occurred!\n"); return 1; }; return 0; }; <|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <solver/solver.hh> #include <graph/graph.hh> #include <graph/dimacs.hh> #include <max_biclique/naive_max_biclique.hh> #include <max_biclique/cc_max_biclique.hh> #include <max_biclique/ccd_max_biclique.hh> #include <max_biclique/degree_max_biclique.hh> #include <boost/program_options.hpp> #include <iostream> #include <exception> #include <cstdlib> #include <chrono> #include <thread> using namespace parasols; namespace po = boost::program_options; auto main(int argc, char * argv[]) -> int { auto algorithms = { std::make_pair( std::string{ "naive" }, run_this(naive_max_biclique) ), std::make_pair( std::string{ "cc" }, run_this(cc_max_biclique) ), std::make_pair( std::string{ "ccd" }, run_this(ccd_max_biclique) ), std::make_pair( std::string{ "degree" }, run_this(degree_max_biclique) ) }; try { po::options_description display_options{ "Program options" }; display_options.add_options() ("help", "Display help information") ("threads", po::value<int>(), "Number of threads to use (where relevant)") ("stop-after-finding", po::value<int>(), "Stop after finding a biclique of this size") ("initial-bound", po::value<int>(), "Specify an initial bound") ("print-incumbents", "Print new incumbents as they are found") ("timeout", po::value<int>(), "Abort after this many seconds") ("break-ab-symmetry", po::value<bool>(), "Break a/b symmetry (on by default)") ("verify", "Verify that we have found a valid result (for sanity checking changes)") ; po::options_description all_options{ "All options" }; all_options.add_options() ("algorithm", "Specify which algorithm to use") ("input-file", "Specify the input file (DIMACS format)") ; all_options.add(display_options); po::positional_options_description positional_options; positional_options .add("algorithm", 1) .add("input-file", 1) ; po::variables_map options_vars; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), options_vars); po::notify(options_vars); /* --help? Show a message, and exit. */ if (options_vars.count("help")) { std::cout << "Usage: " << argv[0] << " [options] algorithm file" << std::endl; std::cout << std::endl; std::cout << display_options << std::endl; return EXIT_SUCCESS; } /* No algorithm or no input file specified? Show a message and exit. */ if (! options_vars.count("algorithm") || ! options_vars.count("input-file")) { std::cout << "Usage: " << argv[0] << " [options] algorithm file" << std::endl; return EXIT_FAILURE; } /* Turn an algorithm string name into a runnable function. */ auto algorithm = algorithms.begin(), algorithm_end = algorithms.end(); for ( ; algorithm != algorithm_end ; ++algorithm) if (algorithm->first == options_vars["algorithm"].as<std::string>()) break; /* Unknown algorithm? Show a message and exit. */ if (algorithm == algorithm_end) { std::cerr << "Unknown algorithm " << options_vars["algorithm"].as<std::string>() << ", choose from:"; for (auto a : algorithms) std::cerr << " " << a.first; std::cerr << std::endl; return EXIT_FAILURE; } /* Figure out what our options should be. */ MaxBicliqueParams params; if (options_vars.count("threads")) params.n_threads = options_vars["threads"].as<int>(); else params.n_threads = std::thread::hardware_concurrency(); if (options_vars.count("stop-after-finding")) params.stop_after_finding = options_vars["stop-after-finding"].as<int>(); if (options_vars.count("initial-bound")) params.initial_bound = options_vars["initial-bound"].as<int>(); if (options_vars.count("print-incumbents")) params.print_incumbents = true; if (options_vars.count("break-ab-symmetry")) params.break_ab_symmetry = options_vars["break-ab-symmetry"].as<bool>(); /* Read in the graph */ auto graph = read_dimacs(options_vars["input-file"].as<std::string>()); /* Do the actual run. */ bool aborted = false; auto result = algorithm->second( graph, params, aborted, options_vars.count("timeout") ? options_vars["timeout"].as<int>() : 0); /* Stop the clock. */ auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - params.start_time); /* Display the results. */ std::cout << result.size << " " << result.nodes; if (aborted) std::cout << " aborted"; std::cout << std::endl; for (auto & s : { result.members_a, result.members_b }) { for (auto v : s) std::cout << graph.vertex_name(v) << " "; std::cout << std::endl; } std::cout << overall_time.count(); if (! result.times.empty()) { for (auto t : result.times) std::cout << " " << t.count(); } std::cout << std::endl; if (options_vars.count("verify")) { for (auto & a : result.members_a) for (auto & b : result.members_b) if (! graph.adjacent(a, b)) { std::cerr << "Oops! Not adjacent: " << a << " " << b << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } catch (const po::error & e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Try " << argv[0] << " --help" << std::endl; return EXIT_FAILURE; } catch (const std::exception & e) { std::cerr << "Error: " << e.what() << std::endl; return EXIT_FAILURE; } } <commit_msg>Support pairs format for bicliques<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <solver/solver.hh> #include <graph/graph.hh> #include <graph/dimacs.hh> #include <graph/pairs.hh> #include <max_biclique/naive_max_biclique.hh> #include <max_biclique/cc_max_biclique.hh> #include <max_biclique/ccd_max_biclique.hh> #include <max_biclique/degree_max_biclique.hh> #include <boost/program_options.hpp> #include <iostream> #include <exception> #include <cstdlib> #include <chrono> #include <thread> using namespace parasols; namespace po = boost::program_options; auto main(int argc, char * argv[]) -> int { auto algorithms = { std::make_pair( std::string{ "naive" }, run_this(naive_max_biclique) ), std::make_pair( std::string{ "cc" }, run_this(cc_max_biclique) ), std::make_pair( std::string{ "ccd" }, run_this(ccd_max_biclique) ), std::make_pair( std::string{ "degree" }, run_this(degree_max_biclique) ) }; try { po::options_description display_options{ "Program options" }; display_options.add_options() ("help", "Display help information") ("threads", po::value<int>(), "Number of threads to use (where relevant)") ("stop-after-finding", po::value<int>(), "Stop after finding a biclique of this size") ("initial-bound", po::value<int>(), "Specify an initial bound") ("print-incumbents", "Print new incumbents as they are found") ("timeout", po::value<int>(), "Abort after this many seconds") ("break-ab-symmetry", po::value<bool>(), "Break a/b symmetry (on by default)") ("verify", "Verify that we have found a valid result (for sanity checking changes)") ("pairs", "Input is in pairs format, not DIMACS") ; po::options_description all_options{ "All options" }; all_options.add_options() ("algorithm", "Specify which algorithm to use") ("input-file", "Specify the input file (DIMACS format, unless --pairs is specified)") ; all_options.add(display_options); po::positional_options_description positional_options; positional_options .add("algorithm", 1) .add("input-file", 1) ; po::variables_map options_vars; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), options_vars); po::notify(options_vars); /* --help? Show a message, and exit. */ if (options_vars.count("help")) { std::cout << "Usage: " << argv[0] << " [options] algorithm file" << std::endl; std::cout << std::endl; std::cout << display_options << std::endl; return EXIT_SUCCESS; } /* No algorithm or no input file specified? Show a message and exit. */ if (! options_vars.count("algorithm") || ! options_vars.count("input-file")) { std::cout << "Usage: " << argv[0] << " [options] algorithm file" << std::endl; return EXIT_FAILURE; } /* Turn an algorithm string name into a runnable function. */ auto algorithm = algorithms.begin(), algorithm_end = algorithms.end(); for ( ; algorithm != algorithm_end ; ++algorithm) if (algorithm->first == options_vars["algorithm"].as<std::string>()) break; /* Unknown algorithm? Show a message and exit. */ if (algorithm == algorithm_end) { std::cerr << "Unknown algorithm " << options_vars["algorithm"].as<std::string>() << ", choose from:"; for (auto a : algorithms) std::cerr << " " << a.first; std::cerr << std::endl; return EXIT_FAILURE; } /* Figure out what our options should be. */ MaxBicliqueParams params; if (options_vars.count("threads")) params.n_threads = options_vars["threads"].as<int>(); else params.n_threads = std::thread::hardware_concurrency(); if (options_vars.count("stop-after-finding")) params.stop_after_finding = options_vars["stop-after-finding"].as<int>(); if (options_vars.count("initial-bound")) params.initial_bound = options_vars["initial-bound"].as<int>(); if (options_vars.count("print-incumbents")) params.print_incumbents = true; if (options_vars.count("break-ab-symmetry")) params.break_ab_symmetry = options_vars["break-ab-symmetry"].as<bool>(); /* Read in the graph */ auto graph = options_vars.count("pairs") ? read_pairs(options_vars["input-file"].as<std::string>()) : read_dimacs(options_vars["input-file"].as<std::string>()); /* Do the actual run. */ bool aborted = false; auto result = algorithm->second( graph, params, aborted, options_vars.count("timeout") ? options_vars["timeout"].as<int>() : 0); /* Stop the clock. */ auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - params.start_time); /* Display the results. */ std::cout << result.size << " " << result.nodes; if (aborted) std::cout << " aborted"; std::cout << std::endl; for (auto & s : { result.members_a, result.members_b }) { for (auto v : s) std::cout << graph.vertex_name(v) << " "; std::cout << std::endl; } std::cout << overall_time.count(); if (! result.times.empty()) { for (auto t : result.times) std::cout << " " << t.count(); } std::cout << std::endl; if (options_vars.count("verify")) { for (auto & a : result.members_a) for (auto & b : result.members_b) if (! graph.adjacent(a, b)) { std::cerr << "Oops! Not adjacent: " << a << " " << b << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } catch (const po::error & e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Try " << argv[0] << " --help" << std::endl; return EXIT_FAILURE; } catch (const std::exception & e) { std::cerr << "Error: " << e.what() << std::endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief FT5206 class @n FocalTech @n Capacitive Touch Panel Controller ドライバー @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include "common/time.h" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief FT5206 テンプレートクラス @param[in] I2C I2C 制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class I2C> class FT5206 { static const uint8_t FT5206_ADR = 0x38; I2C& i2c_; enum class REG : uint8_t { DEVICE_MODE, // R/W GEST_ID, // R TD_STATUS, // R TOUCH_XH, // R TOUCH_XL, // R TOUCH_YH, // R TOUCH_YL, // R TOUCH2_XH = 0x09, // R TOUCH2_XL, // R TOUCH2_YH, // R TOUCH2_YL, // R TOUCH3_XH = 0x0F, // R TOUCH3_XL, // R TOUCH3_YH, // R TOUCH3_YL, // R TOUCH4_XH = 0x15, // R TOUCH4_XL, // R TOUCH4_YH, // R TOUCH4_YL, // R TOUCH5_XH = 0x1B, // R TOUCH5_XL, // R TOUCH5_YH, // R TOUCH5_YL, // R ID_G_THGROUP = 0x80, // R/W ID_G_THPEAK, // R/W ID_G_THCAL, // R/W ID_G_THWATER, // R/W ID_G_THTEMP, // R/W ID_G_CTRL = 0x86, // R/W ID_G_TIME_ENTER_MONITOR, // R/W ID_G_PERIODACTIVE, // R/W ID_G_PERIODMONITOR, // R/W ID_G_AUTO_CLB_MODE = 0xA0, // R/W ID_G_LIB_VERSION_H, // R ID_G_LIB_VERSION_L, // R ID_G_CIPHER, // R ID_G_MODE, // R ID_G_PMODE, // R ID_G_FIRMID, // R ID_G_STATE, // R ID_G_FT5201ID, // R ID_G_ERR, // R ID_G_CLB, // R/W ID_G_B_AREA_TH = 0xAE, // R/W LOG_MSG_CNT = 0xFE, // R LOG_CUR_CHA // R }; uint8_t touch_num_; void write_(REG reg, uint8_t data) noexcept { uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(reg); tmp[1] = data; i2c_.send(FT5206_ADR, tmp, sizeof(tmp)); } uint8_t read_(REG reg) noexcept { uint8_t tmp[1]; tmp[0] = static_cast<uint8_t>(reg); i2c_.send(FT5206_ADR, tmp, sizeof(tmp)); i2c_.recv(FT5206_ADR, tmp, sizeof(tmp)); return tmp[0]; } uint16_t read16_(REG reg) noexcept { uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(reg); i2c_.send(FT5206_ADR, tmp, 1); i2c_.recv(FT5206_ADR, tmp, sizeof(tmp)); return (static_cast<uint16_t>(tmp[0]) << 8) | tmp[1]; } void read_xy_(REG reg, uint16_t& x, uint16_t& y) noexcept { uint8_t tmp[4]; tmp[0] = static_cast<uint8_t>(reg); i2c_.send(FT5206_ADR, tmp, 1); i2c_.recv(FT5206_ADR, tmp, sizeof(tmp)); x = static_cast<uint16_t>(tmp[0]) | static_cast<uint16_t>(tmp[1]); y = static_cast<uint16_t>(tmp[2]) | static_cast<uint16_t>(tmp[3]); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c 制御クラスを参照で渡す */ //-----------------------------------------------------------------// FT5206(I2C& i2c) noexcept : i2c_(i2c), touch_num_(0) { } //-----------------------------------------------------------------// /*! @brief 開始 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool start() noexcept { uint8_t tmp[3]; tmp[0] = static_cast<uint8_t>(REG::ID_G_LIB_VERSION_H); if(!i2c_.send(FT5206_ADR, tmp, 1)) { utils::format("Send fail\n"); return false; } tmp[0] = 0xff; tmp[1] = 0xff; tmp[2] = 0xff; if(!i2c_.recv(FT5206_ADR, tmp, sizeof(tmp))) { utils::format("Recv fail\n"); return false; } uint16_t ver = (static_cast<uint16_t>(tmp[0]) << 8) | tmp[1]; utils::format("FT5206 Version: %04X, Chip: %02X\n") % ver % static_cast<uint16_t>(tmp[2]); write_(REG::DEVICE_MODE, 0x00); return true; } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() noexcept { #if 0 auto id = read_(REG::GEST_ID); if(id != 0) { utils::format("%02X\n") % static_cast<uint16_t>(id); } #endif // uint16_t x; // uint16_t y; // read_xy_(REG::TOUCH_XH, x, y); // if(x & 0b } }; } <commit_msg>update: manage touch positions<commit_after>#pragma once //=====================================================================// /*! @file @brief FT5206 class @n FocalTech @n Capacitive Touch Panel Controller ドライバー @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include "common/time.h" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief FT5206 テンプレートクラス @param[in] I2C I2C 制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class I2C> class FT5206 { public: struct xy { uint8_t st; uint16_t x; uint16_t y; xy() : st(0), x(0), y(0) { } }; private: static const uint8_t FT5206_ADR = 0x38; I2C& i2c_; enum class REG : uint8_t { DEVICE_MODE, // R/W GEST_ID, // R TD_STATUS, // R TOUCH_XH, // R TOUCH_XL, // R TOUCH_YH, // R TOUCH_YL, // R TOUCH2_XH = 0x09, // R TOUCH2_XL, // R TOUCH2_YH, // R TOUCH2_YL, // R TOUCH3_XH = 0x0F, // R TOUCH3_XL, // R TOUCH3_YH, // R TOUCH3_YL, // R TOUCH4_XH = 0x15, // R TOUCH4_XL, // R TOUCH4_YH, // R TOUCH4_YL, // R TOUCH5_XH = 0x1B, // R TOUCH5_XL, // R TOUCH5_YH, // R TOUCH5_YL, // R ID_G_THGROUP = 0x80, // R/W ID_G_THPEAK, // R/W ID_G_THCAL, // R/W ID_G_THWATER, // R/W ID_G_THTEMP, // R/W ID_G_CTRL = 0x86, // R/W ID_G_TIME_ENTER_MONITOR, // R/W ID_G_PERIODACTIVE, // R/W ID_G_PERIODMONITOR, // R/W ID_G_AUTO_CLB_MODE = 0xA0, // R/W ID_G_LIB_VERSION_H, // R ID_G_LIB_VERSION_L, // R ID_G_CIPHER, // R ID_G_MODE, // R ID_G_PMODE, // R ID_G_FIRMID, // R ID_G_STATE, // R ID_G_FT5201ID, // R ID_G_ERR, // R ID_G_CLB, // R/W ID_G_B_AREA_TH = 0xAE, // R/W LOG_MSG_CNT = 0xFE, // R LOG_CUR_CHA // R }; uint8_t touch_num_; xy xy_[2]; void write_(REG reg, uint8_t data) noexcept { uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(reg); tmp[1] = data; i2c_.send(FT5206_ADR, tmp, sizeof(tmp)); } uint8_t read_(REG reg) noexcept { uint8_t tmp[1]; tmp[0] = static_cast<uint8_t>(reg); i2c_.send(FT5206_ADR, tmp, sizeof(tmp)); i2c_.recv(FT5206_ADR, tmp, sizeof(tmp)); return tmp[0]; } uint16_t read16_(REG reg) noexcept { uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(reg); i2c_.send(FT5206_ADR, tmp, 1); i2c_.recv(FT5206_ADR, tmp, sizeof(tmp)); return (static_cast<uint16_t>(tmp[0]) << 8) | tmp[1]; } void read_touch_() noexcept { uint8_t tmp[10]; tmp[0] = static_cast<uint8_t>(REG::TOUCH_XH); i2c_.send(FT5206_ADR, tmp, 1); i2c_.recv(FT5206_ADR, tmp, sizeof(tmp)); xy_[0].st = tmp[0] >> 6; xy_[0].x = (static_cast<uint16_t>(tmp[0] & 0x3F) << 8) | static_cast<uint16_t>(tmp[1]); xy_[0].y = (static_cast<uint16_t>(tmp[2]) << 8) | static_cast<uint16_t>(tmp[3]); xy_[1].st = tmp[6] >> 6; xy_[1].x = (static_cast<uint16_t>(tmp[6] & 0x3F) << 8) | static_cast<uint16_t>(tmp[7]); xy_[1].y = (static_cast<uint16_t>(tmp[8]) << 8) | static_cast<uint16_t>(tmp[9]); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c 制御クラスを参照で渡す */ //-----------------------------------------------------------------// FT5206(I2C& i2c) noexcept : i2c_(i2c), touch_num_(0) { } //-----------------------------------------------------------------// /*! @brief 開始 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool start() noexcept { uint8_t tmp[3]; tmp[0] = static_cast<uint8_t>(REG::ID_G_LIB_VERSION_H); if(!i2c_.send(FT5206_ADR, tmp, 1)) { utils::format("Send fail\n"); return false; } tmp[0] = 0xff; tmp[1] = 0xff; tmp[2] = 0xff; if(!i2c_.recv(FT5206_ADR, tmp, sizeof(tmp))) { utils::format("Recv fail\n"); return false; } uint16_t ver = (static_cast<uint16_t>(tmp[0]) << 8) | tmp[1]; utils::format("FT5206 Version: %04X, Chip: %02X\n") % ver % static_cast<uint16_t>(tmp[2]); write_(REG::DEVICE_MODE, 0x00); return true; } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() noexcept { touch_num_ = read_(REG::TD_STATUS); if(touch_num_ != 0) { read_touch_(); } } //-----------------------------------------------------------------// /*! @brief タッチ数を取得 @return タッチ数 */ //-----------------------------------------------------------------// uint8_t get_touch_num() const noexcept { return touch_num_; } //-----------------------------------------------------------------// /*! @brief タッチ位置を取得 @param[in] idx タッチ・インデックス(0~1) @return タッチ位置 */ //-----------------------------------------------------------------// const xy& get_touch_pos(uint8_t idx) const noexcept { return xy_[idx & 1]; } }; } <|endoftext|>
<commit_before>// $Id: Hash_test.C,v 1.5 2000/06/16 08:45:51 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/COMMON/hash.h> /////////////////////////// START_TEST(class_name, "$Id: Hash_test.C,v 1.5 2000/06/16 08:45:51 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; char* c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string s1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String s2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; CHECK(hashString(const char* str)) TEST_EQUAL(hashString(c), 140) RESULT CHECK(hashPJWString(const char* str)) TEST_EQUAL(hashPJWString(c), 1450744505) RESULT CHECK(hashElfString(const char* str)) TEST_EQUAL(hashElfString(c), 19269177) RESULT CHECK(Hash(const T& key)) TEST_EQUAL(Hash(1), 1) RESULT CHECK(Hash(const string& s)) TEST_EQUAL(Hash(s1), 140) RESULT CHECK(Hash(const String& s)) TEST_EQUAL(Hash(s2), 140) RESULT CHECK(Hash(void *const& ptr)) void* x = 0; TEST_EQUAL(Hash(x), 0) x = (void*)123; TEST_EQUAL(Hash(x), 106040973) x = (void*)123456789; TEST_EQUAL(Hash(x), 2147483648U) RESULT CHECK(getNextPrime(HashIndex l)) TEST_EQUAL(getNextPrime(0), 3) TEST_EQUAL(getNextPrime(1), 3) TEST_EQUAL(getNextPrime(2), 3) TEST_EQUAL(getNextPrime(3), 3) TEST_EQUAL(getNextPrime(4), 5) TEST_EQUAL(getNextPrime(5), 5) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: additional test for hashPointer removed since floating point inaccuracies lead to differing results on different platforms<commit_after>// $Id: Hash_test.C,v 1.6 2000/06/16 08:48:32 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/COMMON/hash.h> /////////////////////////// START_TEST(class_name, "$Id: Hash_test.C,v 1.6 2000/06/16 08:48:32 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; char* c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string s1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String s2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; CHECK(hashString(const char* str)) TEST_EQUAL(hashString(c), 140) RESULT CHECK(hashPJWString(const char* str)) TEST_EQUAL(hashPJWString(c), 1450744505) RESULT CHECK(hashElfString(const char* str)) TEST_EQUAL(hashElfString(c), 19269177) RESULT CHECK(Hash(const T& key)) TEST_EQUAL(Hash(1), 1) RESULT CHECK(Hash(const string& s)) TEST_EQUAL(Hash(s1), 140) RESULT CHECK(Hash(const String& s)) TEST_EQUAL(Hash(s2), 140) RESULT CHECK(Hash(void *const& ptr)) void* x = 0; TEST_EQUAL(Hash(x), 0) x = (void*)123; TEST_EQUAL(Hash(x), 106040973) RESULT CHECK(getNextPrime(HashIndex l)) TEST_EQUAL(getNextPrime(0), 3) TEST_EQUAL(getNextPrime(1), 3) TEST_EQUAL(getNextPrime(2), 3) TEST_EQUAL(getNextPrime(3), 3) TEST_EQUAL(getNextPrime(4), 5) TEST_EQUAL(getNextPrime(5), 5) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>int main(int argc, char *argv[]) { }<commit_msg>finished 3.2 std::lits & std::copy to std::vector<commit_after># include < cstdlib > // std :: rand () # include < vector > // std :: vector < > # include < list > // std :: list < > # include < iostream > // std :: cout # include < iterator > // std :: ostream_iterator < > # include < algorithm > // std :: reverse , std :: generate int main(int argc, char *argv[]) { std::list<int> rndint; for (int i = 0; i < 100; i++) { //int random = rand()%(max-min+1)+min rndint.push_back(rand() % (100 - 1 + 1) + 1); } std::cout << "Testing size of random int list: " << rndint.size() << '\n'; std::vector<int> rndvec; rndvec.reserve(rndint.size()); std::copy(std::begin(rndint), std::end(rndint), std::back_inserter(rndvec)); std::cout << "Testing size of random int vec: " << rndvec.size() << '\n'; }<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkHierarchicalGraphPipeline.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkHierarchicalGraphPipeline.h" #include "vtkActor.h" #include "vtkActor2D.h" #include "vtkApplyColors.h" #include "vtkConvertSelection.h" #include "vtkDataRepresentation.h" #include "vtkDynamic2DLabelMapper.h" #include "vtkEdgeCenters.h" #include "vtkGraphHierarchicalBundleEdges.h" #include "vtkGraphToPolyData.h" #include "vtkInformation.h" #include "vtkLookupTable.h" #include "vtkObjectFactory.h" #include "vtkPolyDataMapper.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkSplineFilter.h" #include "vtkSplineGraphEdges.h" #include "vtkTextProperty.h" #include "vtkViewTheme.h" vtkCxxRevisionMacro(vtkHierarchicalGraphPipeline, "1.6"); vtkStandardNewMacro(vtkHierarchicalGraphPipeline); vtkHierarchicalGraphPipeline::vtkHierarchicalGraphPipeline() { this->ApplyColors = vtkApplyColors::New(); this->Bundle = vtkGraphHierarchicalBundleEdges::New(); this->GraphToPoly = vtkGraphToPolyData::New(); this->Spline = vtkSplineGraphEdges::New(); this->Mapper = vtkPolyDataMapper::New(); this->Actor = vtkActor::New(); this->TextProperty = vtkTextProperty::New(); this->EdgeCenters = vtkEdgeCenters::New(); this->LabelMapper = vtkDynamic2DLabelMapper::New(); this->LabelActor = vtkActor2D::New(); this->ColorArrayNameInternal = 0; this->LabelArrayNameInternal = 0; /* <graphviz> digraph { "Graph input" -> Bundle "Tree input" -> Bundle Bundle -> Spline -> ApplyColors -> GraphToPoly -> Mapper -> Actor Spline -> EdgeCenters -> LabelMapper -> LabelActor } </graphviz> */ this->Spline->SetInputConnection(this->Bundle->GetOutputPort()); this->ApplyColors->SetInputConnection(this->Spline->GetOutputPort()); this->GraphToPoly->SetInputConnection(this->ApplyColors->GetOutputPort()); this->Mapper->SetInputConnection(this->GraphToPoly->GetOutputPort()); this->Actor->SetMapper(this->Mapper); this->EdgeCenters->SetInputConnection(this->Spline->GetOutputPort()); this->LabelMapper->SetInputConnection(this->EdgeCenters->GetOutputPort()); this->LabelMapper->SetLabelTextProperty(this->TextProperty); this->LabelActor->SetMapper(this->LabelMapper); //this->LabelActor->VisibilityOff(); this->Mapper->SetScalarModeToUseCellFieldData(); this->Mapper->SelectColorArray("vtkApplyColors color"); this->Mapper->ScalarVisibilityOn(); this->Actor->PickableOn(); // Make sure this gets rendered on top this->Actor->SetPosition(0.0, 0.0, 1.0); this->Bundle->SetBundlingStrength(0.5); //this->Spline->GetSplineFilter()->SetMaximumNumberOfSubdivisions(16); } vtkHierarchicalGraphPipeline::~vtkHierarchicalGraphPipeline() { this->SetColorArrayNameInternal(0); this->SetLabelArrayNameInternal(0); this->ApplyColors->Delete(); this->Bundle->Delete(); this->GraphToPoly->Delete(); this->Spline->Delete(); this->Mapper->Delete(); this->Actor->Delete(); this->TextProperty->Delete(); this->EdgeCenters->Delete(); this->LabelMapper->Delete(); this->LabelActor->Delete(); } void vtkHierarchicalGraphPipeline::SetBundlingStrength(double strength) { this->Bundle->SetBundlingStrength(strength); } double vtkHierarchicalGraphPipeline::GetBundlingStrength() { return this->Bundle->GetBundlingStrength(); } void vtkHierarchicalGraphPipeline::SetLabelArrayName(const char* name) { this->LabelMapper->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, name); this->SetLabelArrayNameInternal(name); } const char* vtkHierarchicalGraphPipeline::GetLabelArrayName() { return this->GetLabelArrayNameInternal(); } void vtkHierarchicalGraphPipeline::SetLabelVisibility(bool vis) { this->LabelActor->SetVisibility(vis); } bool vtkHierarchicalGraphPipeline::GetLabelVisibility() { return (this->LabelActor->GetVisibility() ? true : false); } void vtkHierarchicalGraphPipeline::SetLabelTextProperty(vtkTextProperty* prop) { this->TextProperty->ShallowCopy(prop); } vtkTextProperty* vtkHierarchicalGraphPipeline::GetLabelTextProperty() { return this->TextProperty; } void vtkHierarchicalGraphPipeline::SetColorArrayName(const char* name) { this->SetColorArrayNameInternal(name); this->ApplyColors->SetInputArrayToProcess(1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_EDGES, name); } const char* vtkHierarchicalGraphPipeline::GetColorArrayName() { return this->GetColorArrayNameInternal(); } void vtkHierarchicalGraphPipeline::SetColorEdgesByArray(bool vis) { this->ApplyColors->SetUseCellLookupTable(vis); } bool vtkHierarchicalGraphPipeline::GetColorEdgesByArray() { return this->ApplyColors->GetUseCellLookupTable(); } void vtkHierarchicalGraphPipeline::SetVisibility(bool vis) { this->Actor->SetVisibility(vis); } bool vtkHierarchicalGraphPipeline::GetVisibility() { return this->Actor->GetVisibility() ? true : false; } void vtkHierarchicalGraphPipeline::PrepareInputConnections( vtkAlgorithmOutput* graphConn, vtkAlgorithmOutput* treeConn, vtkAlgorithmOutput* annConn) { this->Bundle->SetInputConnection(0, graphConn); this->Bundle->SetInputConnection(1, treeConn); this->ApplyColors->SetInputConnection(1, annConn); } vtkSelection* vtkHierarchicalGraphPipeline::ConvertSelection(vtkDataRepresentation* rep, vtkSelection* sel) { vtkSelection* converted = vtkSelection::New(); for (unsigned int j = 0; j < sel->GetNumberOfNodes(); ++j) { vtkSelectionNode* node = sel->GetNode(j); vtkProp* prop = vtkProp::SafeDownCast( node->GetProperties()->Get(vtkSelectionNode::PROP())); if (prop == this->Actor) { vtkDataObject* input = this->Bundle->GetInputDataObject(0, 0); vtkDataObject* poly = this->GraphToPoly->GetOutput(); vtkSmartPointer<vtkSelection> edgeSel = vtkSmartPointer<vtkSelection>::New(); vtkSmartPointer<vtkSelectionNode> nodeCopy = vtkSmartPointer<vtkSelectionNode>::New(); nodeCopy->ShallowCopy(node); nodeCopy->GetProperties()->Remove(vtkSelectionNode::PROP()); edgeSel->AddNode(nodeCopy); vtkSelection* polyConverted = vtkConvertSelection::ToSelectionType( edgeSel, poly, vtkSelectionNode::PEDIGREEIDS); for (unsigned int i = 0; i < polyConverted->GetNumberOfNodes(); ++i) { polyConverted->GetNode(i)->SetFieldType(vtkSelectionNode::EDGE); } vtkSelection* edgeConverted = vtkConvertSelection::ToSelectionType( polyConverted, input, rep->GetSelectionType(), rep->GetSelectionArrayNames()); for (unsigned int i = 0; i < edgeConverted->GetNumberOfNodes(); ++i) { converted->AddNode(edgeConverted->GetNode(i)); } polyConverted->Delete(); edgeConverted->Delete(); } } return converted; } void vtkHierarchicalGraphPipeline::ApplyViewTheme(vtkViewTheme* theme) { this->ApplyColors->SetDefaultCellColor(theme->GetCellColor()); this->ApplyColors->SetDefaultCellOpacity(theme->GetCellOpacity()); this->ApplyColors->SetSelectedCellColor(theme->GetSelectedCellColor()); this->ApplyColors->SetSelectedCellOpacity(theme->GetSelectedCellOpacity()); vtkScalarsToColors* oldLut = this->ApplyColors->GetCellLookupTable(); if (!theme->LookupMatchesCellTheme(oldLut)) { vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New(); lut->SetHueRange(theme->GetCellHueRange()); lut->SetSaturationRange(theme->GetCellSaturationRange()); lut->SetValueRange(theme->GetCellValueRange()); lut->SetAlphaRange(theme->GetCellAlphaRange()); lut->Build(); this->ApplyColors->SetCellLookupTable(lut); } this->TextProperty->SetColor(theme->GetEdgeLabelColor()); } void vtkHierarchicalGraphPipeline::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Actor: "; if (this->Actor && this->Bundle->GetNumberOfInputConnections(0) > 0) { os << "\n"; this->Actor->PrintSelf(os, indent.GetNextIndent()); } else { os << "(none)\n"; } } <commit_msg>BUG: Labels should be off by default.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkHierarchicalGraphPipeline.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkHierarchicalGraphPipeline.h" #include "vtkActor.h" #include "vtkActor2D.h" #include "vtkApplyColors.h" #include "vtkConvertSelection.h" #include "vtkDataRepresentation.h" #include "vtkDynamic2DLabelMapper.h" #include "vtkEdgeCenters.h" #include "vtkGraphHierarchicalBundleEdges.h" #include "vtkGraphToPolyData.h" #include "vtkInformation.h" #include "vtkLookupTable.h" #include "vtkObjectFactory.h" #include "vtkPolyDataMapper.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkSplineFilter.h" #include "vtkSplineGraphEdges.h" #include "vtkTextProperty.h" #include "vtkViewTheme.h" vtkCxxRevisionMacro(vtkHierarchicalGraphPipeline, "1.7"); vtkStandardNewMacro(vtkHierarchicalGraphPipeline); vtkHierarchicalGraphPipeline::vtkHierarchicalGraphPipeline() { this->ApplyColors = vtkApplyColors::New(); this->Bundle = vtkGraphHierarchicalBundleEdges::New(); this->GraphToPoly = vtkGraphToPolyData::New(); this->Spline = vtkSplineGraphEdges::New(); this->Mapper = vtkPolyDataMapper::New(); this->Actor = vtkActor::New(); this->TextProperty = vtkTextProperty::New(); this->EdgeCenters = vtkEdgeCenters::New(); this->LabelMapper = vtkDynamic2DLabelMapper::New(); this->LabelActor = vtkActor2D::New(); this->ColorArrayNameInternal = 0; this->LabelArrayNameInternal = 0; /* <graphviz> digraph { "Graph input" -> Bundle "Tree input" -> Bundle Bundle -> Spline -> ApplyColors -> GraphToPoly -> Mapper -> Actor Spline -> EdgeCenters -> LabelMapper -> LabelActor } </graphviz> */ this->Spline->SetInputConnection(this->Bundle->GetOutputPort()); this->ApplyColors->SetInputConnection(this->Spline->GetOutputPort()); this->GraphToPoly->SetInputConnection(this->ApplyColors->GetOutputPort()); this->Mapper->SetInputConnection(this->GraphToPoly->GetOutputPort()); this->Actor->SetMapper(this->Mapper); this->EdgeCenters->SetInputConnection(this->Spline->GetOutputPort()); this->LabelMapper->SetInputConnection(this->EdgeCenters->GetOutputPort()); this->LabelMapper->SetLabelTextProperty(this->TextProperty); this->LabelActor->SetMapper(this->LabelMapper); this->LabelActor->VisibilityOff(); this->Mapper->SetScalarModeToUseCellFieldData(); this->Mapper->SelectColorArray("vtkApplyColors color"); this->Mapper->ScalarVisibilityOn(); this->Actor->PickableOn(); // Make sure this gets rendered on top this->Actor->SetPosition(0.0, 0.0, 1.0); this->Bundle->SetBundlingStrength(0.5); //this->Spline->GetSplineFilter()->SetMaximumNumberOfSubdivisions(16); } vtkHierarchicalGraphPipeline::~vtkHierarchicalGraphPipeline() { this->SetColorArrayNameInternal(0); this->SetLabelArrayNameInternal(0); this->ApplyColors->Delete(); this->Bundle->Delete(); this->GraphToPoly->Delete(); this->Spline->Delete(); this->Mapper->Delete(); this->Actor->Delete(); this->TextProperty->Delete(); this->EdgeCenters->Delete(); this->LabelMapper->Delete(); this->LabelActor->Delete(); } void vtkHierarchicalGraphPipeline::SetBundlingStrength(double strength) { this->Bundle->SetBundlingStrength(strength); } double vtkHierarchicalGraphPipeline::GetBundlingStrength() { return this->Bundle->GetBundlingStrength(); } void vtkHierarchicalGraphPipeline::SetLabelArrayName(const char* name) { this->LabelMapper->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, name); this->SetLabelArrayNameInternal(name); } const char* vtkHierarchicalGraphPipeline::GetLabelArrayName() { return this->GetLabelArrayNameInternal(); } void vtkHierarchicalGraphPipeline::SetLabelVisibility(bool vis) { this->LabelActor->SetVisibility(vis); } bool vtkHierarchicalGraphPipeline::GetLabelVisibility() { return (this->LabelActor->GetVisibility() ? true : false); } void vtkHierarchicalGraphPipeline::SetLabelTextProperty(vtkTextProperty* prop) { this->TextProperty->ShallowCopy(prop); } vtkTextProperty* vtkHierarchicalGraphPipeline::GetLabelTextProperty() { return this->TextProperty; } void vtkHierarchicalGraphPipeline::SetColorArrayName(const char* name) { this->SetColorArrayNameInternal(name); this->ApplyColors->SetInputArrayToProcess(1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_EDGES, name); } const char* vtkHierarchicalGraphPipeline::GetColorArrayName() { return this->GetColorArrayNameInternal(); } void vtkHierarchicalGraphPipeline::SetColorEdgesByArray(bool vis) { this->ApplyColors->SetUseCellLookupTable(vis); } bool vtkHierarchicalGraphPipeline::GetColorEdgesByArray() { return this->ApplyColors->GetUseCellLookupTable(); } void vtkHierarchicalGraphPipeline::SetVisibility(bool vis) { this->Actor->SetVisibility(vis); } bool vtkHierarchicalGraphPipeline::GetVisibility() { return this->Actor->GetVisibility() ? true : false; } void vtkHierarchicalGraphPipeline::PrepareInputConnections( vtkAlgorithmOutput* graphConn, vtkAlgorithmOutput* treeConn, vtkAlgorithmOutput* annConn) { this->Bundle->SetInputConnection(0, graphConn); this->Bundle->SetInputConnection(1, treeConn); this->ApplyColors->SetInputConnection(1, annConn); } vtkSelection* vtkHierarchicalGraphPipeline::ConvertSelection(vtkDataRepresentation* rep, vtkSelection* sel) { vtkSelection* converted = vtkSelection::New(); for (unsigned int j = 0; j < sel->GetNumberOfNodes(); ++j) { vtkSelectionNode* node = sel->GetNode(j); vtkProp* prop = vtkProp::SafeDownCast( node->GetProperties()->Get(vtkSelectionNode::PROP())); if (prop == this->Actor) { vtkDataObject* input = this->Bundle->GetInputDataObject(0, 0); vtkDataObject* poly = this->GraphToPoly->GetOutput(); vtkSmartPointer<vtkSelection> edgeSel = vtkSmartPointer<vtkSelection>::New(); vtkSmartPointer<vtkSelectionNode> nodeCopy = vtkSmartPointer<vtkSelectionNode>::New(); nodeCopy->ShallowCopy(node); nodeCopy->GetProperties()->Remove(vtkSelectionNode::PROP()); edgeSel->AddNode(nodeCopy); vtkSelection* polyConverted = vtkConvertSelection::ToSelectionType( edgeSel, poly, vtkSelectionNode::PEDIGREEIDS); for (unsigned int i = 0; i < polyConverted->GetNumberOfNodes(); ++i) { polyConverted->GetNode(i)->SetFieldType(vtkSelectionNode::EDGE); } vtkSelection* edgeConverted = vtkConvertSelection::ToSelectionType( polyConverted, input, rep->GetSelectionType(), rep->GetSelectionArrayNames()); for (unsigned int i = 0; i < edgeConverted->GetNumberOfNodes(); ++i) { converted->AddNode(edgeConverted->GetNode(i)); } polyConverted->Delete(); edgeConverted->Delete(); } } return converted; } void vtkHierarchicalGraphPipeline::ApplyViewTheme(vtkViewTheme* theme) { this->ApplyColors->SetDefaultCellColor(theme->GetCellColor()); this->ApplyColors->SetDefaultCellOpacity(theme->GetCellOpacity()); this->ApplyColors->SetSelectedCellColor(theme->GetSelectedCellColor()); this->ApplyColors->SetSelectedCellOpacity(theme->GetSelectedCellOpacity()); vtkScalarsToColors* oldLut = this->ApplyColors->GetCellLookupTable(); if (!theme->LookupMatchesCellTheme(oldLut)) { vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New(); lut->SetHueRange(theme->GetCellHueRange()); lut->SetSaturationRange(theme->GetCellSaturationRange()); lut->SetValueRange(theme->GetCellValueRange()); lut->SetAlphaRange(theme->GetCellAlphaRange()); lut->Build(); this->ApplyColors->SetCellLookupTable(lut); } this->TextProperty->SetColor(theme->GetEdgeLabelColor()); } void vtkHierarchicalGraphPipeline::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Actor: "; if (this->Actor && this->Bundle->GetNumberOfInputConnections(0) > 0) { os << "\n"; this->Actor->PrintSelf(os, indent.GetNextIndent()); } else { os << "(none)\n"; } } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "items/Static.h" #include "VisualizationException.h" #include "shapes/Shape.h" namespace Visualization { ITEM_COMMON_DEFINITIONS(Static, "item") QMap<QString, Static::staticItemConstructorType> Static::itemClasses_; QMap<QString, Static::staticItemStyleConstructorType> Static::itemStyles_; Static::Static(Item* parent, const StyleType *style) : Super(parent, style), item_(nullptr) { } Static::~Static() { SAFE_DELETE_ITEM(item_); } bool Static::isEmpty() const { return style()->isEmpty(); } bool Static::sizeDependsOnParent() const { if (item_) return item_->sizeDependsOnParent(); else return false; } void Static::updateGeometry(int availableWidth, int availableHeight) { if (item_) Item::updateGeometry(item_, availableWidth, availableHeight); else { if (hasShape()) { getShape()->setOffset(0, 0); getShape()->setInnerSize(0, 0); } else setSize(QSize(0, 0)); } } void Static::determineChildren() { if (style()->isEmpty()) SAFE_DELETE_ITEM(item_); else { if (item_ && item_->style() != &style()->itemStyle()) { SAFE_DELETE_ITEM(item_); } if (!item_) { if (itemClasses_.contains(style()->itemClass())) item_ = itemClasses_.value(style()->itemClass())(this, &style()->itemStyle()); else throw VisualizationException("Invalid item class specified for a Static item"); } item_->setStyle( &style()->itemStyle()); } } ItemStyle* Static::constructStyle(const QString& itemClass) { if (itemStyles_.contains(itemClass)) return itemStyles_.value(itemClass)(); else return nullptr; } } <commit_msg>Fix a bug with Static items adopting the shape of their content<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "items/Static.h" #include "VisualizationException.h" #include "shapes/Shape.h" namespace Visualization { ITEM_COMMON_DEFINITIONS(Static, "item") QMap<QString, Static::staticItemConstructorType> Static::itemClasses_; QMap<QString, Static::staticItemStyleConstructorType> Static::itemStyles_; Static::Static(Item* parent, const StyleType *style) : Super(parent, style), item_(nullptr) { removeShape(); // The shape should only show for the contained static item. } Static::~Static() { SAFE_DELETE_ITEM(item_); } bool Static::isEmpty() const { return style()->isEmpty(); } bool Static::sizeDependsOnParent() const { if (item_) return item_->sizeDependsOnParent(); else return false; } void Static::updateGeometry(int availableWidth, int availableHeight) { if (item_) Item::updateGeometry(item_, availableWidth, availableHeight); else { if (hasShape()) { getShape()->setOffset(0, 0); getShape()->setInnerSize(0, 0); } else setSize(QSize(0, 0)); } } void Static::determineChildren() { if (style()->isEmpty()) SAFE_DELETE_ITEM(item_); else { if (item_ && item_->style() != &style()->itemStyle()) { SAFE_DELETE_ITEM(item_); } if (!item_) { if (itemClasses_.contains(style()->itemClass())) item_ = itemClasses_.value(style()->itemClass())(this, &style()->itemStyle()); else throw VisualizationException("Invalid item class specified for a Static item"); } item_->setStyle( &style()->itemStyle()); } } ItemStyle* Static::constructStyle(const QString& itemClass) { if (itemStyles_.contains(itemClass)) return itemStyles_.value(itemClass)(); else return nullptr; } } <|endoftext|>
<commit_before>/** * * Copyright (c) 2021 Project CHIP Authors * * 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 <app-common/zap-generated/attributes/Accessors.h> #include <app-common/zap-generated/cluster-objects.h> #include <app-common/zap-generated/ids/Attributes.h> #include <app-common/zap-generated/ids/Clusters.h> #include <app/AttributeAccessInterface.h> #include <app/CommandHandler.h> #include <app/ConcreteCommandPath.h> #include <app/util/af.h> #include <app/util/attribute-storage.h> #include <lib/core/Optional.h> #include <platform/DiagnosticDataProvider.h> using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::SoftwareDiagnostics; using namespace chip::app::Clusters::SoftwareDiagnostics::Attributes; using chip::DeviceLayer::DiagnosticDataProvider; using chip::DeviceLayer::GetDiagnosticDataProvider; namespace { class SoftwareDiagosticsAttrAccess : public AttributeAccessInterface { public: // Register for the SoftwareDiagnostics cluster on all endpoints. SoftwareDiagosticsAttrAccess() : AttributeAccessInterface(Optional<EndpointId>::Missing(), SoftwareDiagnostics::Id) {} CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; private: CHIP_ERROR ReadIfSupported(CHIP_ERROR (DiagnosticDataProvider::*getter)(uint64_t &), AttributeValueEncoder & aEncoder); CHIP_ERROR ReadThreadMetrics(AttributeValueEncoder & aEncoder); }; SoftwareDiagosticsAttrAccess gAttrAccess; CHIP_ERROR SoftwareDiagosticsAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) { if (aPath.mClusterId != SoftwareDiagnostics::Id) { // We shouldn't have been called at all. return CHIP_ERROR_INVALID_ARGUMENT; } switch (aPath.mAttributeId) { case CurrentHeapFree::Id: { return ReadIfSupported(&DiagnosticDataProvider::GetCurrentHeapFree, aEncoder); } case CurrentHeapUsed::Id: { return ReadIfSupported(&DiagnosticDataProvider::GetCurrentHeapUsed, aEncoder); } case CurrentHeapHighWatermark::Id: { return ReadIfSupported(&DiagnosticDataProvider::GetCurrentHeapHighWatermark, aEncoder); } case ThreadMetrics::Id: { return ReadThreadMetrics(aEncoder); } default: { break; } } return CHIP_NO_ERROR; } CHIP_ERROR SoftwareDiagosticsAttrAccess::ReadIfSupported(CHIP_ERROR (DiagnosticDataProvider::*getter)(uint64_t &), AttributeValueEncoder & aEncoder) { uint64_t data; CHIP_ERROR err = (DeviceLayer::GetDiagnosticDataProvider().*getter)(data); if (err == CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE) { data = 0; } else if (err != CHIP_NO_ERROR) { return err; } return aEncoder.Encode(data); } CHIP_ERROR SoftwareDiagosticsAttrAccess::ReadThreadMetrics(AttributeValueEncoder & aEncoder) { CHIP_ERROR err = CHIP_NO_ERROR; DeviceLayer::ThreadMetrics * threadMetrics; if (DeviceLayer::GetDiagnosticDataProvider().GetThreadMetrics(&threadMetrics) == CHIP_NO_ERROR) { err = aEncoder.EncodeList([&threadMetrics](const auto & encoder) -> CHIP_ERROR { for (DeviceLayer::ThreadMetrics * thread = threadMetrics; thread != nullptr; thread = thread->Next) { ReturnErrorOnFailure(encoder.Encode(*thread)); } return CHIP_NO_ERROR; }); DeviceLayer::GetDiagnosticDataProvider().ReleaseThreadMetrics(threadMetrics); } else { err = aEncoder.Encode(DataModel::List<EndpointId>()); } return err; } class SoftwareDiagnosticsDelegate : public DeviceLayer::SoftwareDiagnosticsDelegate { // Gets called when a software fault that has taken place on the Node. void OnSoftwareFaultDetected(SoftwareDiagnostics::Structs::SoftwareFault::Type & softwareFault) override { ChipLogProgress(Zcl, "SoftwareDiagnosticsDelegate: OnSoftwareFaultDetected"); ForAllEndpointsWithServerCluster(GeneralDiagnostics::Id, [](EndpointId endpoint, intptr_t) -> Loop { // TODO: Log SoftwareFault event and walk them all. return Loop::Break; }); } }; SoftwareDiagnosticsDelegate gDiagnosticDelegate; } // anonymous namespace bool emberAfSoftwareDiagnosticsClusterResetWatermarksCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::ResetWatermarks::DecodableType & commandData) { EndpointId endpoint = commandPath.mEndpointId; uint64_t currentHeapUsed; EmberAfStatus status = SoftwareDiagnostics::Attributes::CurrentHeapUsed::Get(endpoint, &currentHeapUsed); VerifyOrExit(status == EMBER_ZCL_STATUS_SUCCESS, ChipLogError(Zcl, "Failed to get the value of the CurrentHeapUsed attribute")); status = SoftwareDiagnostics::Attributes::CurrentHeapHighWatermark::Set(endpoint, currentHeapUsed); VerifyOrExit( status == EMBER_ZCL_STATUS_SUCCESS, ChipLogError( Zcl, "Failed to reset the value of the CurrentHeapHighWaterMark attribute to the value of the CurrentHeapUsed attribute")); exit: emberAfSendImmediateDefaultResponse(status); return true; } void MatterSoftwareDiagnosticsPluginServerInitCallback() { registerAttributeAccessOverride(&gAttrAccess); GetDiagnosticDataProvider().SetSoftwareDiagnosticsDelegate(&gDiagnosticDelegate); } <commit_msg>Calls user-supplied function for every endpoint that has correct given server cluster (#12574)<commit_after>/** * * Copyright (c) 2021 Project CHIP Authors * * 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 <app-common/zap-generated/attributes/Accessors.h> #include <app-common/zap-generated/cluster-objects.h> #include <app-common/zap-generated/ids/Attributes.h> #include <app-common/zap-generated/ids/Clusters.h> #include <app/AttributeAccessInterface.h> #include <app/CommandHandler.h> #include <app/ConcreteCommandPath.h> #include <app/util/af.h> #include <app/util/attribute-storage.h> #include <lib/core/Optional.h> #include <platform/DiagnosticDataProvider.h> using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::SoftwareDiagnostics; using namespace chip::app::Clusters::SoftwareDiagnostics::Attributes; using chip::DeviceLayer::DiagnosticDataProvider; using chip::DeviceLayer::GetDiagnosticDataProvider; namespace { class SoftwareDiagosticsAttrAccess : public AttributeAccessInterface { public: // Register for the SoftwareDiagnostics cluster on all endpoints. SoftwareDiagosticsAttrAccess() : AttributeAccessInterface(Optional<EndpointId>::Missing(), SoftwareDiagnostics::Id) {} CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; private: CHIP_ERROR ReadIfSupported(CHIP_ERROR (DiagnosticDataProvider::*getter)(uint64_t &), AttributeValueEncoder & aEncoder); CHIP_ERROR ReadThreadMetrics(AttributeValueEncoder & aEncoder); }; SoftwareDiagosticsAttrAccess gAttrAccess; CHIP_ERROR SoftwareDiagosticsAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) { if (aPath.mClusterId != SoftwareDiagnostics::Id) { // We shouldn't have been called at all. return CHIP_ERROR_INVALID_ARGUMENT; } switch (aPath.mAttributeId) { case CurrentHeapFree::Id: { return ReadIfSupported(&DiagnosticDataProvider::GetCurrentHeapFree, aEncoder); } case CurrentHeapUsed::Id: { return ReadIfSupported(&DiagnosticDataProvider::GetCurrentHeapUsed, aEncoder); } case CurrentHeapHighWatermark::Id: { return ReadIfSupported(&DiagnosticDataProvider::GetCurrentHeapHighWatermark, aEncoder); } case ThreadMetrics::Id: { return ReadThreadMetrics(aEncoder); } default: { break; } } return CHIP_NO_ERROR; } CHIP_ERROR SoftwareDiagosticsAttrAccess::ReadIfSupported(CHIP_ERROR (DiagnosticDataProvider::*getter)(uint64_t &), AttributeValueEncoder & aEncoder) { uint64_t data; CHIP_ERROR err = (DeviceLayer::GetDiagnosticDataProvider().*getter)(data); if (err == CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE) { data = 0; } else if (err != CHIP_NO_ERROR) { return err; } return aEncoder.Encode(data); } CHIP_ERROR SoftwareDiagosticsAttrAccess::ReadThreadMetrics(AttributeValueEncoder & aEncoder) { CHIP_ERROR err = CHIP_NO_ERROR; DeviceLayer::ThreadMetrics * threadMetrics; if (DeviceLayer::GetDiagnosticDataProvider().GetThreadMetrics(&threadMetrics) == CHIP_NO_ERROR) { err = aEncoder.EncodeList([&threadMetrics](const auto & encoder) -> CHIP_ERROR { for (DeviceLayer::ThreadMetrics * thread = threadMetrics; thread != nullptr; thread = thread->Next) { ReturnErrorOnFailure(encoder.Encode(*thread)); } return CHIP_NO_ERROR; }); DeviceLayer::GetDiagnosticDataProvider().ReleaseThreadMetrics(threadMetrics); } else { err = aEncoder.Encode(DataModel::List<EndpointId>()); } return err; } class SoftwareDiagnosticsDelegate : public DeviceLayer::SoftwareDiagnosticsDelegate { // Gets called when a software fault that has taken place on the Node. void OnSoftwareFaultDetected(SoftwareDiagnostics::Structs::SoftwareFault::Type & softwareFault) override { ChipLogProgress(Zcl, "SoftwareDiagnosticsDelegate: OnSoftwareFaultDetected"); ForAllEndpointsWithServerCluster(SoftwareDiagnostics::Id, [](EndpointId endpoint, intptr_t) -> Loop { // TODO: Log SoftwareFault event and walk them all. return Loop::Break; }); } }; SoftwareDiagnosticsDelegate gDiagnosticDelegate; } // anonymous namespace bool emberAfSoftwareDiagnosticsClusterResetWatermarksCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::ResetWatermarks::DecodableType & commandData) { EndpointId endpoint = commandPath.mEndpointId; uint64_t currentHeapUsed; EmberAfStatus status = SoftwareDiagnostics::Attributes::CurrentHeapUsed::Get(endpoint, &currentHeapUsed); VerifyOrExit(status == EMBER_ZCL_STATUS_SUCCESS, ChipLogError(Zcl, "Failed to get the value of the CurrentHeapUsed attribute")); status = SoftwareDiagnostics::Attributes::CurrentHeapHighWatermark::Set(endpoint, currentHeapUsed); VerifyOrExit( status == EMBER_ZCL_STATUS_SUCCESS, ChipLogError( Zcl, "Failed to reset the value of the CurrentHeapHighWaterMark attribute to the value of the CurrentHeapUsed attribute")); exit: emberAfSendImmediateDefaultResponse(status); return true; } void MatterSoftwareDiagnosticsPluginServerInitCallback() { registerAttributeAccessOverride(&gAttrAccess); GetDiagnosticDataProvider().SetSoftwareDiagnosticsDelegate(&gDiagnosticDelegate); } <|endoftext|>
<commit_before>// Copyright (c) 2019 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include "common.hh" namespace sparrow { enum class TokenKind { #undef TOKDEF #define TOKDEF(k, s) k, #include "kinds_def.hh" #undef TOKDEF NUM_KINDS }; const char* get_token_name(TokenKind kind); TokenKind get_keyword_kind(const char* key); class Token : public Copyable { TokenKind kind_{TokenKind::TK_UNKNOWN}; str_t literal_; int lineno_{1}; public: Token(void) noexcept {} Token(TokenKind kind, const str_t& literal, int lineno = 1) noexcept : kind_{kind}, literal_{literal}, lineno_{lineno} { } inline TokenKind kind(void) const { return kind_; } inline str_t literal(void) const { return literal_; } inline int lineno(void) const { return lineno_; } inline double as_numeric(void) const { return std::atof(literal_.c_str()); } inline str_t as_string(void) const { return literal_; } inline const char* as_cstring(void) const { return literal_.c_str(); } inline bool operator==(const Token& r) const { return literal_ == r.literal_; } inline bool operator!=(const Token& r) const { return literal_ != r.literal_; } str_t stringify(void) const; static Token make_custom(const str_t& literal = "") { return Token{TokenKind::TK_STRING, literal, 0}; } }; std::ostream& operator<<(std::ostream& out, const Token& tok); } <commit_msg>:construction: chore(token): updated the token definitions<commit_after>// Copyright (c) 2019 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include "common.hh" namespace sparrow { enum class TokenKind { #undef TOKDEF #define TOKDEF(k, s) k, #include "kinds_def.hh" #undef TOKDEF NUM_KINDS }; const char* get_token_name(TokenKind kind); TokenKind get_keyword_kind(const char* key); class Token : public Copyable { TokenKind kind_{TokenKind::TK_UNKNOWN}; str_t literal_; int lineno_{1}; public: Token(void) noexcept {} Token(TokenKind kind, const str_t& literal, int lineno = 1) noexcept : kind_{kind}, literal_{literal}, lineno_{lineno} { } Token(const Token& r) noexcept : kind_{r.kind_}, literal_{r.literal_}, lineno_{r.lineno_} { } Token(Token&& r) noexcept : kind_{std::move(r.kind_)} , literal_{std::move(r.literal_)} , lineno_{std::move(r.lineno_)} { } inline Token& operator=(const Token& r) noexcept { if (this != &r) { kind_ = r.kind_; literal_ = r.literal_; lineno_ = r.lineno_; } return *this; } inline Token& operator=(Token&& r) noexcept { if (this != &r) { kind_ = std::move(r.kind_); literal_ = std::move(r.literal_); lineno_ = std::move(r.lineno_); } return *this; } inline TokenKind kind(void) const { return kind_; } inline str_t literal(void) const { return literal_; } inline int lineno(void) const { return lineno_; } inline double as_numeric(void) const { return std::atof(literal_.c_str()); } inline str_t as_string(void) const { return literal_; } inline const char* as_cstring(void) const { return literal_.c_str(); } inline bool operator==(const Token& r) const { return literal_ == r.literal_; } inline bool operator!=(const Token& r) const { return literal_ != r.literal_; } str_t stringify(void) const; static Token make_custom(const str_t& literal = "") { return Token{TokenKind::TK_STRING, literal, 0}; } }; std::ostream& operator<<(std::ostream& out, const Token& tok); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: measctrl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: cl $ $Date: 2002-06-06 09:08:03 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #pragma hdrstop #include "xoutx.hxx" #include "svdomeas.hxx" #include "svdmodel.hxx" //#include "svdrwobj.hxx" // SdrPaintInfoRec #include "measctrl.hxx" #include "dialmgr.hxx" #include "dlgutil.hxx" /************************************************************************* |* |* Ctor SvxXMeasurePreview |* *************************************************************************/ SvxXMeasurePreview::SvxXMeasurePreview ( Window* pParent, const ResId& rResId, const SfxItemSet& rInAttrs ) : Control ( pParent, rResId ), rAttrs ( rInAttrs ) { pExtOutDev = new ExtOutputDevice( this ); SetMapMode( MAP_100TH_MM ); Size aSize = GetOutputSize(); // Massstab: 1:2 MapMode aMapMode = GetMapMode(); aMapMode.SetScaleX( Fraction( 1, 2 ) ); aMapMode.SetScaleY( Fraction( 1, 2 ) ); SetMapMode( aMapMode ); aSize = GetOutputSize(); Rectangle aRect = Rectangle( Point(), aSize ); Point aPt1 = Point( aSize.Width() / 5, (long) ( aSize.Height() / 2 ) ); Point aPt2 = Point( aSize.Width() * 4 / 5, (long) ( aSize.Height() / 2 ) ); pMeasureObj = new SdrMeasureObj( aPt1, aPt2 ); pModel = new SdrModel(); pMeasureObj->SetModel( pModel ); //-/ pMeasureObj->SetAttributes( rInAttrs, FALSE ); //-/ SdrBroadcastItemChange aItemChange(*pMeasureObj); pMeasureObj->SetItemSetAndBroadcast(rInAttrs); //-/ pMeasureObj->BroadcastItemChange(aItemChange); SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR ); Invalidate(); } /************************************************************************* |* |* Dtor SvxXMeasurePreview |* *************************************************************************/ SvxXMeasurePreview::~SvxXMeasurePreview() { delete pExtOutDev; delete pModel; } /************************************************************************* |* |* SvxXMeasurePreview: Paint() |* *************************************************************************/ void SvxXMeasurePreview::Paint( const Rectangle& rRect ) { SdrPaintInfoRec aInfoRec; pMeasureObj->Paint( *pExtOutDev, aInfoRec ); } /************************************************************************* |* |* SvxXMeasurePreview: SetAttributes() |* *************************************************************************/ void SvxXMeasurePreview::SetAttributes( const SfxItemSet& rInAttrs ) { //-/ pMeasureObj->SetAttributes( rInAttrs, FALSE ); //-/ SdrBroadcastItemChange aItemChange(*pMeasureObj); pMeasureObj->SetItemSetAndBroadcast(rInAttrs); //-/ pMeasureObj->BroadcastItemChange(aItemChange); Invalidate(); } /************************************************************************* |* |* SvxXMeasurePreview: SetAttributes() |* *************************************************************************/ void SvxXMeasurePreview::MouseButtonDown( const MouseEvent& rMEvt ) { BOOL bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift(); BOOL bZoomOut = rMEvt.IsRight() || rMEvt.IsShift(); BOOL bCtrl = rMEvt.IsMod1(); if( bZoomIn || bZoomOut ) { MapMode aMapMode = GetMapMode(); Fraction aXFrac = aMapMode.GetScaleX(); Fraction aYFrac = aMapMode.GetScaleY(); Fraction* pMultFrac; if( bZoomIn ) { if( bCtrl ) pMultFrac = new Fraction( 3, 2 ); else pMultFrac = new Fraction( 11, 10 ); } else { if( bCtrl ) pMultFrac = new Fraction( 2, 3 ); else pMultFrac = new Fraction( 10, 11 ); } aXFrac *= *pMultFrac; aYFrac *= *pMultFrac; if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 && (double)aYFrac > 0.001 && (double)aYFrac < 1000.0 ) { aMapMode.SetScaleX( aXFrac ); aMapMode.SetScaleY( aYFrac ); SetMapMode( aMapMode ); Size aOutSize( GetOutputSize() ); Point aPt( aMapMode.GetOrigin() ); long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); aPt.X() += nX; aPt.Y() += nY; aMapMode.SetOrigin( aPt ); SetMapMode( aMapMode ); Invalidate(); } delete pMultFrac; } } // ----------------------------------------------------------------------- void SvxXMeasurePreview::DataChanged( const DataChangedEvent& rDCEvt ) { Control::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) { SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR ); } } <commit_msg>INTEGRATION: CWS aw003 (1.3.202); FILE MERGED 2003/10/30 14:15:10 aw 1.3.202.4: #111111# No one is deleting the MeasureObj? This is not only an error but also a memory leak (!). Main problem is that this object is still listening to a StyleSheet of the model which was set. Thus, if You want to keep the obnject, set the modfel to 0L, if object is not needed (seems to be the case here), delete it. 2003/10/07 12:16:38 aw 1.3.202.3: #111097# 2003/07/25 16:30:38 aw 1.3.202.2: #110094# Changed Paint() to DoPaintObject() for identifying reasons 2003/06/06 12:59:07 aw 1.3.202.1: #109820# 2nd run of changes for ItemSet isolation<commit_after>/************************************************************************* * * $RCSfile: measctrl.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2003-11-24 16:35:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #pragma hdrstop #include "xoutx.hxx" #include "svdomeas.hxx" #include "svdmodel.hxx" //#include "svdrwobj.hxx" // SdrPaintInfoRec #include "measctrl.hxx" #include "dialmgr.hxx" #include "dlgutil.hxx" /************************************************************************* |* |* Ctor SvxXMeasurePreview |* *************************************************************************/ SvxXMeasurePreview::SvxXMeasurePreview ( Window* pParent, const ResId& rResId, const SfxItemSet& rInAttrs ) : Control ( pParent, rResId ), rAttrs ( rInAttrs ) { pExtOutDev = new ExtOutputDevice( this ); SetMapMode( MAP_100TH_MM ); Size aSize = GetOutputSize(); // Massstab: 1:2 MapMode aMapMode = GetMapMode(); aMapMode.SetScaleX( Fraction( 1, 2 ) ); aMapMode.SetScaleY( Fraction( 1, 2 ) ); SetMapMode( aMapMode ); aSize = GetOutputSize(); Rectangle aRect = Rectangle( Point(), aSize ); Point aPt1 = Point( aSize.Width() / 5, (long) ( aSize.Height() / 2 ) ); Point aPt2 = Point( aSize.Width() * 4 / 5, (long) ( aSize.Height() / 2 ) ); pMeasureObj = new SdrMeasureObj( aPt1, aPt2 ); pModel = new SdrModel(); pMeasureObj->SetModel( pModel ); //pMeasureObj->SetItemSetAndBroadcast(rInAttrs); pMeasureObj->SetMergedItemSetAndBroadcast(rInAttrs); SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR ); Invalidate(); } /************************************************************************* |* |* Dtor SvxXMeasurePreview |* *************************************************************************/ SvxXMeasurePreview::~SvxXMeasurePreview() { delete pExtOutDev; // #111111# // No one is deleting the MeasureObj? This is not only an error but also // a memory leak (!). Main problem is that this object is still listening to // a StyleSheet of the model which was set. Thus, if You want to keep the obnject, // set the modfel to 0L, if object is not needed (seems to be the case here), // delete it. delete pMeasureObj; delete pModel; } /************************************************************************* |* |* SvxXMeasurePreview: Paint() |* *************************************************************************/ void SvxXMeasurePreview::Paint( const Rectangle& rRect ) { SdrPaintInfoRec aInfoRec; pMeasureObj->SingleObjectPainter( *pExtOutDev, aInfoRec ); // #110094#-17 } /************************************************************************* |* |* SvxXMeasurePreview: SetAttributes() |* *************************************************************************/ void SvxXMeasurePreview::SetAttributes( const SfxItemSet& rInAttrs ) { //pMeasureObj->SetItemSetAndBroadcast(rInAttrs); pMeasureObj->SetMergedItemSetAndBroadcast(rInAttrs); Invalidate(); } /************************************************************************* |* |* SvxXMeasurePreview: SetAttributes() |* *************************************************************************/ void SvxXMeasurePreview::MouseButtonDown( const MouseEvent& rMEvt ) { BOOL bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift(); BOOL bZoomOut = rMEvt.IsRight() || rMEvt.IsShift(); BOOL bCtrl = rMEvt.IsMod1(); if( bZoomIn || bZoomOut ) { MapMode aMapMode = GetMapMode(); Fraction aXFrac = aMapMode.GetScaleX(); Fraction aYFrac = aMapMode.GetScaleY(); Fraction* pMultFrac; if( bZoomIn ) { if( bCtrl ) pMultFrac = new Fraction( 3, 2 ); else pMultFrac = new Fraction( 11, 10 ); } else { if( bCtrl ) pMultFrac = new Fraction( 2, 3 ); else pMultFrac = new Fraction( 10, 11 ); } aXFrac *= *pMultFrac; aYFrac *= *pMultFrac; if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 && (double)aYFrac > 0.001 && (double)aYFrac < 1000.0 ) { aMapMode.SetScaleX( aXFrac ); aMapMode.SetScaleY( aYFrac ); SetMapMode( aMapMode ); Size aOutSize( GetOutputSize() ); Point aPt( aMapMode.GetOrigin() ); long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); aPt.X() += nX; aPt.Y() += nY; aMapMode.SetOrigin( aPt ); SetMapMode( aMapMode ); Invalidate(); } delete pMultFrac; } } // ----------------------------------------------------------------------- void SvxXMeasurePreview::DataChanged( const DataChangedEvent& rDCEvt ) { Control::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) { SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR ); } } <|endoftext|>
<commit_before>#include <memory> #include "core/armor_up.h" #include "daemon.h" #include "dataset/dataset.h" #include "micro_http_server.h" #include "supp/helpers.h" #include "utils/query.h" #include "utils/formatter.h" using micro_http_server::Daemon; using micro_http_server::PostHandler; using micro_http_server::SimplePostServer; class SpecialPostHandler : public PostHandler{ public: SpecialPostHandler() : PostHandler(), query_cache_(""), armor_up_(), formatter_(&armor_up_.GetArsenal()) {} int ProcessKeyValue(const std::string &key, const std::string &value) override { if (key == "query") { query_cache_ = value; return MHD_NO; } // Ignore anything when the first key value pair is not for "query". return MHD_NO; } std::string GenerateResponse() override { if (query_cache_.size() == 0) { return "{ error_message: \"no query received.\" }"; } // Convert the query to wstring. std::wstring query_text; query_text.assign(query_cache_.begin(), query_cache_.end()); // Parse the query. Query query; if (!Query::Parse(query_text, &query).Success()) { return "{ error_message: \"Corrupted Query\" }"; } // ArmorUp Search. std::vector<ArmorSet> result = std::move(armor_up_.Search(query)); armor_up_.Summarize(); return formatter_.StringBatchFormat(result); } std::string query_cache_; ArmorUp armor_up_; DexJsonFormatter formatter_; }; int main(int argc, char **argv) { if (argc < 2) { Log(FATAL, L"Please call the command as: armor_up_server [dataset folder] [port]"); } int port = 8887; if (argc >= 3) { try { port = std::stoi(argv[2]); } catch (std::invalid_argument&) { Log(FATAL, L"Invalid port %s.", argv[2]); _exit(-1); } } Log(INFO, L"Loading database ..."); Data::LoadSQLite(argv[1]); Log(INFO, L"Armor up!"); Log(INFO, L"Starting server ..."); SimplePostServer<SpecialPostHandler> server(port); Log(INFO, L"Server Started."); while (true) { sleep(100); } return 0; } <commit_msg>remove one debug information<commit_after>#include <memory> #include "core/armor_up.h" #include "daemon.h" #include "dataset/dataset.h" #include "micro_http_server.h" #include "supp/helpers.h" #include "utils/query.h" #include "utils/formatter.h" using micro_http_server::Daemon; using micro_http_server::PostHandler; using micro_http_server::SimplePostServer; class SpecialPostHandler : public PostHandler{ public: SpecialPostHandler() : PostHandler(), query_cache_(""), armor_up_(), formatter_(&armor_up_.GetArsenal()) {} int ProcessKeyValue(const std::string &key, const std::string &value) override { if (key == "query") { query_cache_ = value; return MHD_NO; } // Ignore anything when the first key value pair is not for "query". return MHD_NO; } std::string GenerateResponse() override { if (query_cache_.size() == 0) { return "{ error_message: \"no query received.\" }"; } // Convert the query to wstring. std::wstring query_text; query_text.assign(query_cache_.begin(), query_cache_.end()); // Parse the query. Query query; if (!Query::Parse(query_text, &query).Success()) { return "{ error_message: \"Corrupted Query\" }"; } // ArmorUp Search. std::vector<ArmorSet> result = std::move(armor_up_.Search(query)); return formatter_.StringBatchFormat(result); } std::string query_cache_; ArmorUp armor_up_; DexJsonFormatter formatter_; }; int main(int argc, char **argv) { if (argc < 2) { Log(FATAL, L"Please call the command as: armor_up_server [dataset folder] [port]"); } int port = 8887; if (argc >= 3) { try { port = std::stoi(argv[2]); } catch (std::invalid_argument&) { Log(FATAL, L"Invalid port %s.", argv[2]); _exit(-1); } } Log(INFO, L"Loading database ..."); Data::LoadSQLite(argv[1]); Log(INFO, L"Armor up!"); Log(INFO, L"Starting server ..."); SimplePostServer<SpecialPostHandler> server(port); Log(INFO, L"Server Started."); while (true) { sleep(100); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: multipat.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-10-12 12:19:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #include "multipat.hxx" #include "dialmgr.hxx" #include "multipat.hrc" #include "dialogs.hrc" #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFolderPicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_ #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #endif #include <unotools/localfilehelper.hxx> #include <svtools/pathoptions.hxx> using namespace ::com::sun::star::lang; using namespace ::com::sun::star::ui::dialogs; using namespace ::com::sun::star::uno; // struct MultiPath_Impl ------------------------------------------------- struct MultiPath_Impl { BOOL bEmptyAllowed; BOOL bIsClassPathMode; bool bIsRadioButtonMode; MultiPath_Impl( BOOL bAllowed ) : bEmptyAllowed( bAllowed ), bIsClassPathMode( FALSE ), bIsRadioButtonMode( false ) {} }; // class SvxMultiPathDialog ---------------------------------------------- IMPL_LINK( SvxMultiPathDialog, SelectHdl_Impl, void *, EMPTYARG ) { ULONG nCount = pImpl->bIsRadioButtonMode ? aRadioLB.GetEntryCount() : aPathLB.GetEntryCount(); bool bIsSelected = pImpl->bIsRadioButtonMode ? aRadioLB.FirstSelected() != NULL : aPathLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND; BOOL bEnable = ( pImpl->bEmptyAllowed || nCount > 1 ); aDelBtn.Enable( bEnable && bIsSelected ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxMultiPathDialog, CheckHdl_Impl, svx::SvxRadioButtonListBox *, pBox ) { SvLBoxEntry* pEntry = pBox ? pBox->GetEntry( pBox->GetCurMousePoint() ) : aRadioLB.FirstSelected(); if ( pEntry ) aRadioLB.HandleEntryChecked( pEntry ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxMultiPathDialog, AddHdl_Impl, PushButton *, EMPTYARG ) { rtl::OUString aService( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ); Reference < XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); Reference < XFolderPicker > xFolderPicker( xFactory->createInstance( aService ), UNO_QUERY ); if ( xFolderPicker->execute() == ExecutableDialogResults::OK ) { INetURLObject aPath( xFolderPicker->getDirectory() ); aPath.removeFinalSlash(); String aURL = aPath.GetMainURL( INetURLObject::NO_DECODE ); String sInsPath; ::utl::LocalFileHelper::ConvertURLToSystemPath( aURL, sInsPath ); if ( pImpl->bIsRadioButtonMode ) { ULONG nPos = aRadioLB.GetEntryPos( sInsPath, 1 ); if ( (ULONG)-1 == nPos ) { String sNewEntry( '\t' ); sNewEntry += sInsPath; SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sNewEntry ); String* pData = new String( aURL ); pEntry->SetUserData( pData ); } else { String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) ); sMsg.SearchAndReplaceAscii( "%1", sInsPath ); InfoBox( this, sMsg ).Execute(); } } else { if ( LISTBOX_ENTRY_NOTFOUND != aPathLB.GetEntryPos( sInsPath ) ) { String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) ); sMsg.SearchAndReplaceAscii( "%1", sInsPath ); InfoBox( this, sMsg ).Execute(); } else { USHORT nPos = aPathLB.InsertEntry( sInsPath, LISTBOX_APPEND ); aPathLB.SetEntryData( nPos, (void*)new String( aURL ) ); } } SelectHdl_Impl( NULL ); } return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxMultiPathDialog, DelHdl_Impl, PushButton *, EMPTYARG ) { if ( pImpl->bIsRadioButtonMode ) { SvLBoxEntry* pEntry = aRadioLB.FirstSelected(); delete (String*)pEntry->GetUserData(); bool bChecked = aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED; ULONG nPos = aRadioLB.GetEntryPos( pEntry ); aRadioLB.RemoveEntry( pEntry ); ULONG nCnt = aRadioLB.GetEntryCount(); if ( nCnt ) { nCnt--; if ( nPos > nCnt ) nPos = nCnt; pEntry = aRadioLB.GetEntry( nPos ); if ( bChecked ) { aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED ); aRadioLB.HandleEntryChecked( pEntry ); } else aRadioLB.Select( pEntry ); } } else { USHORT nPos = aPathLB.GetSelectEntryPos(); aPathLB.RemoveEntry( nPos ); USHORT nCnt = aPathLB.GetEntryCount(); if ( nCnt ) { nCnt--; if ( nPos > nCnt ) nPos = nCnt; aPathLB.SelectEntryPos( nPos ); } } SelectHdl_Impl( NULL ); return 0; } // ----------------------------------------------------------------------- SvxMultiPathDialog::SvxMultiPathDialog( Window* pParent, BOOL bEmptyAllowed ) : ModalDialog( pParent, SVX_RES( RID_SVXDLG_MULTIPATH ) ), aPathFL ( this, ResId( FL_MULTIPATH) ), aPathLB ( this, ResId( LB_MULTIPATH ) ), aRadioLB ( this, ResId( LB_RADIOBUTTON ) ), aRadioFT ( this, ResId( FT_RADIOBUTTON ) ), aAddBtn ( this, ResId( BTN_ADD_MULTIPATH ) ), aDelBtn ( this, ResId( BTN_DEL_MULTIPATH ) ), aOKBtn ( this, ResId( BTN_MULTIPATH_OK ) ), aCancelBtn ( this, ResId( BTN_MULTIPATH_CANCEL ) ), aHelpButton ( this, ResId( BTN_MULTIPATH_HELP ) ), pImpl ( new MultiPath_Impl( bEmptyAllowed ) ) { static long aStaticTabs[]= { 2, 0, 12 }; aRadioLB.SvxSimpleTable::SetTabs( aStaticTabs ); String sHeader( ResId( STR_HEADER_PATHS ) ); aRadioLB.SetQuickHelpText( sHeader ); sHeader.Insert( '\t', 0 ); aRadioLB.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT ); FreeResource(); aPathLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) ); aRadioLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) ); aRadioLB.SetCheckButtonHdl( LINK( this, SvxMultiPathDialog, CheckHdl_Impl ) ); aAddBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, AddHdl_Impl ) ); aDelBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, DelHdl_Impl ) ); SelectHdl_Impl( NULL ); } // ----------------------------------------------------------------------- SvxMultiPathDialog::~SvxMultiPathDialog() { USHORT nPos = aPathLB.GetEntryCount(); while ( nPos-- ) delete (String*)aPathLB.GetEntryData(nPos); nPos = (USHORT)aRadioLB.GetEntryCount(); while ( nPos-- ) { SvLBoxEntry* pEntry = aRadioLB.GetEntry( nPos ); delete (String*)pEntry->GetUserData(); } delete pImpl; } // ----------------------------------------------------------------------- String SvxMultiPathDialog::GetPath() const { String sNewPath; sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER; if ( pImpl->bIsRadioButtonMode ) { String sWritable; for ( USHORT i = 0; i < aRadioLB.GetEntryCount(); ++i ) { SvLBoxEntry* pEntry = aRadioLB.GetEntry(i); if ( aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) sWritable = *(String*)pEntry->GetUserData(); else { if ( sNewPath.Len() > 0 ) sNewPath += cDelim; sNewPath += *(String*)pEntry->GetUserData(); } } if ( sNewPath.Len() > 0 ) sNewPath += cDelim; sNewPath += sWritable; } else { for ( USHORT i = 0; i < aPathLB.GetEntryCount(); ++i ) { if ( sNewPath.Len() > 0 ) sNewPath += cDelim; sNewPath += *(String*)aPathLB.GetEntryData(i); } } return sNewPath; } // ----------------------------------------------------------------------- void SvxMultiPathDialog::SetPath( const String& rPath ) { sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER; USHORT nPos, nCount = rPath.GetTokenCount( cDelim ); for ( USHORT i = 0; i < nCount; ++i ) { String sPath = rPath.GetToken( i, cDelim ); String sSystemPath; sal_Bool bIsSystemPath = ::utl::LocalFileHelper::ConvertURLToSystemPath( sPath, sSystemPath ); if ( pImpl->bIsRadioButtonMode ) { String sEntry( '\t' ); sEntry += bIsSystemPath ? sSystemPath : sPath; SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sEntry ); String* pURL = new String( sPath ); pEntry->SetUserData( pURL ); } else { if ( bIsSystemPath ) nPos = aPathLB.InsertEntry( sSystemPath, LISTBOX_APPEND ); else nPos = aPathLB.InsertEntry( sPath, LISTBOX_APPEND ); aPathLB.SetEntryData( nPos, (void*)new String( sPath ) ); } } if ( pImpl->bIsRadioButtonMode && nCount > 0 ) { SvLBoxEntry* pEntry = aRadioLB.GetEntry( nCount - 1 ); if ( pEntry ) { aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED ); aRadioLB.HandleEntryChecked( pEntry ); } } SelectHdl_Impl( NULL ); } // ----------------------------------------------------------------------- void SvxMultiPathDialog::SetClassPathMode() { pImpl->bIsClassPathMode = TRUE; SetText( SVX_RES( RID_SVXSTR_ARCHIVE_TITLE )); aPathFL.SetText( SVX_RES( RID_SVXSTR_ARCHIVE_HEADLINE ) ); } // ----------------------------------------------------------------------- sal_Bool SvxMultiPathDialog::IsClassPathMode() const { return pImpl->bIsClassPathMode; } // ----------------------------------------------------------------------- void SvxMultiPathDialog::EnableRadioButtonMode() { pImpl->bIsRadioButtonMode = true; aPathFL.Hide(); aPathLB.Hide(); aRadioLB.ShowTable(); aRadioFT.Show(); Point aNewPos = aAddBtn.GetPosPixel(); long nDelta = aNewPos.Y() - aRadioLB.GetPosPixel().Y(); aNewPos.Y() -= nDelta; aAddBtn.SetPosPixel( aNewPos ); aNewPos = aDelBtn.GetPosPixel(); aNewPos.Y() -= nDelta; aDelBtn.SetPosPixel( aNewPos ); } <commit_msg>INTEGRATION: CWS residcleanup (1.9.230); FILE MERGED 2007/02/20 19:38:33 pl 1.9.230.1: #i74635# get rid of global ResMgr<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: multipat.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-04-26 07:36:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #include "multipat.hxx" #include "dialmgr.hxx" #include "multipat.hrc" #include "dialogs.hrc" #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFolderPicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_ #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #endif #include <unotools/localfilehelper.hxx> #include <svtools/pathoptions.hxx> using namespace ::com::sun::star::lang; using namespace ::com::sun::star::ui::dialogs; using namespace ::com::sun::star::uno; // struct MultiPath_Impl ------------------------------------------------- struct MultiPath_Impl { BOOL bEmptyAllowed; BOOL bIsClassPathMode; bool bIsRadioButtonMode; MultiPath_Impl( BOOL bAllowed ) : bEmptyAllowed( bAllowed ), bIsClassPathMode( FALSE ), bIsRadioButtonMode( false ) {} }; // class SvxMultiPathDialog ---------------------------------------------- IMPL_LINK( SvxMultiPathDialog, SelectHdl_Impl, void *, EMPTYARG ) { ULONG nCount = pImpl->bIsRadioButtonMode ? aRadioLB.GetEntryCount() : aPathLB.GetEntryCount(); bool bIsSelected = pImpl->bIsRadioButtonMode ? aRadioLB.FirstSelected() != NULL : aPathLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND; BOOL bEnable = ( pImpl->bEmptyAllowed || nCount > 1 ); aDelBtn.Enable( bEnable && bIsSelected ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxMultiPathDialog, CheckHdl_Impl, svx::SvxRadioButtonListBox *, pBox ) { SvLBoxEntry* pEntry = pBox ? pBox->GetEntry( pBox->GetCurMousePoint() ) : aRadioLB.FirstSelected(); if ( pEntry ) aRadioLB.HandleEntryChecked( pEntry ); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxMultiPathDialog, AddHdl_Impl, PushButton *, EMPTYARG ) { rtl::OUString aService( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ); Reference < XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); Reference < XFolderPicker > xFolderPicker( xFactory->createInstance( aService ), UNO_QUERY ); if ( xFolderPicker->execute() == ExecutableDialogResults::OK ) { INetURLObject aPath( xFolderPicker->getDirectory() ); aPath.removeFinalSlash(); String aURL = aPath.GetMainURL( INetURLObject::NO_DECODE ); String sInsPath; ::utl::LocalFileHelper::ConvertURLToSystemPath( aURL, sInsPath ); if ( pImpl->bIsRadioButtonMode ) { ULONG nPos = aRadioLB.GetEntryPos( sInsPath, 1 ); if ( (ULONG)-1 == nPos ) { String sNewEntry( '\t' ); sNewEntry += sInsPath; SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sNewEntry ); String* pData = new String( aURL ); pEntry->SetUserData( pData ); } else { String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) ); sMsg.SearchAndReplaceAscii( "%1", sInsPath ); InfoBox( this, sMsg ).Execute(); } } else { if ( LISTBOX_ENTRY_NOTFOUND != aPathLB.GetEntryPos( sInsPath ) ) { String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) ); sMsg.SearchAndReplaceAscii( "%1", sInsPath ); InfoBox( this, sMsg ).Execute(); } else { USHORT nPos = aPathLB.InsertEntry( sInsPath, LISTBOX_APPEND ); aPathLB.SetEntryData( nPos, (void*)new String( aURL ) ); } } SelectHdl_Impl( NULL ); } return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxMultiPathDialog, DelHdl_Impl, PushButton *, EMPTYARG ) { if ( pImpl->bIsRadioButtonMode ) { SvLBoxEntry* pEntry = aRadioLB.FirstSelected(); delete (String*)pEntry->GetUserData(); bool bChecked = aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED; ULONG nPos = aRadioLB.GetEntryPos( pEntry ); aRadioLB.RemoveEntry( pEntry ); ULONG nCnt = aRadioLB.GetEntryCount(); if ( nCnt ) { nCnt--; if ( nPos > nCnt ) nPos = nCnt; pEntry = aRadioLB.GetEntry( nPos ); if ( bChecked ) { aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED ); aRadioLB.HandleEntryChecked( pEntry ); } else aRadioLB.Select( pEntry ); } } else { USHORT nPos = aPathLB.GetSelectEntryPos(); aPathLB.RemoveEntry( nPos ); USHORT nCnt = aPathLB.GetEntryCount(); if ( nCnt ) { nCnt--; if ( nPos > nCnt ) nPos = nCnt; aPathLB.SelectEntryPos( nPos ); } } SelectHdl_Impl( NULL ); return 0; } // ----------------------------------------------------------------------- SvxMultiPathDialog::SvxMultiPathDialog( Window* pParent, BOOL bEmptyAllowed ) : ModalDialog( pParent, SVX_RES( RID_SVXDLG_MULTIPATH ) ), aPathFL ( this, SVX_RES( FL_MULTIPATH) ), aPathLB ( this, SVX_RES( LB_MULTIPATH ) ), aRadioLB ( this, SVX_RES( LB_RADIOBUTTON ) ), aRadioFT ( this, SVX_RES( FT_RADIOBUTTON ) ), aAddBtn ( this, SVX_RES( BTN_ADD_MULTIPATH ) ), aDelBtn ( this, SVX_RES( BTN_DEL_MULTIPATH ) ), aOKBtn ( this, SVX_RES( BTN_MULTIPATH_OK ) ), aCancelBtn ( this, SVX_RES( BTN_MULTIPATH_CANCEL ) ), aHelpButton ( this, SVX_RES( BTN_MULTIPATH_HELP ) ), pImpl ( new MultiPath_Impl( bEmptyAllowed ) ) { static long aStaticTabs[]= { 2, 0, 12 }; aRadioLB.SvxSimpleTable::SetTabs( aStaticTabs ); String sHeader( SVX_RES( STR_HEADER_PATHS ) ); aRadioLB.SetQuickHelpText( sHeader ); sHeader.Insert( '\t', 0 ); aRadioLB.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT ); FreeResource(); aPathLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) ); aRadioLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) ); aRadioLB.SetCheckButtonHdl( LINK( this, SvxMultiPathDialog, CheckHdl_Impl ) ); aAddBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, AddHdl_Impl ) ); aDelBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, DelHdl_Impl ) ); SelectHdl_Impl( NULL ); } // ----------------------------------------------------------------------- SvxMultiPathDialog::~SvxMultiPathDialog() { USHORT nPos = aPathLB.GetEntryCount(); while ( nPos-- ) delete (String*)aPathLB.GetEntryData(nPos); nPos = (USHORT)aRadioLB.GetEntryCount(); while ( nPos-- ) { SvLBoxEntry* pEntry = aRadioLB.GetEntry( nPos ); delete (String*)pEntry->GetUserData(); } delete pImpl; } // ----------------------------------------------------------------------- String SvxMultiPathDialog::GetPath() const { String sNewPath; sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER; if ( pImpl->bIsRadioButtonMode ) { String sWritable; for ( USHORT i = 0; i < aRadioLB.GetEntryCount(); ++i ) { SvLBoxEntry* pEntry = aRadioLB.GetEntry(i); if ( aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) sWritable = *(String*)pEntry->GetUserData(); else { if ( sNewPath.Len() > 0 ) sNewPath += cDelim; sNewPath += *(String*)pEntry->GetUserData(); } } if ( sNewPath.Len() > 0 ) sNewPath += cDelim; sNewPath += sWritable; } else { for ( USHORT i = 0; i < aPathLB.GetEntryCount(); ++i ) { if ( sNewPath.Len() > 0 ) sNewPath += cDelim; sNewPath += *(String*)aPathLB.GetEntryData(i); } } return sNewPath; } // ----------------------------------------------------------------------- void SvxMultiPathDialog::SetPath( const String& rPath ) { sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER; USHORT nPos, nCount = rPath.GetTokenCount( cDelim ); for ( USHORT i = 0; i < nCount; ++i ) { String sPath = rPath.GetToken( i, cDelim ); String sSystemPath; sal_Bool bIsSystemPath = ::utl::LocalFileHelper::ConvertURLToSystemPath( sPath, sSystemPath ); if ( pImpl->bIsRadioButtonMode ) { String sEntry( '\t' ); sEntry += bIsSystemPath ? sSystemPath : sPath; SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sEntry ); String* pURL = new String( sPath ); pEntry->SetUserData( pURL ); } else { if ( bIsSystemPath ) nPos = aPathLB.InsertEntry( sSystemPath, LISTBOX_APPEND ); else nPos = aPathLB.InsertEntry( sPath, LISTBOX_APPEND ); aPathLB.SetEntryData( nPos, (void*)new String( sPath ) ); } } if ( pImpl->bIsRadioButtonMode && nCount > 0 ) { SvLBoxEntry* pEntry = aRadioLB.GetEntry( nCount - 1 ); if ( pEntry ) { aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED ); aRadioLB.HandleEntryChecked( pEntry ); } } SelectHdl_Impl( NULL ); } // ----------------------------------------------------------------------- void SvxMultiPathDialog::SetClassPathMode() { pImpl->bIsClassPathMode = TRUE; SetText( SVX_RES( RID_SVXSTR_ARCHIVE_TITLE )); aPathFL.SetText( SVX_RES( RID_SVXSTR_ARCHIVE_HEADLINE ) ); } // ----------------------------------------------------------------------- sal_Bool SvxMultiPathDialog::IsClassPathMode() const { return pImpl->bIsClassPathMode; } // ----------------------------------------------------------------------- void SvxMultiPathDialog::EnableRadioButtonMode() { pImpl->bIsRadioButtonMode = true; aPathFL.Hide(); aPathLB.Hide(); aRadioLB.ShowTable(); aRadioFT.Show(); Point aNewPos = aAddBtn.GetPosPixel(); long nDelta = aNewPos.Y() - aRadioLB.GetPosPixel().Y(); aNewPos.Y() -= nDelta; aAddBtn.SetPosPixel( aNewPos ); aNewPos = aDelBtn.GetPosPixel(); aNewPos.Y() -= nDelta; aDelBtn.SetPosPixel( aNewPos ); } <|endoftext|>
<commit_before>/******************************************************************************/ /** @file @author Scott Fazackerley @brief Wraps the Arduino Serial object and provides a simple printf implementation for C. @copyright Copyright 2016 The University of British Columbia, IonDB Project Contributors (see AUTHORS.md) @par 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 @par 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 "serial_c_iface.h" int serial_printf_c( const char *format, ... ) { va_list args, countpass; va_start(args, format); va_copy(countpass, args); int bufsize = vsnprintf(NULL, 0, format, countpass); char buf[bufsize]; vsnprintf(buf, bufsize, format, args); va_end(countpass); va_end(args); return serial_print(buf); } int serial_print( const char *buffer ) { int num; num = Serial.print(buffer); #if DEBUG Serial.flush(); #endif return num; } void serial_init( int baud_rate ) { Serial.begin(baud_rate); } void serial_close( ) { Serial.end(); } <commit_msg>Attempt to fix vsnprintf<commit_after>/******************************************************************************/ /** @file @author Scott Fazackerley @brief Wraps the Arduino Serial object and provides a simple printf implementation for C. @copyright Copyright 2016 The University of British Columbia, IonDB Project Contributors (see AUTHORS.md) @par 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 @par 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 "serial_c_iface.h" int serial_printf_c( const char *format, ... ) { va_list args; va_start(args, format); int bufsize = vsnprintf(NULL, 0, format, args); char buf[bufsize]; va_end(args); va_start(args); vsnprintf(buf, bufsize, format, args); va_end(args); return serial_print(buf); } int serial_print( const char *buffer ) { int num; num = Serial.print(buffer); #if DEBUG Serial.flush(); #endif return num; } void serial_init( int baud_rate ) { Serial.begin(baud_rate); } void serial_close( ) { Serial.end(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: optinet2.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-01-28 15:41:21 $ * * 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 _SVX_OPTINET_HXX #define _SVX_OPTINET_HXX #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_GROUP_HXX #include <vcl/group.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _SVTABBX_HXX //autogen #include <svtools/svtabbx.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SVX_SRCHNCFG_HXX #include "srchcfg.hxx" #endif #ifdef _SVX_OPTINET2_CXX #ifndef _HEADBAR_HXX //autogen #include <svtools/headbar.hxx> #endif #else class HeaderBar; #endif #ifndef _SVX_READONLYIMAGE_HXX #include <readonlyimage.hxx> #endif class SfxFilter; class SvtInetOptions; #ifndef SV_NODIALOG #define PROXY_CONTROLS 23 #define CACHE_CONTROLS 20 #define INET_SEARCH 19 #if defined(OS2) || defined(MAC) #define TYPE_CONTROLS 20 #else #define TYPE_CONTROLS 18 #endif namespace lang = ::com::sun::star::lang; namespace uno = ::com::sun::star::uno; // class SvxNoSpaceEdit -------------------------------------------------- class SvxNoSpaceEdit : public Edit { private: BOOL bOnlyNumeric; public: SvxNoSpaceEdit(Window* pParent, ResId rResId, BOOL bNum = FALSE ) : Edit( pParent, rResId ), bOnlyNumeric( bNum ) {} virtual void KeyInput( const KeyEvent& rKEvent ); virtual void Modify(); }; typedef SfxFilter* SfxFilterPtr; SV_DECL_PTRARR( SfxFilterPtrArr, SfxFilterPtr, 0, 4 ) // class SvxProxyTabPage ------------------------------------------------- class SvxProxyTabPage : public SfxTabPage { private: FixedLine aOptionGB; FixedText aProxyModeFT; ListBox aProxyModeLB; FixedText aHttpProxyFT; SvxNoSpaceEdit aHttpProxyED; FixedText aHttpPortFT; SvxNoSpaceEdit aHttpPortED; FixedText aFtpProxyFT; SvxNoSpaceEdit aFtpProxyED; FixedText aFtpPortFT; SvxNoSpaceEdit aFtpPortED; FixedText aNoProxyForFT; Edit aNoProxyForED; FixedText aNoProxyDescFT; String sFromBrowser; const rtl::OUString aProxyModePN; const rtl::OUString aHttpProxyPN; const rtl::OUString aHttpPortPN; const rtl::OUString aFtpProxyPN; const rtl::OUString aFtpPortPN; const rtl::OUString aNoProxyDescPN; uno::Reference< uno::XInterface > m_xConfigurationUpdateAccess; #ifdef _SVX_OPTINET2_CXX void EnableControls_Impl(BOOL bEnable); void ReadConfigData_Impl(); void ReadConfigDefaults_Impl(); void RestoreConfigDefaults_Impl(); DECL_LINK( ProxyHdl_Impl, ListBox * ); DECL_LINK( LoseFocusHdl_Impl, Edit * ); #endif SvxProxyTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxProxyTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; // class SvxSearchTabPage ------------------------------------------------ class SvxSearchConfig; class SvxSearchTabPage : public SfxTabPage { private: FixedLine aSearchGB; ListBox aSearchLB; FixedText aSearchNameFT; SvxNoSpaceEdit aSearchNameED; FixedText aSearchFT; RadioButton aAndRB; RadioButton aOrRB; RadioButton aExactRB; FixedText aURLFT; SvxNoSpaceEdit aURLED; FixedText aPostFixFT; SvxNoSpaceEdit aPostFixED; FixedText aSeparatorFT; SvxNoSpaceEdit aSeparatorED; FixedText aCaseFT; ListBox aCaseED; PushButton aNewPB; PushButton aAddPB; PushButton aChangePB; PushButton aDeletePB; String sLastSelectedEntry; String sModifyMsg; SvxSearchConfig aSearchConfig; SvxSearchEngineData aCurrentSrchData; #ifdef _SVX_OPTINET2_CXX void FillSearchBox_Impl(); String GetSearchString_Impl(); DECL_LINK( NewSearchHdl_Impl, PushButton * ); DECL_LINK( AddSearchHdl_Impl, PushButton * ); DECL_LINK( ChangeSearchHdl_Impl, PushButton * ); DECL_LINK( DeleteSearchHdl_Impl, PushButton * ); DECL_LINK( SearchEntryHdl_Impl, ListBox * ); DECL_LINK( SearchModifyHdl_Impl, SvxNoSpaceEdit * ); DECL_LINK( SearchPartHdl_Impl, RadioButton * ); #endif virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); BOOL ConfirmLeave( const String& rStringSelection ); //add by BerryJia for fixing Bug102610 Time:2002-8-29 11:00 (China Standard Time GMT+08:00) SvxSearchTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxSearchTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; // #98647# class SvxScriptExecListBox ------------------------------------ class SvxScriptExecListBox : public ListBox { // for adding tooltips to ListBox public: SvxScriptExecListBox( Window* pParent, WinBits nStyle = WB_BORDER ) :ListBox(pParent, nStyle) {} SvxScriptExecListBox( Window* pParent, const ResId& rResId ) :ListBox(pParent, rResId) {} protected: virtual void RequestHelp( const HelpEvent& rHEvt ); }; // class SvxSecurityTabPage --------------------------------------------- class SvtJavaOptions; class SvtSecurityOptions; class SvxSecurityTabPage : public SfxTabPage { public: enum RedliningMode { RL_NONE, RL_WRITER, RL_CALC }; private: FixedLine maSecOptionsFL; FixedInfo maSecOptionsFI; ReadOnlyImage maSaveOrSendDocsFI; CheckBox maSaveOrSendDocsCB; ReadOnlyImage maSignDocsFI; CheckBox maSignDocsCB; ReadOnlyImage maPrintDocsFI; CheckBox maPrintDocsCB; ReadOnlyImage maCreatePdfFI; CheckBox maCreatePdfCB; ReadOnlyImage maRemovePersInfoFI; CheckBox maRemovePersInfoCB; ReadOnlyImage maRecommPasswdFI; CheckBox maRecommPasswdCB; FixedLine maMacroSecFL; FixedInfo maMacroSecFI; PushButton maMacroSecPB; FixedLine maFilesharingFL; CheckBox maRecommReadOnlyCB; CheckBox maRecordChangesCB; PushButton maProtectRecordsPB; SvtSecurityOptions* mpSecOptions; RedliningMode meRedlingMode; String msProtectRecordsStr; String msUnprotectRecordsStr; DECL_LINK( AdvancedPBHdl, void* ); DECL_LINK( MacroSecPBHdl, void* ); DECL_LINK( RecordChangesCBHdl, void* ); DECL_LINK( ProtectRecordsPBHdl, void* ); void CheckRecordChangesState( void ); void InitControls(); SvxSecurityTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxSecurityTabPage(); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; //added by jmeng begin class MozPluginTabPage : public SfxTabPage { FixedLine aMSWordGB; CheckBox aWBasicCodeCB; BOOL isInstalled(void); BOOL installPlugin(void); BOOL uninstallPlugin(void); MozPluginTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~MozPluginTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; //added by jmeng end #endif /* -----------------------------20.06.01 16:32-------------------------------- ---------------------------------------------------------------------------*/ #ifdef WNT #else #define HELPER_PAGE_COMPLETE #endif struct SvxEMailTabPage_Impl; class SvxEMailTabPage : public SfxTabPage { FixedLine aMailFL; ReadOnlyImage aMailerURLFI; FixedText aMailerURLFT; Edit aMailerURLED; PushButton aMailerURLPB; String m_sDefaultFilterName; SvxEMailTabPage_Impl* pImpl; DECL_LINK( FileDialogHdl_Impl, PushButton* ) ; public: SvxEMailTabPage( Window* pParent, const SfxItemSet& rSet ); ~SvxEMailTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; #endif // #ifndef _SVX_OPTINET_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.9.408); FILE MERGED 2005/09/05 14:21:34 rt 1.9.408.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optinet2.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:45:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_OPTINET_HXX #define _SVX_OPTINET_HXX #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_GROUP_HXX #include <vcl/group.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _SVTABBX_HXX //autogen #include <svtools/svtabbx.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SVX_SRCHNCFG_HXX #include "srchcfg.hxx" #endif #ifdef _SVX_OPTINET2_CXX #ifndef _HEADBAR_HXX //autogen #include <svtools/headbar.hxx> #endif #else class HeaderBar; #endif #ifndef _SVX_READONLYIMAGE_HXX #include <readonlyimage.hxx> #endif class SfxFilter; class SvtInetOptions; #ifndef SV_NODIALOG #define PROXY_CONTROLS 23 #define CACHE_CONTROLS 20 #define INET_SEARCH 19 #if defined(OS2) || defined(MAC) #define TYPE_CONTROLS 20 #else #define TYPE_CONTROLS 18 #endif namespace lang = ::com::sun::star::lang; namespace uno = ::com::sun::star::uno; // class SvxNoSpaceEdit -------------------------------------------------- class SvxNoSpaceEdit : public Edit { private: BOOL bOnlyNumeric; public: SvxNoSpaceEdit(Window* pParent, ResId rResId, BOOL bNum = FALSE ) : Edit( pParent, rResId ), bOnlyNumeric( bNum ) {} virtual void KeyInput( const KeyEvent& rKEvent ); virtual void Modify(); }; typedef SfxFilter* SfxFilterPtr; SV_DECL_PTRARR( SfxFilterPtrArr, SfxFilterPtr, 0, 4 ) // class SvxProxyTabPage ------------------------------------------------- class SvxProxyTabPage : public SfxTabPage { private: FixedLine aOptionGB; FixedText aProxyModeFT; ListBox aProxyModeLB; FixedText aHttpProxyFT; SvxNoSpaceEdit aHttpProxyED; FixedText aHttpPortFT; SvxNoSpaceEdit aHttpPortED; FixedText aFtpProxyFT; SvxNoSpaceEdit aFtpProxyED; FixedText aFtpPortFT; SvxNoSpaceEdit aFtpPortED; FixedText aNoProxyForFT; Edit aNoProxyForED; FixedText aNoProxyDescFT; String sFromBrowser; const rtl::OUString aProxyModePN; const rtl::OUString aHttpProxyPN; const rtl::OUString aHttpPortPN; const rtl::OUString aFtpProxyPN; const rtl::OUString aFtpPortPN; const rtl::OUString aNoProxyDescPN; uno::Reference< uno::XInterface > m_xConfigurationUpdateAccess; #ifdef _SVX_OPTINET2_CXX void EnableControls_Impl(BOOL bEnable); void ReadConfigData_Impl(); void ReadConfigDefaults_Impl(); void RestoreConfigDefaults_Impl(); DECL_LINK( ProxyHdl_Impl, ListBox * ); DECL_LINK( LoseFocusHdl_Impl, Edit * ); #endif SvxProxyTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxProxyTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; // class SvxSearchTabPage ------------------------------------------------ class SvxSearchConfig; class SvxSearchTabPage : public SfxTabPage { private: FixedLine aSearchGB; ListBox aSearchLB; FixedText aSearchNameFT; SvxNoSpaceEdit aSearchNameED; FixedText aSearchFT; RadioButton aAndRB; RadioButton aOrRB; RadioButton aExactRB; FixedText aURLFT; SvxNoSpaceEdit aURLED; FixedText aPostFixFT; SvxNoSpaceEdit aPostFixED; FixedText aSeparatorFT; SvxNoSpaceEdit aSeparatorED; FixedText aCaseFT; ListBox aCaseED; PushButton aNewPB; PushButton aAddPB; PushButton aChangePB; PushButton aDeletePB; String sLastSelectedEntry; String sModifyMsg; SvxSearchConfig aSearchConfig; SvxSearchEngineData aCurrentSrchData; #ifdef _SVX_OPTINET2_CXX void FillSearchBox_Impl(); String GetSearchString_Impl(); DECL_LINK( NewSearchHdl_Impl, PushButton * ); DECL_LINK( AddSearchHdl_Impl, PushButton * ); DECL_LINK( ChangeSearchHdl_Impl, PushButton * ); DECL_LINK( DeleteSearchHdl_Impl, PushButton * ); DECL_LINK( SearchEntryHdl_Impl, ListBox * ); DECL_LINK( SearchModifyHdl_Impl, SvxNoSpaceEdit * ); DECL_LINK( SearchPartHdl_Impl, RadioButton * ); #endif virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); BOOL ConfirmLeave( const String& rStringSelection ); //add by BerryJia for fixing Bug102610 Time:2002-8-29 11:00 (China Standard Time GMT+08:00) SvxSearchTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxSearchTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; // #98647# class SvxScriptExecListBox ------------------------------------ class SvxScriptExecListBox : public ListBox { // for adding tooltips to ListBox public: SvxScriptExecListBox( Window* pParent, WinBits nStyle = WB_BORDER ) :ListBox(pParent, nStyle) {} SvxScriptExecListBox( Window* pParent, const ResId& rResId ) :ListBox(pParent, rResId) {} protected: virtual void RequestHelp( const HelpEvent& rHEvt ); }; // class SvxSecurityTabPage --------------------------------------------- class SvtJavaOptions; class SvtSecurityOptions; class SvxSecurityTabPage : public SfxTabPage { public: enum RedliningMode { RL_NONE, RL_WRITER, RL_CALC }; private: FixedLine maSecOptionsFL; FixedInfo maSecOptionsFI; ReadOnlyImage maSaveOrSendDocsFI; CheckBox maSaveOrSendDocsCB; ReadOnlyImage maSignDocsFI; CheckBox maSignDocsCB; ReadOnlyImage maPrintDocsFI; CheckBox maPrintDocsCB; ReadOnlyImage maCreatePdfFI; CheckBox maCreatePdfCB; ReadOnlyImage maRemovePersInfoFI; CheckBox maRemovePersInfoCB; ReadOnlyImage maRecommPasswdFI; CheckBox maRecommPasswdCB; FixedLine maMacroSecFL; FixedInfo maMacroSecFI; PushButton maMacroSecPB; FixedLine maFilesharingFL; CheckBox maRecommReadOnlyCB; CheckBox maRecordChangesCB; PushButton maProtectRecordsPB; SvtSecurityOptions* mpSecOptions; RedliningMode meRedlingMode; String msProtectRecordsStr; String msUnprotectRecordsStr; DECL_LINK( AdvancedPBHdl, void* ); DECL_LINK( MacroSecPBHdl, void* ); DECL_LINK( RecordChangesCBHdl, void* ); DECL_LINK( ProtectRecordsPBHdl, void* ); void CheckRecordChangesState( void ); void InitControls(); SvxSecurityTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxSecurityTabPage(); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; //added by jmeng begin class MozPluginTabPage : public SfxTabPage { FixedLine aMSWordGB; CheckBox aWBasicCodeCB; BOOL isInstalled(void); BOOL installPlugin(void); BOOL uninstallPlugin(void); MozPluginTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~MozPluginTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; //added by jmeng end #endif /* -----------------------------20.06.01 16:32-------------------------------- ---------------------------------------------------------------------------*/ #ifdef WNT #else #define HELPER_PAGE_COMPLETE #endif struct SvxEMailTabPage_Impl; class SvxEMailTabPage : public SfxTabPage { FixedLine aMailFL; ReadOnlyImage aMailerURLFI; FixedText aMailerURLFT; Edit aMailerURLED; PushButton aMailerURLPB; String m_sDefaultFilterName; SvxEMailTabPage_Impl* pImpl; DECL_LINK( FileDialogHdl_Impl, PushButton* ) ; public: SvxEMailTabPage( Window* pParent, const SfxItemSet& rSet ); ~SvxEMailTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; #endif // #ifndef _SVX_OPTINET_HXX <|endoftext|>
<commit_before>//===- DomPrinter.cpp - DOT printer for the dominance trees ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines '-dot-dom' and '-dot-postdom' analysis passes, which emit // a dom.<fnname>.dot or postdom.<fnname>.dot file for each function in the // program, with a graph of the dominance/postdominance tree of that // function. // // There are also passes available to directly call dotty ('-view-dom' or // '-view-postdom'). By appending '-only' like '-dot-dom-only' only the // names of the bbs are printed, but the content is hidden. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DomPrinter.h" #include "llvm/Analysis/DOTGraphTraitsPass.h" #include "llvm/Analysis/PostDominators.h" using namespace llvm; namespace llvm { template<> struct DOTGraphTraits<DomTreeNode*> : public DefaultDOTGraphTraits { DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} std::string getNodeLabel(DomTreeNode *Node, DomTreeNode *Graph) { BasicBlock *BB = Node->getBlock(); if (!BB) return "Post dominance root node"; if (isSimple()) return DOTGraphTraits<const Function*> ::getSimpleNodeLabel(BB, BB->getParent()); else return DOTGraphTraits<const Function*> ::getCompleteNodeLabel(BB, BB->getParent()); } }; template<> struct DOTGraphTraits<DominatorTree*> : public DOTGraphTraits<DomTreeNode*> { DOTGraphTraits (bool isSimple=false) : DOTGraphTraits<DomTreeNode*>(isSimple) {} static std::string getGraphName(DominatorTree *DT) { return "Dominator tree"; } std::string getNodeLabel(DomTreeNode *Node, DominatorTree *G) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode()); } }; template<> struct DOTGraphTraits<PostDominatorTree*> : public DOTGraphTraits<DomTreeNode*> { DOTGraphTraits (bool isSimple=false) : DOTGraphTraits<DomTreeNode*>(isSimple) {} static std::string getGraphName(PostDominatorTree *DT) { return "Post dominator tree"; } std::string getNodeLabel(DomTreeNode *Node, PostDominatorTree *G ) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode()); } }; } namespace { struct DomViewer : public DOTGraphTraitsViewer<DominatorTree, false> { static char ID; DomViewer() : DOTGraphTraitsViewer<DominatorTree, false>("dom", ID){ initializeDomViewerPass(*PassRegistry::getPassRegistry()); } }; struct DomOnlyViewer : public DOTGraphTraitsViewer<DominatorTree, true> { static char ID; DomOnlyViewer() : DOTGraphTraitsViewer<DominatorTree, true>("domonly", ID){ initializeDomOnlyViewerPass(*PassRegistry::getPassRegistry()); } }; struct PostDomViewer : public DOTGraphTraitsViewer<PostDominatorTree, false> { static char ID; PostDomViewer() : DOTGraphTraitsViewer<PostDominatorTree, false>("postdom", ID){ initializePostDomViewerPass(*PassRegistry::getPassRegistry()); } }; struct PostDomOnlyViewer : public DOTGraphTraitsViewer<PostDominatorTree, true> { static char ID; PostDomOnlyViewer() : DOTGraphTraitsViewer<PostDominatorTree, true>("postdomonly", ID){ initializePostDomOnlyViewerPass(*PassRegistry::getPassRegistry()); } }; } // end anonymous namespace char DomViewer::ID = 0; INITIALIZE_PASS(DomViewer, "view-dom", "View dominance tree of function", false, false) char DomOnlyViewer::ID = 0; INITIALIZE_PASS(DomOnlyViewer, "view-dom-only", "View dominance tree of function (with no function bodies)", false, false) char PostDomViewer::ID = 0; INITIALIZE_PASS(PostDomViewer, "view-postdom", "View postdominance tree of function", false, false) char PostDomOnlyViewer::ID = 0; INITIALIZE_PASS(PostDomOnlyViewer, "view-postdom-only", "View postdominance tree of function " "(with no function bodies)", false, false) namespace { struct DomPrinter : public DOTGraphTraitsPrinter<DominatorTree, false> { static char ID; DomPrinter() : DOTGraphTraitsPrinter<DominatorTree, false>("dom", ID) { initializeDomPrinterPass(*PassRegistry::getPassRegistry()); } }; struct DomOnlyPrinter : public DOTGraphTraitsPrinter<DominatorTree, true> { static char ID; DomOnlyPrinter() : DOTGraphTraitsPrinter<DominatorTree, true>("domonly", ID) { initializeDomOnlyPrinterPass(*PassRegistry::getPassRegistry()); } }; struct PostDomPrinter : public DOTGraphTraitsPrinter<PostDominatorTree, false> { static char ID; PostDomPrinter() : DOTGraphTraitsPrinter<PostDominatorTree, false>("postdom", ID) { initializePostDomPrinterPass(*PassRegistry::getPassRegistry()); } }; struct PostDomOnlyPrinter : public DOTGraphTraitsPrinter<PostDominatorTree, true> { static char ID; PostDomOnlyPrinter() : DOTGraphTraitsPrinter<PostDominatorTree, true>("postdomonly", ID) { initializePostDomOnlyPrinterPass(*PassRegistry::getPassRegistry()); } }; } // end anonymous namespace char DomPrinter::ID = 0; INITIALIZE_PASS(DomPrinter, "dot-dom", "Print dominance tree of function to 'dot' file", false, false) char DomOnlyPrinter::ID = 0; INITIALIZE_PASS(DomOnlyPrinter, "dot-dom-only", "Print dominance tree of function to 'dot' file " "(with no function bodies)", false, false) char PostDomPrinter::ID = 0; INITIALIZE_PASS(PostDomPrinter, "dot-postdom", "Print postdominance tree of function to 'dot' file", false, false) char PostDomOnlyPrinter::ID = 0; INITIALIZE_PASS(PostDomOnlyPrinter, "dot-postdom-only", "Print postdominance tree of function to 'dot' file " "(with no function bodies)", false, false) // Create methods available outside of this file, to use them // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by // the link time optimization. FunctionPass *llvm::createDomPrinterPass() { return new DomPrinter(); } FunctionPass *llvm::createDomOnlyPrinterPass() { return new DomOnlyPrinter(); } FunctionPass *llvm::createDomViewerPass() { return new DomViewer(); } FunctionPass *llvm::createDomOnlyViewerPass() { return new DomOnlyViewer(); } FunctionPass *llvm::createPostDomPrinterPass() { return new PostDomPrinter(); } FunctionPass *llvm::createPostDomOnlyPrinterPass() { return new PostDomOnlyPrinter(); } FunctionPass *llvm::createPostDomViewerPass() { return new PostDomViewer(); } FunctionPass *llvm::createPostDomOnlyViewerPass() { return new PostDomOnlyViewer(); } <commit_msg>test commit. add a blank line.<commit_after>//===- DomPrinter.cpp - DOT printer for the dominance trees ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines '-dot-dom' and '-dot-postdom' analysis passes, which emit // a dom.<fnname>.dot or postdom.<fnname>.dot file for each function in the // program, with a graph of the dominance/postdominance tree of that // function. // // There are also passes available to directly call dotty ('-view-dom' or // '-view-postdom'). By appending '-only' like '-dot-dom-only' only the // names of the bbs are printed, but the content is hidden. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DomPrinter.h" #include "llvm/Analysis/DOTGraphTraitsPass.h" #include "llvm/Analysis/PostDominators.h" using namespace llvm; namespace llvm { template<> struct DOTGraphTraits<DomTreeNode*> : public DefaultDOTGraphTraits { DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} std::string getNodeLabel(DomTreeNode *Node, DomTreeNode *Graph) { BasicBlock *BB = Node->getBlock(); if (!BB) return "Post dominance root node"; if (isSimple()) return DOTGraphTraits<const Function*> ::getSimpleNodeLabel(BB, BB->getParent()); else return DOTGraphTraits<const Function*> ::getCompleteNodeLabel(BB, BB->getParent()); } }; template<> struct DOTGraphTraits<DominatorTree*> : public DOTGraphTraits<DomTreeNode*> { DOTGraphTraits (bool isSimple=false) : DOTGraphTraits<DomTreeNode*>(isSimple) {} static std::string getGraphName(DominatorTree *DT) { return "Dominator tree"; } std::string getNodeLabel(DomTreeNode *Node, DominatorTree *G) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode()); } }; template<> struct DOTGraphTraits<PostDominatorTree*> : public DOTGraphTraits<DomTreeNode*> { DOTGraphTraits (bool isSimple=false) : DOTGraphTraits<DomTreeNode*>(isSimple) {} static std::string getGraphName(PostDominatorTree *DT) { return "Post dominator tree"; } std::string getNodeLabel(DomTreeNode *Node, PostDominatorTree *G ) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode()); } }; } namespace { struct DomViewer : public DOTGraphTraitsViewer<DominatorTree, false> { static char ID; DomViewer() : DOTGraphTraitsViewer<DominatorTree, false>("dom", ID){ initializeDomViewerPass(*PassRegistry::getPassRegistry()); } }; struct DomOnlyViewer : public DOTGraphTraitsViewer<DominatorTree, true> { static char ID; DomOnlyViewer() : DOTGraphTraitsViewer<DominatorTree, true>("domonly", ID){ initializeDomOnlyViewerPass(*PassRegistry::getPassRegistry()); } }; struct PostDomViewer : public DOTGraphTraitsViewer<PostDominatorTree, false> { static char ID; PostDomViewer() : DOTGraphTraitsViewer<PostDominatorTree, false>("postdom", ID){ initializePostDomViewerPass(*PassRegistry::getPassRegistry()); } }; struct PostDomOnlyViewer : public DOTGraphTraitsViewer<PostDominatorTree, true> { static char ID; PostDomOnlyViewer() : DOTGraphTraitsViewer<PostDominatorTree, true>("postdomonly", ID){ initializePostDomOnlyViewerPass(*PassRegistry::getPassRegistry()); } }; } // end anonymous namespace char DomViewer::ID = 0; INITIALIZE_PASS(DomViewer, "view-dom", "View dominance tree of function", false, false) char DomOnlyViewer::ID = 0; INITIALIZE_PASS(DomOnlyViewer, "view-dom-only", "View dominance tree of function (with no function bodies)", false, false) char PostDomViewer::ID = 0; INITIALIZE_PASS(PostDomViewer, "view-postdom", "View postdominance tree of function", false, false) char PostDomOnlyViewer::ID = 0; INITIALIZE_PASS(PostDomOnlyViewer, "view-postdom-only", "View postdominance tree of function " "(with no function bodies)", false, false) namespace { struct DomPrinter : public DOTGraphTraitsPrinter<DominatorTree, false> { static char ID; DomPrinter() : DOTGraphTraitsPrinter<DominatorTree, false>("dom", ID) { initializeDomPrinterPass(*PassRegistry::getPassRegistry()); } }; struct DomOnlyPrinter : public DOTGraphTraitsPrinter<DominatorTree, true> { static char ID; DomOnlyPrinter() : DOTGraphTraitsPrinter<DominatorTree, true>("domonly", ID) { initializeDomOnlyPrinterPass(*PassRegistry::getPassRegistry()); } }; struct PostDomPrinter : public DOTGraphTraitsPrinter<PostDominatorTree, false> { static char ID; PostDomPrinter() : DOTGraphTraitsPrinter<PostDominatorTree, false>("postdom", ID) { initializePostDomPrinterPass(*PassRegistry::getPassRegistry()); } }; struct PostDomOnlyPrinter : public DOTGraphTraitsPrinter<PostDominatorTree, true> { static char ID; PostDomOnlyPrinter() : DOTGraphTraitsPrinter<PostDominatorTree, true>("postdomonly", ID) { initializePostDomOnlyPrinterPass(*PassRegistry::getPassRegistry()); } }; } // end anonymous namespace char DomPrinter::ID = 0; INITIALIZE_PASS(DomPrinter, "dot-dom", "Print dominance tree of function to 'dot' file", false, false) char DomOnlyPrinter::ID = 0; INITIALIZE_PASS(DomOnlyPrinter, "dot-dom-only", "Print dominance tree of function to 'dot' file " "(with no function bodies)", false, false) char PostDomPrinter::ID = 0; INITIALIZE_PASS(PostDomPrinter, "dot-postdom", "Print postdominance tree of function to 'dot' file", false, false) char PostDomOnlyPrinter::ID = 0; INITIALIZE_PASS(PostDomOnlyPrinter, "dot-postdom-only", "Print postdominance tree of function to 'dot' file " "(with no function bodies)", false, false) // Create methods available outside of this file, to use them // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by // the link time optimization. FunctionPass *llvm::createDomPrinterPass() { return new DomPrinter(); } FunctionPass *llvm::createDomOnlyPrinterPass() { return new DomOnlyPrinter(); } FunctionPass *llvm::createDomViewerPass() { return new DomViewer(); } FunctionPass *llvm::createDomOnlyViewerPass() { return new DomOnlyViewer(); } FunctionPass *llvm::createPostDomPrinterPass() { return new PostDomPrinter(); } FunctionPass *llvm::createPostDomOnlyPrinterPass() { return new PostDomOnlyPrinter(); } FunctionPass *llvm::createPostDomViewerPass() { return new PostDomViewer(); } FunctionPass *llvm::createPostDomOnlyViewerPass() { return new PostDomOnlyViewer(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pagectrl.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hjs $ $Date: 2000-11-06 19:19:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #pragma hdrstop #define ITEMID_BOX 0 #ifndef _SV_BITMAP_HXX #include <vcl/bitmap.hxx> #endif #include "pageitem.hxx" #include "pagectrl.hxx" #include "boxitem.hxx" #include <string> #include <algorithm> // struct PageWindow_Impl ------------------------------------------------ struct PageWindow_Impl { SvxBoxItem* pBorder; Bitmap aBitmap; FASTBOOL bBitmap; PageWindow_Impl() : pBorder(0), bBitmap(FALSE) {} }; // STATIC DATA ----------------------------------------------------------- #define CELL_WIDTH 1600L #define CELL_HEIGHT 800L // class SvxPageWindow --------------------------------------------------- SvxPageWindow::SvxPageWindow( Window* pParent, const ResId& rId ) : Window( pParent, rId ), nTop ( 0 ), nBottom ( 0 ), nLeft ( 0 ), nRight ( 0 ), aColor ( COL_WHITE ), nHdLeft ( 0 ), nHdRight ( 0 ), nHdDist ( 0 ), nHdHeight ( 0 ), aHdColor ( COL_WHITE ), pHdBorder ( 0 ), nFtLeft ( 0 ), nFtRight ( 0 ), nFtDist ( 0 ), nFtHeight ( 0 ), aFtColor ( COL_WHITE ), pFtBorder ( 0 ), bFooter ( FALSE ), bHeader ( FALSE ), bTable ( FALSE ), bHorz ( FALSE ), bVert ( FALSE ), eUsage ( SVX_PAGE_ALL ) { pImpl = new PageWindow_Impl; // defaultmaessing in Twips rechnen SetMapMode( MapMode( MAP_TWIP ) ); aWinSize = GetOutputSizePixel(); aWinSize.Height() -= 4; aWinSize.Width() -= 4; aWinSize = PixelToLogic( aWinSize ); aSolidLineColor = Color( COL_BLACK ); aDotLineColor = Color( COL_BLACK ); aGrayLineColor = Color( COL_GRAY ); aNormalFillColor = GetFillColor(); aDisabledFillColor = Color( COL_GRAY ); aGrayFillColor = Color( COL_LIGHTGRAY ); } // ----------------------------------------------------------------------- SvxPageWindow::~SvxPageWindow() { delete pImpl; delete pHdBorder; delete pFtBorder; } // ----------------------------------------------------------------------- void __EXPORT SvxPageWindow::Paint( const Rectangle& rRect ) { Fraction aXScale( aWinSize.Width(), std::max( aSize.Width() * 2 + aSize.Width() / 8, 1 ) ); Fraction aYScale( aWinSize.Height(), std::max( aSize.Height(), 1L ) ); MapMode aMapMode( GetMapMode() ); if ( aYScale < aXScale ) { aMapMode.SetScaleX( aYScale ); aMapMode.SetScaleY( aYScale ); } else { aMapMode.SetScaleX( aXScale ); aMapMode.SetScaleY( aXScale ); } SetMapMode( aMapMode ); Size aSz( PixelToLogic( GetSizePixel() ) ); long nYPos = ( aSz.Height() - aSize.Height() ) / 2; if ( eUsage == SVX_PAGE_ALL ) { // alle Seiten gleich -> eine Seite malen if ( aSize.Width() > aSize.Height() ) { // Querformat in gleicher Gr"osse zeichnen Fraction aX = aMapMode.GetScaleX(); Fraction aY = aMapMode.GetScaleY(); Fraction a2( 1.5 ); aX *= a2; aY *= a2; aMapMode.SetScaleX( aX ); aMapMode.SetScaleY( aY ); SetMapMode( aMapMode ); aSz = PixelToLogic( GetSizePixel() ); nYPos = ( aSz.Height() - aSize.Height() ) / 2; long nXPos = ( aSz.Width() - aSize.Width() ) / 2; DrawPage( Point( nXPos, nYPos ), TRUE, TRUE ); } else // Hochformat DrawPage( Point( ( aSz.Width() - aSize.Width() ) / 2, nYPos ), TRUE, TRUE ); } else { // Linke und rechte Seite unterschiedlich -> ggf. zwei Seiten malen DrawPage( Point( 0, nYPos ), FALSE, (BOOL)( eUsage & SVX_PAGE_LEFT ) ); DrawPage( Point( aSize.Width() + aSize.Width() / 8, nYPos ), TRUE, (BOOL)( eUsage & SVX_PAGE_RIGHT ) ); } } // ----------------------------------------------------------------------- void SvxPageWindow::DrawPage( const Point& rOrg, const BOOL bSecond, const BOOL bEnabled ) { // Schatten Size aTempSize = aSize; if ( aTempSize.Height() > aTempSize.Width() ) // Beim Hochformat die H"ohe etwas verkleinern, damit der Schatten passt. aTempSize.Height() -= PixelToLogic( Size( 0, 2 ) ).Height(); Point aShadowPt( rOrg ); aShadowPt += PixelToLogic( Point( 2, 2 ) ); SetLineColor( Color( COL_GRAY ) ); SetFillColor( Color( COL_GRAY ) ); DrawRect( Rectangle( aShadowPt, aTempSize ) ); // Seite SetLineColor( Color( COL_BLACK ) ); if ( !bEnabled ) { SetFillColor( Color( COL_GRAY ) ); DrawRect( Rectangle( rOrg, aTempSize ) ); return; } SetFillColor( Color( COL_WHITE ) ); DrawRect( Rectangle( rOrg, aTempSize ) ); // Border Top Bottom Left Right Point aBegin( rOrg ); Point aEnd( rOrg ); long nL = nLeft; long nR = nRight; if ( eUsage == SVX_PAGE_MIRROR && !bSecond ) { // f"ur gespiegelt drehen nL = nRight; nR = nLeft; } Rectangle aRect; aRect.Left() = rOrg.X() + nL; aRect.Right() = rOrg.X() + aTempSize.Width() - nR; aRect.Top() = rOrg.Y() + nTop; aRect.Bottom()= rOrg.Y() + aTempSize.Height() - nBottom; Rectangle aHdRect( aRect ); Rectangle aFtRect( aRect ); if ( bHeader ) { // ggf. Header anzeigen aHdRect.Left() += nHdLeft; aHdRect.Right() -= nHdRight; aHdRect.Bottom() = aRect.Top() + nHdHeight; aRect.Top() += nHdHeight + nHdDist; SetFillColor( aHdColor ); DrawRect( aHdRect ); } if ( bFooter ) { // ggf. Footer anzeigen aFtRect.Left() += nFtLeft; aFtRect.Right() -= nFtRight; aFtRect.Top() = aRect.Bottom() - nFtHeight; aRect.Bottom() -= nFtHeight + nFtDist; SetFillColor( aFtColor ); DrawRect( aFtRect ); } // Body malen SetFillColor( aColor ); if ( pImpl->bBitmap ) { DrawRect( aRect ); Point aBmpPnt = aRect.TopLeft(); Size aBmpSiz = aRect.GetSize(); long nDeltaX = aBmpSiz.Width() / 15; long nDeltaY = aBmpSiz.Height() / 15; aBmpPnt.X() += nDeltaX; aBmpPnt.Y() += nDeltaY; aBmpSiz.Width() -= nDeltaX * 2; aBmpSiz.Height() -= nDeltaY * 2; DrawBitmap( aBmpPnt, aBmpSiz, pImpl->aBitmap ); } else DrawRect( aRect ); if ( bTable ) { // Tabelle malen, ggf. zentrieren SetLineColor( Color(COL_LIGHTGRAY) ); long nW = aRect.GetWidth(), nH = aRect.GetHeight(); long nTW = CELL_WIDTH * 3, nTH = CELL_HEIGHT * 3; long nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left(); long nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top(); Rectangle aCellRect( Point( nLeft, nTop ), Size( CELL_WIDTH, CELL_HEIGHT ) ); for ( USHORT i = 0; i < 3; ++i ) { aCellRect.Left() = nLeft; aCellRect.Right() = nLeft + CELL_WIDTH; if ( i > 0 ) aCellRect.Move( 0, CELL_HEIGHT ); for ( USHORT j = 0; j < 3; ++j ) { if ( j > 0 ) aCellRect.Move( CELL_WIDTH, 0 ); DrawRect( aCellRect ); } } } } // ----------------------------------------------------------------------- void SvxPageWindow::SetBorder( const SvxBoxItem& rNew ) { delete pImpl->pBorder; pImpl->pBorder = new SvxBoxItem( rNew ); } // ----------------------------------------------------------------------- void SvxPageWindow::SetBitmap( Bitmap* pBmp ) { if ( pBmp ) { pImpl->aBitmap = *pBmp; pImpl->bBitmap = TRUE; } else pImpl->bBitmap = FALSE; } // ----------------------------------------------------------------------- void SvxPageWindow::SetHdBorder( const SvxBoxItem& rNew ) { delete pHdBorder; pHdBorder = new SvxBoxItem( rNew ); } // ----------------------------------------------------------------------- void SvxPageWindow::SetFtBorder( const SvxBoxItem& rNew ) { delete pFtBorder; pFtBorder = new SvxBoxItem( rNew ); } <commit_msg>#65293#: use long with std::max()<commit_after>/************************************************************************* * * $RCSfile: pagectrl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2000-11-09 14:29:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #pragma hdrstop #define ITEMID_BOX 0 #ifndef _SV_BITMAP_HXX #include <vcl/bitmap.hxx> #endif #include "pageitem.hxx" #include "pagectrl.hxx" #include "boxitem.hxx" #include <algorithm> // struct PageWindow_Impl ------------------------------------------------ struct PageWindow_Impl { SvxBoxItem* pBorder; Bitmap aBitmap; FASTBOOL bBitmap; PageWindow_Impl() : pBorder(0), bBitmap(FALSE) {} }; // STATIC DATA ----------------------------------------------------------- #define CELL_WIDTH 1600L #define CELL_HEIGHT 800L // class SvxPageWindow --------------------------------------------------- SvxPageWindow::SvxPageWindow( Window* pParent, const ResId& rId ) : Window( pParent, rId ), nTop ( 0 ), nBottom ( 0 ), nLeft ( 0 ), nRight ( 0 ), aColor ( COL_WHITE ), nHdLeft ( 0 ), nHdRight ( 0 ), nHdDist ( 0 ), nHdHeight ( 0 ), aHdColor ( COL_WHITE ), pHdBorder ( 0 ), nFtLeft ( 0 ), nFtRight ( 0 ), nFtDist ( 0 ), nFtHeight ( 0 ), aFtColor ( COL_WHITE ), pFtBorder ( 0 ), bFooter ( FALSE ), bHeader ( FALSE ), bTable ( FALSE ), bHorz ( FALSE ), bVert ( FALSE ), eUsage ( SVX_PAGE_ALL ) { pImpl = new PageWindow_Impl; // defaultmaessing in Twips rechnen SetMapMode( MapMode( MAP_TWIP ) ); aWinSize = GetOutputSizePixel(); aWinSize.Height() -= 4; aWinSize.Width() -= 4; aWinSize = PixelToLogic( aWinSize ); aSolidLineColor = Color( COL_BLACK ); aDotLineColor = Color( COL_BLACK ); aGrayLineColor = Color( COL_GRAY ); aNormalFillColor = GetFillColor(); aDisabledFillColor = Color( COL_GRAY ); aGrayFillColor = Color( COL_LIGHTGRAY ); } // ----------------------------------------------------------------------- SvxPageWindow::~SvxPageWindow() { delete pImpl; delete pHdBorder; delete pFtBorder; } // ----------------------------------------------------------------------- void __EXPORT SvxPageWindow::Paint( const Rectangle& rRect ) { Fraction aXScale( aWinSize.Width(), std::max( aSize.Width() * 2 + aSize.Width() / 8, 1L ) ); Fraction aYScale( aWinSize.Height(), std::max( aSize.Height(), 1L ) ); MapMode aMapMode( GetMapMode() ); if ( aYScale < aXScale ) { aMapMode.SetScaleX( aYScale ); aMapMode.SetScaleY( aYScale ); } else { aMapMode.SetScaleX( aXScale ); aMapMode.SetScaleY( aXScale ); } SetMapMode( aMapMode ); Size aSz( PixelToLogic( GetSizePixel() ) ); long nYPos = ( aSz.Height() - aSize.Height() ) / 2; if ( eUsage == SVX_PAGE_ALL ) { // alle Seiten gleich -> eine Seite malen if ( aSize.Width() > aSize.Height() ) { // Querformat in gleicher Gr"osse zeichnen Fraction aX = aMapMode.GetScaleX(); Fraction aY = aMapMode.GetScaleY(); Fraction a2( 1.5 ); aX *= a2; aY *= a2; aMapMode.SetScaleX( aX ); aMapMode.SetScaleY( aY ); SetMapMode( aMapMode ); aSz = PixelToLogic( GetSizePixel() ); nYPos = ( aSz.Height() - aSize.Height() ) / 2; long nXPos = ( aSz.Width() - aSize.Width() ) / 2; DrawPage( Point( nXPos, nYPos ), TRUE, TRUE ); } else // Hochformat DrawPage( Point( ( aSz.Width() - aSize.Width() ) / 2, nYPos ), TRUE, TRUE ); } else { // Linke und rechte Seite unterschiedlich -> ggf. zwei Seiten malen DrawPage( Point( 0, nYPos ), FALSE, (BOOL)( eUsage & SVX_PAGE_LEFT ) ); DrawPage( Point( aSize.Width() + aSize.Width() / 8, nYPos ), TRUE, (BOOL)( eUsage & SVX_PAGE_RIGHT ) ); } } // ----------------------------------------------------------------------- void SvxPageWindow::DrawPage( const Point& rOrg, const BOOL bSecond, const BOOL bEnabled ) { // Schatten Size aTempSize = aSize; if ( aTempSize.Height() > aTempSize.Width() ) // Beim Hochformat die H"ohe etwas verkleinern, damit der Schatten passt. aTempSize.Height() -= PixelToLogic( Size( 0, 2 ) ).Height(); Point aShadowPt( rOrg ); aShadowPt += PixelToLogic( Point( 2, 2 ) ); SetLineColor( Color( COL_GRAY ) ); SetFillColor( Color( COL_GRAY ) ); DrawRect( Rectangle( aShadowPt, aTempSize ) ); // Seite SetLineColor( Color( COL_BLACK ) ); if ( !bEnabled ) { SetFillColor( Color( COL_GRAY ) ); DrawRect( Rectangle( rOrg, aTempSize ) ); return; } SetFillColor( Color( COL_WHITE ) ); DrawRect( Rectangle( rOrg, aTempSize ) ); // Border Top Bottom Left Right Point aBegin( rOrg ); Point aEnd( rOrg ); long nL = nLeft; long nR = nRight; if ( eUsage == SVX_PAGE_MIRROR && !bSecond ) { // f"ur gespiegelt drehen nL = nRight; nR = nLeft; } Rectangle aRect; aRect.Left() = rOrg.X() + nL; aRect.Right() = rOrg.X() + aTempSize.Width() - nR; aRect.Top() = rOrg.Y() + nTop; aRect.Bottom()= rOrg.Y() + aTempSize.Height() - nBottom; Rectangle aHdRect( aRect ); Rectangle aFtRect( aRect ); if ( bHeader ) { // ggf. Header anzeigen aHdRect.Left() += nHdLeft; aHdRect.Right() -= nHdRight; aHdRect.Bottom() = aRect.Top() + nHdHeight; aRect.Top() += nHdHeight + nHdDist; SetFillColor( aHdColor ); DrawRect( aHdRect ); } if ( bFooter ) { // ggf. Footer anzeigen aFtRect.Left() += nFtLeft; aFtRect.Right() -= nFtRight; aFtRect.Top() = aRect.Bottom() - nFtHeight; aRect.Bottom() -= nFtHeight + nFtDist; SetFillColor( aFtColor ); DrawRect( aFtRect ); } // Body malen SetFillColor( aColor ); if ( pImpl->bBitmap ) { DrawRect( aRect ); Point aBmpPnt = aRect.TopLeft(); Size aBmpSiz = aRect.GetSize(); long nDeltaX = aBmpSiz.Width() / 15; long nDeltaY = aBmpSiz.Height() / 15; aBmpPnt.X() += nDeltaX; aBmpPnt.Y() += nDeltaY; aBmpSiz.Width() -= nDeltaX * 2; aBmpSiz.Height() -= nDeltaY * 2; DrawBitmap( aBmpPnt, aBmpSiz, pImpl->aBitmap ); } else DrawRect( aRect ); if ( bTable ) { // Tabelle malen, ggf. zentrieren SetLineColor( Color(COL_LIGHTGRAY) ); long nW = aRect.GetWidth(), nH = aRect.GetHeight(); long nTW = CELL_WIDTH * 3, nTH = CELL_HEIGHT * 3; long nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left(); long nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top(); Rectangle aCellRect( Point( nLeft, nTop ), Size( CELL_WIDTH, CELL_HEIGHT ) ); for ( USHORT i = 0; i < 3; ++i ) { aCellRect.Left() = nLeft; aCellRect.Right() = nLeft + CELL_WIDTH; if ( i > 0 ) aCellRect.Move( 0, CELL_HEIGHT ); for ( USHORT j = 0; j < 3; ++j ) { if ( j > 0 ) aCellRect.Move( CELL_WIDTH, 0 ); DrawRect( aCellRect ); } } } } // ----------------------------------------------------------------------- void SvxPageWindow::SetBorder( const SvxBoxItem& rNew ) { delete pImpl->pBorder; pImpl->pBorder = new SvxBoxItem( rNew ); } // ----------------------------------------------------------------------- void SvxPageWindow::SetBitmap( Bitmap* pBmp ) { if ( pBmp ) { pImpl->aBitmap = *pBmp; pImpl->bBitmap = TRUE; } else pImpl->bBitmap = FALSE; } // ----------------------------------------------------------------------- void SvxPageWindow::SetHdBorder( const SvxBoxItem& rNew ) { delete pHdBorder; pHdBorder = new SvxBoxItem( rNew ); } // ----------------------------------------------------------------------- void SvxPageWindow::SetFtBorder( const SvxBoxItem& rNew ) { delete pFtBorder; pFtBorder = new SvxBoxItem( rNew ); } <|endoftext|>
<commit_before>#include <iostream> #include <string> void run_part_one() { } void run_part_two() { } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day16 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } } <commit_msg>added runtime code for day 16 part one<commit_after>#include <iostream> #include <string> #include "Aunt.hpp" void run_part_one() { std::string line; int aunt_pos = 1; Aunt target_aunt("Sue 1: children: 3, cats: 7, samoyeds: 2, pomeranians: 3, akitas: 0, vizslas: 0, goldfish: 5, trees: 3, cars: 2, perfumes: 1"); while(std::getline(std::cin,line)) { if (Aunt(line) == target_aunt) { break; } aunt_pos++; } std::cout << aunt_pos << std::endl; } void run_part_two() { } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day16 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: srchcfg.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 23:55:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _SVX_SRCHNCFG_HXX #include <srchcfg.hxx> #endif #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED #include <unotools/configpathes.hxx> #endif //----------------------------------------------------------------------------- using namespace utl; using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; #define C2U(cChar) OUString::createFromAscii(cChar) //----------------------------------------------------------------------------- typedef SvxSearchEngineData* SvxSearchEngineDataPtr; SV_DECL_PTRARR_DEL(SvxSearchEngineArr, SvxSearchEngineDataPtr, 2, 2); SV_IMPL_PTRARR(SvxSearchEngineArr, SvxSearchEngineDataPtr); //----------------------------------------------------------------------------- struct SvxSearchConfig_Impl { SvxSearchEngineArr aEngineArr; }; /* -----------------------------19.03.01 14:00-------------------------------- ---------------------------------------------------------------------------*/ sal_Bool SvxSearchEngineData::operator==(const SvxSearchEngineData& rData) { return sEngineName == rData.sEngineName && sAndPrefix == rData.sAndPrefix && sAndSuffix == rData.sAndSuffix && sAndSeparator == rData.sAndSeparator && nAndCaseMatch == rData.nAndCaseMatch && sOrPrefix == rData.sOrPrefix && sOrSuffix == rData.sOrSuffix && sOrSeparator == rData.sOrSeparator && nOrCaseMatch == rData.nOrCaseMatch && sExactPrefix == rData.sExactPrefix && sExactSuffix == rData.sExactSuffix && sExactSeparator == rData.sExactSeparator && nExactCaseMatch == rData.nExactCaseMatch; } /* -----------------------------16.01.01 15:36-------------------------------- ---------------------------------------------------------------------------*/ const Sequence<OUString>& lcl_GetSearchPropertyNames_Impl() { static Sequence<OUString> aNames; if(!aNames.getLength()) { aNames.realloc(12); OUString* pNames = aNames.getArray(); pNames[0] = C2U("And/ooInetPrefix"); pNames[1] = C2U("And/ooInetSuffix"); pNames[2] = C2U("And/ooInetSeparator"); pNames[3] = C2U("And/ooInetCaseMatch"); pNames[4] = C2U("Or/ooInetPrefix"); pNames[5] = C2U("Or/ooInetSuffix"); pNames[6] = C2U("Or/ooInetSeparator"); pNames[7] = C2U("Or/ooInetCaseMatch"); pNames[8] = C2U("Exact/ooInetPrefix"); pNames[9] = C2U("Exact/ooInetSuffix"); pNames[10] = C2U("Exact/ooInetSeparator"); pNames[11] = C2U("Exact/ooInetCaseMatch"); } return aNames; } // --------------------------------------------------------------------------- SvxSearchConfig::SvxSearchConfig(sal_Bool bEnableNotify) : utl::ConfigItem(C2U("Inet/SearchEngines"), CONFIG_MODE_DELAYED_UPDATE), pImpl(new SvxSearchConfig_Impl) { if(bEnableNotify) { //request notifications from the node Sequence<OUString> aEnable(1); EnableNotification(aEnable); } Load(); } /* -----------------------------16.01.01 15:36-------------------------------- ---------------------------------------------------------------------------*/ SvxSearchConfig::~SvxSearchConfig() { delete pImpl; } /* -----------------------------17.01.01 09:57-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::Load() { pImpl->aEngineArr.DeleteAndDestroy(0, pImpl->aEngineArr.Count()); Sequence<OUString> aNodeNames = GetNodeNames(OUString()); const OUString* pNodeNames = aNodeNames.getConstArray(); for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength(); nNode++) { SvxSearchEngineDataPtr pNew = new SvxSearchEngineData; pNew->sEngineName = pNodeNames[nNode]; const Sequence<OUString>& rPropNames = lcl_GetSearchPropertyNames_Impl(); const OUString* pPropNames = rPropNames.getConstArray(); Sequence<OUString> aPropertyNames(rPropNames.getLength()); OUString* pPropertyNames = aPropertyNames.getArray(); const OUString sSlash(C2U("/")); sal_Int32 nProp; for(nProp = 0; nProp < rPropNames.getLength(); nProp++) { pPropertyNames[nProp] = wrapConfigurationElementName(pNodeNames[nNode]); pPropertyNames[nProp] += sSlash; pPropertyNames[nProp] += pPropNames[nProp]; } Sequence<Any> aValues = GetProperties(aPropertyNames); const Any* pValues = aValues.getConstArray(); for(nProp = 0; nProp < rPropNames.getLength(); nProp++) { switch(nProp) { case 0 : pValues[nProp] >>= pNew->sAndPrefix; break; case 1 : pValues[nProp] >>= pNew->sAndSuffix; break; case 2 : pValues[nProp] >>= pNew->sAndSeparator; break; case 3 : pValues[nProp] >>= pNew->nAndCaseMatch; break; case 4 : pValues[nProp] >>= pNew->sOrPrefix; break; case 5 : pValues[nProp] >>= pNew->sOrSuffix; break; case 6 : pValues[nProp] >>= pNew->sOrSeparator; break; case 7 : pValues[nProp] >>= pNew->nOrCaseMatch; break; case 8 : pValues[nProp] >>= pNew->sExactPrefix; break; case 9 : pValues[nProp] >>= pNew->sExactSuffix; break; case 10: pValues[nProp] >>= pNew->sExactSeparator; break; case 11: pValues[nProp] >>= pNew->nExactCaseMatch; break; } } pImpl->aEngineArr.Insert(pNew, pImpl->aEngineArr.Count()); } } /* -----------------------------17.01.01 09:57-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::Notify( const Sequence<OUString>& rPropertyNames) { Load(); } /* -----------------------------16.01.01 15:36-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::Commit() { OUString sNode; if(!pImpl->aEngineArr.Count()) ClearNodeSet(sNode); else { Sequence<PropertyValue> aSetValues(12 * pImpl->aEngineArr.Count()); PropertyValue* pSetValues = aSetValues.getArray(); sal_Int32 nSetValue = 0; const Sequence<OUString>& rPropNames = lcl_GetSearchPropertyNames_Impl(); const OUString* pPropNames = rPropNames.getConstArray(); const OUString sSlash(C2U("/")); for(sal_uInt16 i = 0; i < pImpl->aEngineArr.Count(); i++) { SvxSearchEngineDataPtr pSave = pImpl->aEngineArr[i]; for(sal_Int16 nProp = 0; nProp < rPropNames.getLength(); nProp++) { OUString sTmpName = sSlash; sTmpName += wrapConfigurationElementName(pSave->sEngineName); sTmpName += sSlash; sTmpName += pPropNames[nProp]; pSetValues[nProp].Name = sTmpName; switch(nProp) { case 0 : pSetValues[nProp].Value <<= pSave->sAndPrefix; break; case 1 : pSetValues[nProp].Value <<= pSave->sAndSuffix; break; case 2 : pSetValues[nProp].Value <<= pSave->sAndSeparator; break; case 3 : pSetValues[nProp].Value <<= pSave->nAndCaseMatch; break; case 4 : pSetValues[nProp].Value <<= pSave->sOrPrefix; break; case 5 : pSetValues[nProp].Value <<= pSave->sOrSuffix; break; case 6 : pSetValues[nProp].Value <<= pSave->sOrSeparator; break; case 7 : pSetValues[nProp].Value <<= pSave->nOrCaseMatch; break; case 8 : pSetValues[nProp].Value <<= pSave->sExactPrefix; break; case 9 : pSetValues[nProp].Value <<= pSave->sExactSuffix; break; case 10: pSetValues[nProp].Value <<= pSave->sExactSeparator; break; case 11: pSetValues[nProp].Value <<= pSave->nExactCaseMatch; break; } } pSetValues+= 12; } ReplaceSetProperties(sNode, aSetValues); } } /* -----------------------------19.03.01 10:02-------------------------------- ---------------------------------------------------------------------------*/ sal_uInt16 SvxSearchConfig::Count() { return pImpl->aEngineArr.Count(); } /* -----------------------------19.03.01 10:02-------------------------------- ---------------------------------------------------------------------------*/ const SvxSearchEngineData& SvxSearchConfig::GetData(sal_uInt16 nPos) { DBG_ASSERT(nPos < pImpl->aEngineArr.Count(), "wrong array index") return *pImpl->aEngineArr[nPos]; } /* -----------------------------19.03.01 10:38-------------------------------- ---------------------------------------------------------------------------*/ const SvxSearchEngineData* SvxSearchConfig::GetData(const rtl::OUString& rEngineName) { for(sal_uInt16 nPos = 0; nPos < pImpl->aEngineArr.Count(); nPos++) { if(pImpl->aEngineArr[nPos]->sEngineName == rEngineName) return pImpl->aEngineArr[nPos]; } return 0; } /* -----------------------------19.03.01 10:02-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::SetData(const SvxSearchEngineData& rData) { for(sal_uInt16 nPos = 0; nPos < pImpl->aEngineArr.Count(); nPos++) { if(pImpl->aEngineArr[nPos]->sEngineName == rData.sEngineName) { if((*pImpl->aEngineArr[nPos]) == rData) return; pImpl->aEngineArr.DeleteAndDestroy(nPos, 1); break; } } SvxSearchEngineDataPtr pInsert = new SvxSearchEngineData(rData); pImpl->aEngineArr.Insert(pInsert, pImpl->aEngineArr.Count()); SetModified(); } /* -----------------------------19.03.01 10:38-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::RemoveData(const rtl::OUString& rEngineName) { for(sal_uInt16 nPos = 0; nPos < pImpl->aEngineArr.Count(); nPos++) { if(pImpl->aEngineArr[nPos]->sEngineName == rEngineName) { pImpl->aEngineArr.DeleteAndDestroy(nPos, 1); SetModified(); return ; } } } <commit_msg>INTEGRATION: CWS warnings01 (1.7.222); FILE MERGED 2006/04/20 14:49:59 cl 1.7.222.1: warning free code changes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: srchcfg.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-19 16:22:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_SRCHNCFG_HXX #include <srchcfg.hxx> #endif #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED #include <unotools/configpathes.hxx> #endif //----------------------------------------------------------------------------- using namespace utl; using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; #define C2U(cChar) OUString::createFromAscii(cChar) //----------------------------------------------------------------------------- typedef SvxSearchEngineData* SvxSearchEngineDataPtr; SV_DECL_PTRARR_DEL(SvxSearchEngineArr, SvxSearchEngineDataPtr, 2, 2); SV_IMPL_PTRARR(SvxSearchEngineArr, SvxSearchEngineDataPtr); //----------------------------------------------------------------------------- struct SvxSearchConfig_Impl { SvxSearchEngineArr aEngineArr; }; /* -----------------------------19.03.01 14:00-------------------------------- ---------------------------------------------------------------------------*/ sal_Bool SvxSearchEngineData::operator==(const SvxSearchEngineData& rData) { return sEngineName == rData.sEngineName && sAndPrefix == rData.sAndPrefix && sAndSuffix == rData.sAndSuffix && sAndSeparator == rData.sAndSeparator && nAndCaseMatch == rData.nAndCaseMatch && sOrPrefix == rData.sOrPrefix && sOrSuffix == rData.sOrSuffix && sOrSeparator == rData.sOrSeparator && nOrCaseMatch == rData.nOrCaseMatch && sExactPrefix == rData.sExactPrefix && sExactSuffix == rData.sExactSuffix && sExactSeparator == rData.sExactSeparator && nExactCaseMatch == rData.nExactCaseMatch; } /* -----------------------------16.01.01 15:36-------------------------------- ---------------------------------------------------------------------------*/ const Sequence<OUString>& lcl_GetSearchPropertyNames_Impl() { static Sequence<OUString> aNames; if(!aNames.getLength()) { aNames.realloc(12); OUString* pNames = aNames.getArray(); pNames[0] = C2U("And/ooInetPrefix"); pNames[1] = C2U("And/ooInetSuffix"); pNames[2] = C2U("And/ooInetSeparator"); pNames[3] = C2U("And/ooInetCaseMatch"); pNames[4] = C2U("Or/ooInetPrefix"); pNames[5] = C2U("Or/ooInetSuffix"); pNames[6] = C2U("Or/ooInetSeparator"); pNames[7] = C2U("Or/ooInetCaseMatch"); pNames[8] = C2U("Exact/ooInetPrefix"); pNames[9] = C2U("Exact/ooInetSuffix"); pNames[10] = C2U("Exact/ooInetSeparator"); pNames[11] = C2U("Exact/ooInetCaseMatch"); } return aNames; } // --------------------------------------------------------------------------- SvxSearchConfig::SvxSearchConfig(sal_Bool bEnableNotify) : utl::ConfigItem(C2U("Inet/SearchEngines"), CONFIG_MODE_DELAYED_UPDATE), pImpl(new SvxSearchConfig_Impl) { if(bEnableNotify) { //request notifications from the node Sequence<OUString> aEnable(1); EnableNotification(aEnable); } Load(); } /* -----------------------------16.01.01 15:36-------------------------------- ---------------------------------------------------------------------------*/ SvxSearchConfig::~SvxSearchConfig() { delete pImpl; } /* -----------------------------17.01.01 09:57-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::Load() { pImpl->aEngineArr.DeleteAndDestroy(0, pImpl->aEngineArr.Count()); Sequence<OUString> aNodeNames = GetNodeNames(OUString()); const OUString* pNodeNames = aNodeNames.getConstArray(); for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength(); nNode++) { SvxSearchEngineDataPtr pNew = new SvxSearchEngineData; pNew->sEngineName = pNodeNames[nNode]; const Sequence<OUString>& rPropNames = lcl_GetSearchPropertyNames_Impl(); const OUString* pPropNames = rPropNames.getConstArray(); Sequence<OUString> aPropertyNames(rPropNames.getLength()); OUString* pPropertyNames = aPropertyNames.getArray(); const OUString sSlash(C2U("/")); sal_Int32 nProp; for(nProp = 0; nProp < rPropNames.getLength(); nProp++) { pPropertyNames[nProp] = wrapConfigurationElementName(pNodeNames[nNode]); pPropertyNames[nProp] += sSlash; pPropertyNames[nProp] += pPropNames[nProp]; } Sequence<Any> aValues = GetProperties(aPropertyNames); const Any* pValues = aValues.getConstArray(); for(nProp = 0; nProp < rPropNames.getLength(); nProp++) { switch(nProp) { case 0 : pValues[nProp] >>= pNew->sAndPrefix; break; case 1 : pValues[nProp] >>= pNew->sAndSuffix; break; case 2 : pValues[nProp] >>= pNew->sAndSeparator; break; case 3 : pValues[nProp] >>= pNew->nAndCaseMatch; break; case 4 : pValues[nProp] >>= pNew->sOrPrefix; break; case 5 : pValues[nProp] >>= pNew->sOrSuffix; break; case 6 : pValues[nProp] >>= pNew->sOrSeparator; break; case 7 : pValues[nProp] >>= pNew->nOrCaseMatch; break; case 8 : pValues[nProp] >>= pNew->sExactPrefix; break; case 9 : pValues[nProp] >>= pNew->sExactSuffix; break; case 10: pValues[nProp] >>= pNew->sExactSeparator; break; case 11: pValues[nProp] >>= pNew->nExactCaseMatch; break; } } pImpl->aEngineArr.Insert(pNew, pImpl->aEngineArr.Count()); } } /* -----------------------------17.01.01 09:57-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::Notify( const Sequence<OUString>& rPropertyNames) { Load(); } /* -----------------------------16.01.01 15:36-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::Commit() { OUString sNode; if(!pImpl->aEngineArr.Count()) ClearNodeSet(sNode); else { Sequence<PropertyValue> aSetValues(12 * pImpl->aEngineArr.Count()); PropertyValue* pSetValues = aSetValues.getArray(); sal_Int32 nSetValue = 0; const Sequence<OUString>& rPropNames = lcl_GetSearchPropertyNames_Impl(); const OUString* pPropNames = rPropNames.getConstArray(); const OUString sSlash(C2U("/")); for(sal_uInt16 i = 0; i < pImpl->aEngineArr.Count(); i++) { SvxSearchEngineDataPtr pSave = pImpl->aEngineArr[i]; for(sal_Int16 nProp = 0; nProp < rPropNames.getLength(); nProp++) { OUString sTmpName = sSlash; sTmpName += wrapConfigurationElementName(pSave->sEngineName); sTmpName += sSlash; sTmpName += pPropNames[nProp]; pSetValues[nProp].Name = sTmpName; switch(nProp) { case 0 : pSetValues[nProp].Value <<= pSave->sAndPrefix; break; case 1 : pSetValues[nProp].Value <<= pSave->sAndSuffix; break; case 2 : pSetValues[nProp].Value <<= pSave->sAndSeparator; break; case 3 : pSetValues[nProp].Value <<= pSave->nAndCaseMatch; break; case 4 : pSetValues[nProp].Value <<= pSave->sOrPrefix; break; case 5 : pSetValues[nProp].Value <<= pSave->sOrSuffix; break; case 6 : pSetValues[nProp].Value <<= pSave->sOrSeparator; break; case 7 : pSetValues[nProp].Value <<= pSave->nOrCaseMatch; break; case 8 : pSetValues[nProp].Value <<= pSave->sExactPrefix; break; case 9 : pSetValues[nProp].Value <<= pSave->sExactSuffix; break; case 10: pSetValues[nProp].Value <<= pSave->sExactSeparator; break; case 11: pSetValues[nProp].Value <<= pSave->nExactCaseMatch; break; } } pSetValues+= 12; } ReplaceSetProperties(sNode, aSetValues); } } /* -----------------------------19.03.01 10:02-------------------------------- ---------------------------------------------------------------------------*/ sal_uInt16 SvxSearchConfig::Count() { return pImpl->aEngineArr.Count(); } /* -----------------------------19.03.01 10:02-------------------------------- ---------------------------------------------------------------------------*/ const SvxSearchEngineData& SvxSearchConfig::GetData(sal_uInt16 nPos) { DBG_ASSERT(nPos < pImpl->aEngineArr.Count(), "wrong array index") return *pImpl->aEngineArr[nPos]; } /* -----------------------------19.03.01 10:38-------------------------------- ---------------------------------------------------------------------------*/ const SvxSearchEngineData* SvxSearchConfig::GetData(const rtl::OUString& rEngineName) { for(sal_uInt16 nPos = 0; nPos < pImpl->aEngineArr.Count(); nPos++) { if(pImpl->aEngineArr[nPos]->sEngineName == rEngineName) return pImpl->aEngineArr[nPos]; } return 0; } /* -----------------------------19.03.01 10:02-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::SetData(const SvxSearchEngineData& rData) { for(sal_uInt16 nPos = 0; nPos < pImpl->aEngineArr.Count(); nPos++) { if(pImpl->aEngineArr[nPos]->sEngineName == rData.sEngineName) { if((*pImpl->aEngineArr[nPos]) == rData) return; pImpl->aEngineArr.DeleteAndDestroy(nPos, 1); break; } } SvxSearchEngineDataPtr pInsert = new SvxSearchEngineData(rData); pImpl->aEngineArr.Insert(pInsert, pImpl->aEngineArr.Count()); SetModified(); } /* -----------------------------19.03.01 10:38-------------------------------- ---------------------------------------------------------------------------*/ void SvxSearchConfig::RemoveData(const rtl::OUString& rEngineName) { for(sal_uInt16 nPos = 0; nPos < pImpl->aEngineArr.Count(); nPos++) { if(pImpl->aEngineArr[nPos]->sEngineName == rEngineName) { pImpl->aEngineArr.DeleteAndDestroy(nPos, 1); SetModified(); return ; } } } <|endoftext|>
<commit_before><commit_msg>fdo#56980 drop cached shape engine on invalidation<commit_after><|endoftext|>
<commit_before><commit_msg>GRAPHICS: Check that the textureSRVs and/or samplers are non-empty before trying to iterate<commit_after><|endoftext|>
<commit_before>#include <QNetworkInterface> #include "DiscoveryServer.h" /* TODO: implement a security process based on activation * Client send Discovery process with an UUID, EMS check if * this UUID is known, if it's the case, we accept the request * and send back the DISCOVERY answer. * If it's not the case, we need to find a way to display a popup * on the screen to ask the user to accept the connection request * for this new UUID. * How to do that ? Creating a pipe for Inter process communication * between EMS and the UI, only for connexion inside the same machine ? * Have the connection between EMS and the UI on the same device * through a simple TCPSocket instead through websocket ? And let the * websockets connexion for the UI outside machine ? */ DiscoveryServer::DiscoveryServer(quint16 port, QObject *parent) : QObject(parent) { m_socket = new QUdpSocket(this); m_socket->bind(QHostAddress::AnyIPv4, port); qDebug() << "Udp Discovery server listening on port " << port; connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead())); } DiscoveryServer::~DiscoveryServer() { delete m_socket; } void DiscoveryServer::readyRead() { QByteArray buffer; buffer.resize(m_socket->pendingDatagramSize()); qDebug() << "Read Read"; QHostAddress sender; quint16 senderPort; m_socket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort); /* TODO: Read the datagram, and check the UUID */ qDebug() << "Message from: " << sender.toString(); qDebug() << "Message port: " << senderPort; qDebug() << "Message: " << buffer; //QByteArray datagram = "EMS_DISCOVER"; //m_udpSocket->writeDatagram(datagram.data(),datagram.size(), QHostAddress::Broadcast , BCAST_UDP_PORT); QHostAddress local_address; foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) { local_address = address; } } QByteArray datagram; datagram.append("EMS_IP "); datagram.append(local_address.toString()); m_socket->writeDatagram(datagram.data(), datagram.size(), sender, senderPort); } <commit_msg>Handle discovery mechanism with json message<commit_after>#include <QNetworkInterface> #include <QJsonObject> #include <QJsonDocument> #include <QCoreApplication> #include <QSettings> #include "DiscoveryServer.h" /* TODO: implement a security process based on activation * Client send Discovery process with an UUID, EMS check if * this UUID is known, if it's the case, we accept the request * and send back the DISCOVERY answer. * If it's not the case, we need to find a way to display a popup * on the screen to ask the user to accept the connection request * for this new UUID. * How to do that ? Creating a pipe for Inter process communication * between EMS and the UI, only for connexion inside the same machine ? * Have the connection between EMS and the UI on the same device * through a simple TCPSocket instead through websocket ? And let the * websockets connexion for the UI outside machine ? */ DiscoveryServer::DiscoveryServer(quint16 port, QObject *parent) : QObject(parent) { m_socket = new QUdpSocket(this); m_socket->bind(QHostAddress::AnyIPv4, port); qDebug() << "Udp Discovery server listening on port " << port; connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead())); } DiscoveryServer::~DiscoveryServer() { delete m_socket; } void DiscoveryServer::readyRead() { QByteArray buffer; buffer.resize(m_socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; // Read data received m_socket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort); QJsonParseError err; QJsonDocument j = QJsonDocument::fromJson(buffer, &err); // Error reading Json if (err.error!= QJsonParseError::NoError) { return; } // TODO : check if UUID is accepted qDebug() << "UUID :" << j.object()["uuid"].toString(); QHostAddress local_address; // Get the local address foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) { local_address = address; } } QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName()); // Create object containing the answer QJsonObject jobj; jobj["action"] = "EMS_DISCOVER"; jobj["status"] = "accepted"; jobj["ip"] = local_address.toString(); jobj["port"] = settings.value("main/websocket_port").toInt(); qDebug() << "Port : " << settings.value("main/websocket_port").toInt(); QJsonDocument jdoc(jobj); // Convert json object into datagram QByteArray datagram = jdoc.toJson(QJsonDocument::Compact); // Send the data m_socket->writeDatagram(datagram.data(), datagram.size(), sender, senderPort); } <|endoftext|>
<commit_before>#include "Assembler.hpp" #include "VMOpcodes.hpp" #include <sstream> #include <cstdio> namespace wvm { static void stripAsmComments(std::string& str) { bool erasing = false; str += ' '; for(std::size_t i = 1u; i < str.size(); ++i) { if(str[i] == '\n') erasing = false; if(str[i] == '/' && str[i + 1u] == '/') erasing = true; if(erasing) str[i] = ' '; } } bool assemble(std::string code, std::vector<short>& outopcodes, std::string * error) { stripAsmComments(code); std::istringstream ss(code); std::string asmcommand; outopcodes.clear(); while(ss >> asmcommand) { const EVM_OPCODE opcode = strToOpcode(asmcommand.c_str(), asmcommand.size()); if(opcode == EVO_OPCODES_COUNT) //no such code { if(error) { (*error) = "'" + asmcommand + "' is not a valid command"; } return false; } //if opcode == EVO_OPCODES_COUNT outopcodes.push_back(opcode); for(int i = 0; i < opcodeArgCount(opcode); ++i) { int arg; if(ss >> arg) { outopcodes.push_back(arg); } else //cant read next number { if(error) { char buff[256]; std::sprintf(buff, "' needs %d args, found only %d\n", opcodeArgCount(opcode), i); (*error) = "'" + asmcommand + buff; } return false; } }//for i = 0, opcodeArgCount opcode, 1 } //while ss >> asmcommand return true; } } <commit_msg>fixed typo in asm comment stripper<commit_after>#include "Assembler.hpp" #include "VMOpcodes.hpp" #include <sstream> #include <cstdio> namespace wvm { static void stripAsmComments(std::string& str) { bool erasing = false; str += ' '; for(std::size_t i = 0u; i < str.size(); ++i) { if(str[i] == '\n') erasing = false; if(str[i] == '/' && str[i + 1u] == '/') erasing = true; if(erasing) str[i] = ' '; } } bool assemble(std::string code, std::vector<short>& outopcodes, std::string * error) { stripAsmComments(code); std::istringstream ss(code); std::string asmcommand; outopcodes.clear(); while(ss >> asmcommand) { const EVM_OPCODE opcode = strToOpcode(asmcommand.c_str(), asmcommand.size()); if(opcode == EVO_OPCODES_COUNT) //no such code { if(error) { (*error) = "'" + asmcommand + "' is not a valid command"; } return false; } //if opcode == EVO_OPCODES_COUNT outopcodes.push_back(opcode); for(int i = 0; i < opcodeArgCount(opcode); ++i) { int arg; if(ss >> arg) { outopcodes.push_back(arg); } else //cant read next number { if(error) { char buff[256]; std::sprintf(buff, "' needs %d args, found only %d\n", opcodeArgCount(opcode), i); (*error) = "'" + asmcommand + buff; } return false; } }//for i = 0, opcodeArgCount opcode, 1 } //while ss >> asmcommand return true; } } <|endoftext|>
<commit_before>//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This contains code dealing with C++ exception related code generation. // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" using namespace clang; using namespace CodeGen; static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) { // void *__cxa_allocate_exception(size_t thrown_size); const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); std::vector<const llvm::Type*> Args(1, SizeTy); const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()), Args, false); return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception"); } static llvm::Constant *getThrowFn(CodeGenFunction &CGF) { // void __cxa_throw (void *thrown_exception, std::type_info *tinfo, // void (*dest) (void *) ); const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext()); std::vector<const llvm::Type*> Args(3, Int8PtrTy); const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), Args, false); return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw"); } void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) { // FIXME: Handle rethrows. if (!E->getSubExpr()) { ErrorUnsupported(E, "rethrow expression"); return; } QualType ThrowType = E->getSubExpr()->getType(); // FIXME: We only handle non-class types for now. if (ThrowType->isRecordType()) { ErrorUnsupported(E, "throw expression"); return; } // FIXME: Handle cleanup. if (!CleanupEntries.empty()){ ErrorUnsupported(E, "throw expression"); return; } // Now allocate the exception object. const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); uint64_t TypeSize = getContext().getTypeSize(ThrowType) / 8; llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this); llvm::Value *ExceptionPtr = Builder.CreateCall(AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception"); // Store the throw exception in the exception object. if (!hasAggregateLLVMType(ThrowType)) { llvm::Value *Value = EmitScalarExpr(E->getSubExpr()); const llvm::Type *ValuePtrTy = Value->getType()->getPointerTo(0); Builder.CreateStore(Value, Builder.CreateBitCast(ExceptionPtr, ValuePtrTy)); } else { // FIXME: Handle complex and aggregate expressions. ErrorUnsupported(E, "throw expression"); } // Now throw the exception. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext()); llvm::SmallString<256> OutName; llvm::raw_svector_ostream Out(OutName); mangleCXXRtti(CGM.getMangleContext(), ThrowType, Out); // FIXME: Is it OK to use CreateRuntimeVariable for this? llvm::Constant *TypeInfo = CGM.CreateRuntimeVariable(llvm::Type::getInt8Ty(getLLVMContext()), OutName.c_str()); llvm::Constant *Dtor = llvm::Constant::getNullValue(Int8PtrTy); llvm::CallInst *ThrowCall = Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor); ThrowCall->setDoesNotReturn(); Builder.CreateUnreachable(); // Clear the insertion point to indicate we are in unreachable code. Builder.ClearInsertionPoint(); } <commit_msg>Fix rtti generation for throws. WIP.<commit_after>//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This contains code dealing with C++ exception related code generation. // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" using namespace clang; using namespace CodeGen; static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) { // void *__cxa_allocate_exception(size_t thrown_size); const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); std::vector<const llvm::Type*> Args(1, SizeTy); const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()), Args, false); return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception"); } static llvm::Constant *getThrowFn(CodeGenFunction &CGF) { // void __cxa_throw (void *thrown_exception, std::type_info *tinfo, // void (*dest) (void *) ); const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext()); std::vector<const llvm::Type*> Args(3, Int8PtrTy); const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), Args, false); return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw"); } void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) { // FIXME: Handle rethrows. if (!E->getSubExpr()) { ErrorUnsupported(E, "rethrow expression"); return; } QualType ThrowType = E->getSubExpr()->getType(); // FIXME: We only handle non-class types for now. if (ThrowType->isRecordType()) { ErrorUnsupported(E, "throw expression"); return; } // FIXME: Handle cleanup. if (!CleanupEntries.empty()){ ErrorUnsupported(E, "throw expression"); return; } // Now allocate the exception object. const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); uint64_t TypeSize = getContext().getTypeSize(ThrowType) / 8; llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this); llvm::Value *ExceptionPtr = Builder.CreateCall(AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception"); // Store the throw exception in the exception object. if (!hasAggregateLLVMType(ThrowType)) { llvm::Value *Value = EmitScalarExpr(E->getSubExpr()); const llvm::Type *ValuePtrTy = Value->getType()->getPointerTo(0); Builder.CreateStore(Value, Builder.CreateBitCast(ExceptionPtr, ValuePtrTy)); } else { // FIXME: Handle complex and aggregate expressions. ErrorUnsupported(E, "throw expression"); } // Now throw the exception. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext()); llvm::Constant *TypeInfo = CGM.GenerateRtti(ThrowType); llvm::Constant *Dtor = llvm::Constant::getNullValue(Int8PtrTy); llvm::CallInst *ThrowCall = Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor); ThrowCall->setDoesNotReturn(); Builder.CreateUnreachable(); // Clear the insertion point to indicate we are in unreachable code. Builder.ClearInsertionPoint(); } <|endoftext|>
<commit_before>/* ATS is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Authors: Ethan Coon ([email protected]) */ //! An evaluator for calculating the water table height, relative to the surface. #include "water_table_depth_evaluator.hh" namespace Amanzi { namespace Relations { ParserWaterTableDepth::ParserWaterTableDepth(Teuchos::ParameterList& plist, const KeyTag& key_tag) { Key domain = Keys::getDomain(key_tag.first); Tag tag = key_tag.second; Key domain_ss = Keys::readDomainHint(plist, domain, "surface", "subsurface"); Key sat_key = Keys::readKey(plist, domain_ss, "saturation of liquid", "saturation_liquid"); dependencies.insert(KeyTag{sat_key, tag}); Key cv_key = Keys::readKey(plist, domain_ss, "cell volume", "cell_volume"); dependencies.insert(KeyTag{cv_key, tag}); Key cv_surf_key = Keys::readKey(plist, domain, "cell volume", "cell_volume"); dependencies.insert(KeyTag{cv_surf_key, tag}); } IntegratorWaterTableDepth::IntegratorWaterTableDepth(Teuchos::ParameterList& plist, std::vector<const Epetra_MultiVector*>& deps, const AmanziMesh::Mesh* mesh) { sat_ = deps[0]; cv_ = deps[1]; surf_cv_ = deps[2]; } int IntegratorWaterTableDepth::scan(AmanziMesh::Entity_ID col, AmanziMesh::Entity_ID c, AmanziGeometry::Point& p) { if ((*sat_)[0][c] < 1.0) { p[0] += (*cv_)[0][c]; return false; } return true; } double IntegratorWaterTableDepth::coefficient(AmanziMesh::Entity_ID col) { return 1./(*surf_cv_)[0][col]; } } //namespace } //namespace <commit_msg>fixes bug in identically named parameters, which would result in same key and therefore memory errors<commit_after>/* ATS is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Authors: Ethan Coon ([email protected]) */ //! An evaluator for calculating the water table height, relative to the surface. #include "water_table_depth_evaluator.hh" namespace Amanzi { namespace Relations { ParserWaterTableDepth::ParserWaterTableDepth(Teuchos::ParameterList& plist, const KeyTag& key_tag) { Key domain = Keys::getDomain(key_tag.first); Tag tag = key_tag.second; Key domain_ss = Keys::readDomainHint(plist, domain, "surface", "subsurface"); Key sat_key = Keys::readKey(plist, domain_ss, "saturation of liquid", "saturation_liquid"); dependencies.insert(KeyTag{sat_key, tag}); Key cv_key = Keys::readKey(plist, domain_ss, "subsurface cell volume", "cell_volume"); dependencies.insert(KeyTag{cv_key, tag}); Key cv_surf_key = Keys::readKey(plist, domain, "surface cell volume", "cell_volume"); dependencies.insert(KeyTag{cv_surf_key, tag}); } IntegratorWaterTableDepth::IntegratorWaterTableDepth(Teuchos::ParameterList& plist, std::vector<const Epetra_MultiVector*>& deps, const AmanziMesh::Mesh* mesh) { AMANZI_ASSERT(deps.size() == 3); sat_ = deps[0]; cv_ = deps[1]; surf_cv_ = deps[2]; } int IntegratorWaterTableDepth::scan(AmanziMesh::Entity_ID col, AmanziMesh::Entity_ID c, AmanziGeometry::Point& p) { if ((*sat_)[0][c] < 1.0) { p[0] += (*cv_)[0][c]; return false; } return true; } double IntegratorWaterTableDepth::coefficient(AmanziMesh::Entity_ID col) { return 1./(*surf_cv_)[0][col]; } } //namespace } //namespace <|endoftext|>
<commit_before>#include "../includes/AxisInertia.hpp" #include "../includes/pdb/CGReader.hpp" #include "../includes/para/MassConst.hpp" using namespace coffeemill; int main(int argc, char *argv[]) { if(argc != 3) { std::cerr << "Usage: ./inertia <filename>.pdb [chain IDs]" << std::endl; std::cerr << " : cg pdb only" << std::endl; return 1; } std::string filename(argv[1]); CGReader reader(filename); reader.read_file(); CGMdlSptr model = reader.get_model(0); std::vector<CGChnSptr> chains(model->get_data()); std::size_t particle_num(0); std::string chainIDs(argv[2]); std::transform(chainIDs.cbegin(), chainIDs.cend(), chainIDs.begin(), toupper); for(auto iter = chains.begin(); iter != chains.end();) if(chainIDs.find((*iter)->get_chainID()) == std::string::npos) chains.erase(iter); else ++iter; for(auto iter = chains.begin(); iter != chains.end(); ++iter) particle_num += (*iter)->size(); std::vector<std::pair<Realvec, double>> particles(particle_num); int atom_index(0); for(auto chain_iter = chains.begin(); chain_iter != chains.end(); ++chain_iter) { for(auto atom_iter = (*chain_iter)->begin(); atom_iter != (*chain_iter)->end(); ++atom_iter) { std::string element = (*atom_iter)->get_beadname(); std::size_t pos; while((pos = element.find_first_of(" ")) != std::string::npos) element.erase(pos, 1); Realvec position((*atom_iter)->get_coordx(), (*atom_iter)->get_coordy(), (*atom_iter)->get_coordz()); particles.at(atom_index) = std::make_pair(position, AtomMass::getInstance().get_mass_atom(element[0])); ++atom_index; } } AxisInertia inertia(particles); // Realvec axisline1 = inertia.get_CoM() + 1e2 * inertia.get_axis(0); // Realvec axisline2 = inertia.get_CoM() + 1e2 * inertia.get_axis(1); // Realvec axisline3 = inertia.get_CoM() + 1e2 * inertia.get_axis(2); std::cout << "Center of Mass: " << inertia.get_CoM() << std::endl; std::cout << "Axis 1 : " << inertia.get_axis(0) << ", length: " << length(inertia.get_axis(0)) << std::endl; std::cout << "Axis 2 : " << inertia.get_axis(1) << ", length: " << length(inertia.get_axis(1)) << std::endl; std::cout << "Axis 3 : " << inertia.get_axis(2) << ", length: " << length(inertia.get_axis(2)) << std::endl; // std::cout << "Axis 1 line : " << axisline1 << std::endl; // std::cout << "Axis 2 line : " << axisline2 << std::endl; // std::cout << "Axis 3 line : " << axisline3 << std::endl; return 0; } <commit_msg>small change in CG-Inertia<commit_after>#include "../includes/AxisInertia.hpp" #include "../includes/pdb/CGReader.hpp" #include "../includes/para/MassConst.hpp" using namespace coffeemill; int main(int argc, char *argv[]) { if(argc != 3) { std::cerr << "Usage: ./inertia <filename>.pdb [chain IDs]" << std::endl; std::cerr << " : cg pdb only" << std::endl; return 1; } std::string filename(argv[1]); CGReader reader(filename); reader.read_file(); CGMdlSptr model = reader.get_model(0); std::vector<CGChnSptr> chains(model->get_data()); std::size_t particle_num(0); std::string chainIDs(argv[2]); std::transform(chainIDs.cbegin(), chainIDs.cend(), chainIDs.begin(), toupper); for(auto iter = chains.begin(); iter != chains.end();) if(chainIDs.find((*iter)->get_chainID()) == std::string::npos) chains.erase(iter); else ++iter; for(auto iter = chains.begin(); iter != chains.end(); ++iter) particle_num += (*iter)->size(); std::vector<std::pair<Realvec, double>> particles(particle_num); int atom_index(0); for(auto chain_iter = chains.begin(); chain_iter != chains.end(); ++chain_iter) { for(auto atom_iter = (*chain_iter)->begin(); atom_iter != (*chain_iter)->end(); ++atom_iter) { std::string element = (*atom_iter)->get_beadname(); std::size_t pos; while((pos = element.find_first_of(" ")) != std::string::npos) element.erase(pos, 1); Realvec position((*atom_iter)->get_coordx(), (*atom_iter)->get_coordy(), (*atom_iter)->get_coordz()); particles.at(atom_index) = std::make_pair(position, 1e0); // AtomMass::getInstance().get_mass_atom(element[0])); ++atom_index; } } AxisInertia inertia(particles); Realvec axisline1 = inertia.get_CoM() + 1e2 * inertia.get_axis(0); Realvec axisline2 = inertia.get_CoM() + 1e2 * inertia.get_axis(1); Realvec axisline3 = inertia.get_CoM() + 1e2 * inertia.get_axis(2); std::cout << "Center of Mass: " << inertia.get_CoM() << std::endl; std::cout << "Axis 1 : " << inertia.get_axis(0) << ", length: " << length(inertia.get_axis(0)) << std::endl; std::cout << "Axis 2 : " << inertia.get_axis(1) << ", length: " << length(inertia.get_axis(1)) << std::endl; std::cout << "Axis 3 : " << inertia.get_axis(2) << ", length: " << length(inertia.get_axis(2)) << std::endl; std::cout << "Axis 1 line : " << axisline1 << std::endl; std::cout << "Axis 2 line : " << axisline2 << std::endl; std::cout << "Axis 3 line : " << axisline3 << std::endl; return 0; } <|endoftext|>
<commit_before><commit_msg>fdo#54620 do not use vector iterator after insert<commit_after><|endoftext|>
<commit_before><commit_msg>dead increment (clang)<commit_after><|endoftext|>
<commit_before>#include "tcp_socket.h" #ifndef _WIN32 #define POSIX #endif //Include these files if the platform is POSIX #ifdef POSIX #include <sys/stat.h> #include <sys/socket.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <netinet/in.h> #endif #include <cstring> #include <thread> #include <sstream> #include "../stringproc.h" #define E_SOCK_CREATE_ERROR -1 #define E_SOCK_BIND_ERROR -2 #define E_BAD_ALLOC -3 #define E_BAD_WRITE -4 #define E_BAD_READ -5 #include <stdio.h> dev::TcpServer::TcpServer() : _address_allocated(false) { _address = NULL; } inline struct sockaddr_in* s(void* v) { return (struct sockaddr_in*) v; } inline void* v(struct sockaddr_in* s) { return (struct sockaddr_in*) s; } int dev::TcpServer::start(int port) { //Set the port number of the class as the given one _port = port; //Create the socket _fd = socket(AF_INET, SOCK_STREAM, 0); //Check to make sure socket creation was successful if(_fd < 0) { throw dev::TcpServerException(E_SOCK_CREATE_ERROR, "Unable to create socket"); } //Allocate memory for the socket address structure and //initialize to zero try { _address = new struct sockaddr_in; } catch(std::bad_alloc& e) { throw dev::TcpServerException(E_BAD_ALLOC, "Unable to allocate memory for the address structre"); } _address_allocated = true; bzero((char*) _address, sizeof(struct sockaddr_in)); //Populate the server address structure with important information s(_address)->sin_family = AF_INET; s(_address)->sin_addr.s_addr = htonl(INADDR_ANY); s(_address)->sin_port = htons(_port); //Bind the socket to the address/port if(bind(_fd, (struct sockaddr*) _address, sizeof(struct sockaddr_in)) < 0) { throw dev::TcpServerException(E_SOCK_BIND_ERROR, "Unable to bind to socket"); } //Begin listening for incoming connections. The queue depth is 3 listen(_fd, 3); //Infinitely wait for an incoming connection and accept. while(true) { dev::TcpServerSession* session; //Allocate a new session try { session = new dev::TcpServerSession; } catch(std::bad_alloc& e) { //We were unable to allocate memory. Wait 10 ms before retrying. Hopefully another //server thread or something quit by now. std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } //Just a temporary var really int c = sizeof(struct sockaddr_in); //Accept the new connection session->_fd = accept(_fd, (struct sockaddr*) session->_address, (socklen_t*) &c); //Check for accept failures if(session->_fd < 0) { //Prevent a memory leak delete session; //Retry continue; } //Set the pointer to the server in the TCP socket session object so that the user //has external access to this object session->server = this; //Handle the connection. Have fun :) std::thread(&dev::TcpServer::listenerProxy, this, session).detach(); } } void dev::TcpServer::listenerProxy(dev::TcpServerSession* connection) { //To catch any exceptions encountered. If any exceptions get past, the program will crash // (BAD). Note that failure is very common because an exception is thrown whenever there is // a connection error! try { //Let the user play with the connection worker(connection); } catch(std::exception& e) {} //Deallocate the connection structure. We hate runaway RAM ;) delete connection; } void dev::TcpServer::worker(dev::TcpServerSession* connection) { connection->put("Hello World!\nYour TCP server works! Now, create a class which inherits off dev::TcpServer and implement your own worker function!\n"); std::this_thread::sleep_for(std::chrono::seconds(10)); } dev::TcpServer::~TcpServer() { //Memory management -- deallocate RAM if it is not being used. if(_address_allocated) { struct sockaddr_in* ad = (struct sockaddr_in*) _address; delete ad; } close(_fd); } //!----------Session functions. Random other clutter---------- dev::TcpServerSession::TcpServerSession() { //Allocate _address = (void*) new struct sockaddr_in; } dev::TcpServerSession::~TcpServerSession() { //Deallocate struct sockaddr_in* sock = (struct sockaddr_in*) _address; delete sock; shutdown(_fd, SHUT_WR); close(_fd); } int dev::TcpServerSession::put(char byte) { int o = ::send(_fd, &byte, 1, MSG_NOSIGNAL); if(o < 0) throw dev::TcpServerException(E_BAD_WRITE, "Unable to write to socket"); return o; } int dev::TcpServerSession::put(std::string string) { int o = ::send(_fd, string.c_str(), string.size(), MSG_NOSIGNAL); if(o < 0) throw dev::TcpServerException(E_BAD_WRITE, "Unable to write to socket"); return o; } char dev::TcpServerSession::get() { char ch; int o = ::recv(_fd, &ch, 1, 0); if(o < 0) throw dev::TcpServerException(E_BAD_READ, "Unable to read from socket"); return ch; } std::string dev::TcpServerSession::get(int mxlength) { //Allocate space for a C String char* ch = new char[mxlength + 1]; //Read some data int o = ::recv(_fd, ch, mxlength, 0); if(o < 0) { delete[] ch; throw dev::TcpServerException(E_BAD_READ, "Unable to read from socket"); } //Place the NULL terminator (for safety and prevention of ugly SEGFAULTS!!!) ch[o] = '\0'; std::string ret = dev::toString(ch); //GC delete[] ch; return ret; } std::string dev::TcpServerSession::readLine(char end) { std::stringstream str; while(true) { char ch; int x = ::recv(_fd, &ch, 1, 0); if(ch == end) return str.str(); if(x < 0) return str.str(); str << ch; } } std::string dev::TcpServerSession::readLine(std::string end) { std::string line = ""; while(true) { if(line.size() >= end.size()) { if(line.substr(line.size() - (end.size() - 1), line.size() - 1) == end) { break; } } line += (char) get(); } return line = line.substr(0, line.size() - (end.size() + 1)); } std::string dev::TcpServerSession::readLine(std::vector<std::string> end) { if(end.size() == 0) return ""; size_t len = end[0].size(); for(size_t i = 0; i < end.size(); i++) { if(end[i].size() != len) return ""; } std::string line = ""; while(true) { if(line.size() >= len) { for(size_t i = 0; i < end.size(); i++) { std::string x = line.substr(line.size() - (len - 1) - 1, line.size()); if(x == end[i]) { return line.substr(0, line.size() - len); } } } line += (char) get(); } } //int dev::TcpServerSession::put(char byte) //{ // int o = write(_fd, &byte, sizeof(byte)); // if(o < 0) throw dev::TcpServerException(E_BAD_WRITE, "Unable to write to socket"); // return o; //} //int dev::TcpServerSession::put(std::string string) //{ // int o = write(_fd, string.c_str(), string.size()); // if(o < 0) throw dev::TcpServerException(E_BAD_WRITE, "Unable to write to socket"); // return 0; //} //char dev::TcpServerSession::read() //{ // return this->read(1)[0]; //} //std::string dev::TcpServerSession::read(int length) //{ // char* x = new char[length]; //Allocate some memory to read into // //Attempt to read from the socket. Throw and exception otherwise // if(recv(_fd, x, length, 0) < 0) // { // throw dev::TcpServerException(E_BAD_READ, "Unable to read from socket!"); // } // //Convert what we recieved to an std::string so we have automatic GC. // std::string z = dev::toString(x); // //Deallocate the memory that we previously allocated // delete[] x; // //Return the string! // return z; //} //std::string dev::TcpServerSession::readline(char end) //{ // std::string out; // try // { // while(true) // { // char c = read(1)[0]; // if(c == end) // { // return out; // } // else // { // out += c; // } // } // return out; // } // catch(std::exception& e) // { // return out; // } //} //std::string dev::TcpServerSession::readline(std::string end) //{ // std::string out; // try // { // while(true) // { // if(out.size() >= end.size()) // { // if(!strcmp(out.substr(out.size() - end.size(), out.size()).c_str(), end.c_str())) // { // return out.substr(0, out.size() - end.size()); // } // } // char ch = (char) read(1)[0]; // out += ch; // } // } // catch(std::exception& e) // { // return out; // } //} dev::TcpServerException::TcpServerException() : _code(0), _message("Server Error") {} dev::TcpServerException::TcpServerException(int code) : _code(code), _message("Server Error") {} dev::TcpServerException::TcpServerException(const char* message) : _code(0), _message(message) {} dev::TcpServerException::TcpServerException(int code, const char* message) : _code(code), _message(message) {} const int dev::TcpServerException::code() { return _code; } const char* dev::TcpServerException::what() const throw() { return _message; } dev::TcpServerException::~TcpServerException() {} <commit_msg>Cleaning up<commit_after>#include "tcp_socket.h" #ifndef _WIN32 #define POSIX #endif //Include these files if the platform is POSIX #ifdef POSIX #include <sys/stat.h> #include <sys/socket.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <netinet/in.h> #endif #include <cstring> #include <thread> #include <sstream> #include "../stringproc.h" #define E_SOCK_CREATE_ERROR -1 #define E_SOCK_BIND_ERROR -2 #define E_BAD_ALLOC -3 #define E_BAD_WRITE -4 #define E_BAD_READ -5 #include <stdio.h> dev::TcpServer::TcpServer() : _address_allocated(false) { _address = NULL; } inline struct sockaddr_in* s(void* v) { return (struct sockaddr_in*) v; } inline void* v(struct sockaddr_in* s) { return (struct sockaddr_in*) s; } int dev::TcpServer::start(int port) { //Set the port number of the class as the given one _port = port; //Create the socket _fd = socket(AF_INET, SOCK_STREAM, 0); //Check to make sure socket creation was successful if(_fd < 0) { throw dev::TcpServerException(E_SOCK_CREATE_ERROR, "Unable to create socket"); } //Allocate memory for the socket address structure and //initialize to zero try { _address = new struct sockaddr_in; } catch(std::bad_alloc& e) { throw dev::TcpServerException(E_BAD_ALLOC, "Unable to allocate memory for the address structre"); } _address_allocated = true; bzero((char*) _address, sizeof(struct sockaddr_in)); //Populate the server address structure with important information s(_address)->sin_family = AF_INET; s(_address)->sin_addr.s_addr = htonl(INADDR_ANY); s(_address)->sin_port = htons(_port); //Bind the socket to the address/port if(bind(_fd, (struct sockaddr*) _address, sizeof(struct sockaddr_in)) < 0) { throw dev::TcpServerException(E_SOCK_BIND_ERROR, "Unable to bind to socket"); } //Begin listening for incoming connections. The queue depth is 3 listen(_fd, 3); //Infinitely wait for an incoming connection and accept. while(true) { dev::TcpServerSession* session; //Allocate a new session try { session = new dev::TcpServerSession; } catch(std::bad_alloc& e) { //We were unable to allocate memory. Wait 10 ms before retrying. Hopefully another //server thread or something quit by now. std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } //Just a temporary var really int c = sizeof(struct sockaddr_in); //Accept the new connection session->_fd = accept(_fd, (struct sockaddr*) session->_address, (socklen_t*) &c); //Check for accept failures if(session->_fd < 0) { //Prevent a memory leak delete session; //Retry continue; } //Set the pointer to the server in the TCP socket session object so that the user //has external access to this object session->server = this; //Handle the connection. Have fun :) std::thread(&dev::TcpServer::listenerProxy, this, session).detach(); } } void dev::TcpServer::listenerProxy(dev::TcpServerSession* connection) { //To catch any exceptions encountered. If any exceptions get past, the program will crash // (BAD). Note that failure is very common because an exception is thrown whenever there is // a connection error! try { //Let the user play with the connection worker(connection); } catch(std::exception& e) {} //Deallocate the connection structure. We hate runaway RAM ;) delete connection; } void dev::TcpServer::worker(dev::TcpServerSession* connection) { connection->put("Hello World!\nYour TCP server works! Now, create a class which inherits off dev::TcpServer and implement your own worker function!\n"); std::this_thread::sleep_for(std::chrono::seconds(10)); } dev::TcpServer::~TcpServer() { //Memory management -- deallocate RAM if it is not being used. if(_address_allocated) { struct sockaddr_in* ad = (struct sockaddr_in*) _address; delete ad; } close(_fd); } //!----------Session functions. Random other clutter---------- dev::TcpServerSession::TcpServerSession() { //Allocate _address = (void*) new struct sockaddr_in; } dev::TcpServerSession::~TcpServerSession() { //Deallocate struct sockaddr_in* sock = (struct sockaddr_in*) _address; delete sock; shutdown(_fd, SHUT_WR); close(_fd); } int dev::TcpServerSession::put(char byte) { int o = ::send(_fd, &byte, 1, MSG_NOSIGNAL); if(o < 0) throw dev::TcpServerException(E_BAD_WRITE, "Unable to write to socket"); return o; } int dev::TcpServerSession::put(std::string string) { int o = ::send(_fd, string.c_str(), string.size(), MSG_NOSIGNAL); if(o < 0) throw dev::TcpServerException(E_BAD_WRITE, "Unable to write to socket"); return o; } char dev::TcpServerSession::get() { char ch; int o = ::recv(_fd, &ch, 1, 0); if(o < 0) throw dev::TcpServerException(E_BAD_READ, "Unable to read from socket"); return ch; } std::string dev::TcpServerSession::get(int mxlength) { //Allocate space for a C String char* ch = new char[mxlength + 1]; //Read some data int o = ::recv(_fd, ch, mxlength, 0); if(o < 0) { delete[] ch; throw dev::TcpServerException(E_BAD_READ, "Unable to read from socket"); } //Place the NULL terminator (for safety and prevention of ugly SEGFAULTS!!!) ch[o] = '\0'; std::string ret = dev::toString(ch); //GC delete[] ch; return ret; } std::string dev::TcpServerSession::readLine(char end) { std::stringstream str; while(true) { char ch; int x = ::recv(_fd, &ch, 1, 0); if(ch == end) return str.str(); if(x < 0) return str.str(); str << ch; } } std::string dev::TcpServerSession::readLine(std::string end) { std::string line = ""; while(true) { if(line.size() >= end.size()) { if(line.substr(line.size() - (end.size() - 1), line.size() - 1) == end) { break; } } line += (char) get(); } return line = line.substr(0, line.size() - (end.size() + 1)); } std::string dev::TcpServerSession::readLine(std::vector<std::string> end) { if(end.size() == 0) return ""; size_t len = end[0].size(); for(size_t i = 0; i < end.size(); i++) { if(end[i].size() != len) return ""; } std::string line = ""; while(true) { if(line.size() >= len) { for(size_t i = 0; i < end.size(); i++) { std::string x = line.substr(line.size() - (len - 1) - 1, line.size()); if(x == end[i]) { return line.substr(0, line.size() - len); } } } line += (char) get(); } } dev::TcpServerException::TcpServerException() : _code(0), _message("Server Error") {} dev::TcpServerException::TcpServerException(int code) : _code(code), _message("Server Error") {} dev::TcpServerException::TcpServerException(const char* message) : _code(0), _message(message) {} dev::TcpServerException::TcpServerException(int code, const char* message) : _code(code), _message(message) {} const int dev::TcpServerException::code() { return _code; } const char* dev::TcpServerException::what() const throw() { return _message; } dev::TcpServerException::~TcpServerException() {} <|endoftext|>
<commit_before>#if !defined( __CINT__) || defined(__MAKECINT__) #include <iostream> #include <AliCDBManager.h> #include <AliCDBStorage.h> #include <AliCDBEntry.h> #include <AliCDBMetaData.h> #include "AliTRDgeometry.h" #include "AliTRDCalROC.h" #include "AliTRDCalChamberPos.h" #include "AliTRDCalStackPos.h" #include "AliTRDCalSuperModulePos.h" #include "AliTRDCalPad.h" #include "AliTRDCalDet.h" #include "AliTRDCalGlobals.h" #include "AliTRDCalSuperModuleStatus.h" #include "AliTRDCalChamberStatus.h" #include "AliTRDCalMCMStatus.h" #include "AliTRDCalPadStatus.h" #include "AliTRDCalSingleChamberStatus.h" #include "AliTRDCalPIDLQ.h" #include "AliTRDCalMonitoring.h" #endif // run number for the dummy file const Int_t gkDummyRun = 0; AliCDBStorage* gStorLoc = 0; TObject* CreatePadObject(const char* shortName, const char* description, Float_t value) { AliTRDCalPad *calPad = new AliTRDCalPad(shortName, description); for (Int_t det=0; det<AliTRDgeometry::kNdet; ++det) { AliTRDCalROC *calROC = calPad->GetCalROC(det); for (Int_t channel=0; channel<calROC->GetNchannels(); ++channel) calROC->SetValue(channel, value); } return calPad; } TObject* CreateDetObject(const char* shortName, const char* description, Float_t value) { AliTRDCalDet *object = new AliTRDCalDet(shortName, description); for (Int_t det=0; det<AliTRDgeometry::kNdet; ++det) object->SetValue(det, value); return object; } TObject* CreateGlobalsObject() { AliTRDCalGlobals *object = new AliTRDCalGlobals("Globals", "Global TRD calibration parameters"); object->SetSamplingFrequency(10.0); object->SetNumberOfTimeBins(22); return object; } TObject* CreateChamberObject() { AliTRDCalChamberPos *object = new AliTRDCalChamberPos("Chamber", "TRD chamber positions"); for (Int_t det=0; det<AliTRDgeometry::kNdet; ++det) { object->SetPos(det, 0, 0, 0); object->SetRot(det, 0, 0, 0); } return object; } TObject* CreateStackObject() { AliTRDCalStackPos *object = new AliTRDCalStackPos("Stack", "TRD stack positions"); for (Int_t sect=0; sect<AliTRDgeometry::kNsect; ++sect) { for (Int_t chamber=0; chamber<AliTRDgeometry::kNcham; ++chamber) { object->SetPos(chamber, sect, 0, 0, 0); object->SetRot(chamber, sect, 0, 0, 0); } } return object; } TObject* CreateSuperModuleObject() { AliTRDCalSuperModulePos *object = new AliTRDCalSuperModulePos("Stack", "TRD supermodule positions"); for (Int_t sect=0; sect<AliTRDgeometry::kNsect; ++sect) { object->SetPos(sect, 0, 0, 0); object->SetRot(sect, 0, 0, 0); } return object; } TObject* CreatePRFWidthObject() { AliTRDCalPad *calPad = new AliTRDCalPad("PRFWidth","PRFWidth"); for (Int_t plane=0; plane<AliTRDgeometry::kNplan; ++plane) { Float_t value = 0; switch (plane) { case 0: value = 0.515; break; case 1: value = 0.502; break; case 2: value = 0.491; break; case 3: value = 0.481; break; case 4: value = 0.471; break; case 5: value = 0.463; break; default: cout << "CreatePRFWidthObject: UNEXPECTED" << endl; return 0; } for (Int_t chamber=0; chamber<AliTRDgeometry::kNcham; ++chamber) { for (Int_t sector=0; sector<AliTRDgeometry::kNsect; ++sector) { AliTRDCalROC *calROC = calPad->GetCalROC(plane, chamber, sector); for (Int_t channel=0; channel<calROC->GetNchannels(); ++channel) calROC->SetValue(channel, value); } } } return calPad; } AliTRDCalSuperModuleStatus* CreateSuperModuleStatusObject() { AliTRDCalSuperModuleStatus* obj = new AliTRDCalSuperModuleStatus("supermodulestatus", "supermodulestatus"); for (Int_t i=0; i<AliTRDgeometry::kNsect; ++i) obj->SetStatus(i, AliTRDCalSuperModuleStatus::kInstalled); return obj; } AliTRDCalChamberStatus* CreateChamberStatusObject() { AliTRDCalChamberStatus* obj = new AliTRDCalChamberStatus("chamberstatus", "chamberstatus"); for (Int_t i=0; i<AliTRDgeometry::kNdet; ++i) obj->SetStatus(i, AliTRDCalChamberStatus::kInstalled); return obj; } AliTRDCalMCMStatus* CreateMCMStatusObject() { AliTRDCalMCMStatus* obj = new AliTRDCalMCMStatus("mcmstatus", "mcmstatus"); return obj; } AliTRDCalPadStatus* CreatePadStatusObject() { AliTRDCalPadStatus* obj = new AliTRDCalPadStatus("padstatus", "padstatus"); return obj; } AliTRDCalPIDLQ* CreatePIDLQObject() { AliTRDCalPIDLQ* pid = new AliTRDCalPIDLQ("pidobject", "pidobject"); pid->ReadData("$ALICE_ROOT/TRD/TRDdEdxHistogramsV1.root"); pid->SetMeanChargeRatio(1.0); // The factor is the ratio of Mean of pi charge dist. // for the New TRD code divided by the Mean of pi charge // dist. given in AliTRDCalPIDLQ object return pid; } AliTRDCalMonitoring* CreateMonitoringObject() { AliTRDCalMonitoring* obj = new AliTRDCalMonitoring(); return obj; } AliCDBMetaData* CreateMetaObject(const char* objectClassName) { AliCDBMetaData *md1= new AliCDBMetaData(); md1->SetObjectClassName(objectClassName); md1->SetResponsible("Jan Fiete Grosse-Oetringhaus"); md1->SetBeamPeriod(1); md1->SetAliRootVersion("05-06-00"); //root version md1->SetComment("The dummy values in this calibration file are for testing only"); return md1; } void StoreObject(const char* cdbPath, TObject* object, AliCDBMetaData* metaData) { AliCDBId id1(cdbPath, gkDummyRun, gkDummyRun); gStorLoc->Put(object, id1, metaData); } void AliTRDCreateDummyCDB() { cout << endl << "TRD :: Creating dummy CDB with event number " << gkDummyRun << endl; AliCDBManager *man = AliCDBManager::Instance(); gStorLoc = man->GetStorage("local://$ALICE_ROOT"); if (!gStorLoc) return; TObject* obj = 0; AliCDBMetaData* metaData = 0; metaData = CreateMetaObject("AliTRDCalPad"); obj = CreatePadObject("LocalVdrift","TRD drift velocities (local variations)", 1); StoreObject("TRD/Calib/LocalVdrift", obj, metaData); obj = CreatePadObject("LocalT0","T0 (local variations)", 1); StoreObject("TRD/Calib/LocalT0", obj, metaData); obj = CreatePadObject("GainFactor","GainFactor (local variations)", 1); StoreObject("TRD/Calib/LocalGainFactor", obj, metaData); obj = CreatePRFWidthObject(); StoreObject("TRD/Calib/PRFWidth", obj, metaData); metaData = CreateMetaObject("AliTRDCalDet"); obj = CreateDetObject("ChamberVdrift","TRD drift velocities (detector value)", 1.5); StoreObject("TRD/Calib/ChamberVdrift", obj, metaData); obj = CreateDetObject("ChamberT0","T0 (detector value)", 0); StoreObject("TRD/Calib/ChamberT0", obj, metaData); obj = CreateDetObject("ChamberGainFactor","GainFactor (detector value)", 1); StoreObject("TRD/Calib/ChamberGainFactor", obj, metaData); metaData = CreateMetaObject("AliTRDCalGlobals"); obj = CreateGlobalsObject(); StoreObject("TRD/Calib/Globals", obj, metaData); metaData = CreateMetaObject("AliTRDCalChamberPos"); obj = CreateChamberObject(); StoreObject("TRD/Calib/ChamberPos", obj, metaData); metaData = CreateMetaObject("AliTRDCalStackPos"); obj = CreateStackObject(); StoreObject("TRD/Calib/StackPos", obj, metaData); metaData = CreateMetaObject("AliTRDCalSuperModulePos"); obj = CreateSuperModuleObject(); StoreObject("TRD/Calib/SuperModulePos", obj, metaData); metaData = CreateMetaObject("AliTRDCalSuperModuleStatus"); obj = CreateSuperModuleStatusObject(); StoreObject("TRD/Calib/SuperModuleStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalChamberStatus"); obj = CreateChamberStatusObject(); StoreObject("TRD/Calib/ChamberStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalMCMStatus"); obj = CreateMCMStatusObject(); StoreObject("TRD/Calib/MCMStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalPadStatus"); obj = CreatePadStatusObject(); StoreObject("TRD/Calib/PadStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalPIDLQ"); obj = CreatePIDLQObject(); StoreObject("TRD/Calib/PIDLQ", obj, metaData); metaData = CreateMetaObject("AliTRDCalMonitoring"); obj = CreateMonitoringObject(); StoreObject("TRD/Calib/MonitoringData", obj, metaData); } <commit_msg>Remove the Pos objects<commit_after>#if !defined( __CINT__) || defined(__MAKECINT__) #include <iostream> #include <AliCDBManager.h> #include <AliCDBStorage.h> #include <AliCDBEntry.h> #include <AliCDBMetaData.h> #include "AliTRDgeometry.h" #include "AliTRDCalROC.h" #include "AliTRDCalPad.h" #include "AliTRDCalDet.h" #include "AliTRDCalGlobals.h" #include "AliTRDCalSuperModuleStatus.h" #include "AliTRDCalChamberStatus.h" #include "AliTRDCalMCMStatus.h" #include "AliTRDCalPadStatus.h" #include "AliTRDCalSingleChamberStatus.h" #include "AliTRDCalPIDLQ.h" #include "AliTRDCalMonitoring.h" #endif // run number for the dummy file const Int_t gkDummyRun = 0; AliCDBStorage* gStorLoc = 0; TObject* CreatePadObject(const char* shortName, const char* description, Float_t value) { AliTRDCalPad *calPad = new AliTRDCalPad(shortName, description); for (Int_t det=0; det<AliTRDgeometry::kNdet; ++det) { AliTRDCalROC *calROC = calPad->GetCalROC(det); for (Int_t channel=0; channel<calROC->GetNchannels(); ++channel) calROC->SetValue(channel, value); } return calPad; } TObject* CreateDetObject(const char* shortName, const char* description, Float_t value) { AliTRDCalDet *object = new AliTRDCalDet(shortName, description); for (Int_t det=0; det<AliTRDgeometry::kNdet; ++det) object->SetValue(det, value); return object; } TObject* CreateGlobalsObject() { AliTRDCalGlobals *object = new AliTRDCalGlobals("Globals", "Global TRD calibration parameters"); object->SetSamplingFrequency(10.0); object->SetNumberOfTimeBins(22); return object; } TObject* CreatePRFWidthObject() { AliTRDCalPad *calPad = new AliTRDCalPad("PRFWidth","PRFWidth"); for (Int_t plane=0; plane<AliTRDgeometry::kNplan; ++plane) { Float_t value = 0; switch (plane) { case 0: value = 0.515; break; case 1: value = 0.502; break; case 2: value = 0.491; break; case 3: value = 0.481; break; case 4: value = 0.471; break; case 5: value = 0.463; break; default: cout << "CreatePRFWidthObject: UNEXPECTED" << endl; return 0; } for (Int_t chamber=0; chamber<AliTRDgeometry::kNcham; ++chamber) { for (Int_t sector=0; sector<AliTRDgeometry::kNsect; ++sector) { AliTRDCalROC *calROC = calPad->GetCalROC(plane, chamber, sector); for (Int_t channel=0; channel<calROC->GetNchannels(); ++channel) calROC->SetValue(channel, value); } } } return calPad; } AliTRDCalSuperModuleStatus* CreateSuperModuleStatusObject() { AliTRDCalSuperModuleStatus* obj = new AliTRDCalSuperModuleStatus("supermodulestatus", "supermodulestatus"); for (Int_t i=0; i<AliTRDgeometry::kNsect; ++i) obj->SetStatus(i, AliTRDCalSuperModuleStatus::kInstalled); return obj; } AliTRDCalChamberStatus* CreateChamberStatusObject() { AliTRDCalChamberStatus* obj = new AliTRDCalChamberStatus("chamberstatus", "chamberstatus"); for (Int_t i=0; i<AliTRDgeometry::kNdet; ++i) obj->SetStatus(i, AliTRDCalChamberStatus::kInstalled); return obj; } AliTRDCalMCMStatus* CreateMCMStatusObject() { AliTRDCalMCMStatus* obj = new AliTRDCalMCMStatus("mcmstatus", "mcmstatus"); return obj; } AliTRDCalPadStatus* CreatePadStatusObject() { AliTRDCalPadStatus* obj = new AliTRDCalPadStatus("padstatus", "padstatus"); return obj; } AliTRDCalPIDLQ* CreatePIDLQObject() { AliTRDCalPIDLQ* pid = new AliTRDCalPIDLQ("pidobject", "pidobject"); pid->ReadData("$ALICE_ROOT/TRD/TRDdEdxHistogramsV1.root"); pid->SetMeanChargeRatio(1.0); // The factor is the ratio of Mean of pi charge dist. // for the New TRD code divided by the Mean of pi charge // dist. given in AliTRDCalPIDLQ object return pid; } AliTRDCalMonitoring* CreateMonitoringObject() { AliTRDCalMonitoring* obj = new AliTRDCalMonitoring(); return obj; } AliCDBMetaData* CreateMetaObject(const char* objectClassName) { AliCDBMetaData *md1= new AliCDBMetaData(); md1->SetObjectClassName(objectClassName); md1->SetResponsible("Jan Fiete Grosse-Oetringhaus"); md1->SetBeamPeriod(1); md1->SetAliRootVersion("05-06-00"); //root version md1->SetComment("The dummy values in this calibration file are for testing only"); return md1; } void StoreObject(const char* cdbPath, TObject* object, AliCDBMetaData* metaData) { AliCDBId id1(cdbPath, gkDummyRun, gkDummyRun); gStorLoc->Put(object, id1, metaData); } void AliTRDCreateDummyCDB() { cout << endl << "TRD :: Creating dummy CDB with event number " << gkDummyRun << endl; AliCDBManager *man = AliCDBManager::Instance(); gStorLoc = man->GetStorage("local://$ALICE_ROOT"); if (!gStorLoc) return; TObject* obj = 0; AliCDBMetaData* metaData = 0; metaData = CreateMetaObject("AliTRDCalPad"); obj = CreatePadObject("LocalVdrift","TRD drift velocities (local variations)", 1); StoreObject("TRD/Calib/LocalVdrift", obj, metaData); obj = CreatePadObject("LocalT0","T0 (local variations)", 1); StoreObject("TRD/Calib/LocalT0", obj, metaData); obj = CreatePadObject("GainFactor","GainFactor (local variations)", 1); StoreObject("TRD/Calib/LocalGainFactor", obj, metaData); obj = CreatePRFWidthObject(); StoreObject("TRD/Calib/PRFWidth", obj, metaData); metaData = CreateMetaObject("AliTRDCalDet"); obj = CreateDetObject("ChamberVdrift","TRD drift velocities (detector value)", 1.5); StoreObject("TRD/Calib/ChamberVdrift", obj, metaData); obj = CreateDetObject("ChamberT0","T0 (detector value)", 0); StoreObject("TRD/Calib/ChamberT0", obj, metaData); obj = CreateDetObject("ChamberGainFactor","GainFactor (detector value)", 1); StoreObject("TRD/Calib/ChamberGainFactor", obj, metaData); metaData = CreateMetaObject("AliTRDCalGlobals"); obj = CreateGlobalsObject(); StoreObject("TRD/Calib/Globals", obj, metaData); metaData = CreateMetaObject("AliTRDCalSuperModuleStatus"); obj = CreateSuperModuleStatusObject(); StoreObject("TRD/Calib/SuperModuleStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalChamberStatus"); obj = CreateChamberStatusObject(); StoreObject("TRD/Calib/ChamberStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalMCMStatus"); obj = CreateMCMStatusObject(); StoreObject("TRD/Calib/MCMStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalPadStatus"); obj = CreatePadStatusObject(); StoreObject("TRD/Calib/PadStatus", obj, metaData); metaData = CreateMetaObject("AliTRDCalPIDLQ"); obj = CreatePIDLQObject(); StoreObject("TRD/Calib/PIDLQ", obj, metaData); metaData = CreateMetaObject("AliTRDCalMonitoring"); obj = CreateMonitoringObject(); StoreObject("TRD/Calib/MonitoringData", obj, metaData); } <|endoftext|>
<commit_before>//===--- DebugTypeInfo.cpp - Type Info for Debugging ----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the data structure that holds all the debug info // we want to emit for types. // //===----------------------------------------------------------------------===// #include "DebugTypeInfo.h" #include "FixedTypeInfo.h" #include "swift/SIL/SILGlobalVariable.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace swift; using namespace irgen; DebugTypeInfo::DebugTypeInfo(DeclContext *DC, GenericEnvironment *GE, swift::Type Ty, llvm::Type *StorageTy, Size size, Alignment align, bool HasDefaultAlignment) : DeclCtx(DC), GenericEnv(GE), Type(Ty.getPointer()), StorageType(StorageTy), size(size), align(align), DefaultAlignment(HasDefaultAlignment) { assert(StorageType && "StorageType is a nullptr"); assert(align.getValue() != 0); } /// Determine whether this type has a custom @_alignment attribute. static bool hasDefaultAlignment(swift::Type Ty) { if (auto CanTy = Ty->getCanonicalType()) if (auto *TyDecl = CanTy.getNominalOrBoundGenericNominal()) if (TyDecl->getAttrs().getAttribute<AlignmentAttr>()) return false; return true; } DebugTypeInfo DebugTypeInfo::getFromTypeInfo(DeclContext *DC, GenericEnvironment *GE, swift::Type Ty, const TypeInfo &Info) { Size size; if (Info.isFixedSize()) { const FixedTypeInfo &FixTy = *cast<const FixedTypeInfo>(&Info); size = FixTy.getFixedSize(); } else { // FIXME: Handle NonFixedTypeInfo here or assert that we won't // encounter one. size = Size(0); } return DebugTypeInfo(DC, GE, Ty.getPointer(), Info.getStorageType(), size, Info.getBestKnownAlignment(), hasDefaultAlignment(Ty)); } DebugTypeInfo DebugTypeInfo::getLocalVariable(DeclContext *DC, GenericEnvironment *GE, VarDecl *Decl, swift::Type Ty, const TypeInfo &Info, bool Unwrap) { auto DeclType = (Decl->hasType() ? Decl->getType() : Decl->getDeclContext()->mapTypeIntoContext( Decl->getInterfaceType())); auto RealType = Ty; if (Unwrap) { DeclType = DeclType->getInOutObjectType(); RealType = RealType->getInOutObjectType(); } // DynamicSelfType is also sugar as far as debug info is concerned. auto DeclSelfType = DeclType; if (auto DynSelfTy = DeclType->getAs<DynamicSelfType>()) DeclSelfType = DynSelfTy->getSelfType(); // Prefer the original, potentially sugared version of the type if // the type hasn't been mucked with by an optimization pass. auto *Type = DeclSelfType->isEqual(RealType) ? DeclType.getPointer() : RealType.getPointer(); return getFromTypeInfo(DC, GE, Type, Info); } DebugTypeInfo DebugTypeInfo::getMetadata(swift::Type Ty, llvm::Type *StorageTy, Size size, Alignment align) { DebugTypeInfo DbgTy(nullptr, nullptr, Ty.getPointer(), StorageTy, size, align, true); assert(!DbgTy.isArchetype() && "type metadata cannot contain an archetype"); return DbgTy; } DebugTypeInfo DebugTypeInfo::getGlobal(SILGlobalVariable *GV, llvm::Type *StorageTy, Size size, Alignment align) { // Prefer the original, potentially sugared version of the type if // the type hasn't been mucked with by an optimization pass. DeclContext *DC = nullptr; GenericEnvironment *GE = nullptr; auto LowTy = GV->getLoweredType().getSwiftRValueType(); auto *Type = LowTy.getPointer(); if (auto *Decl = GV->getDecl()) { DC = Decl->getDeclContext(); GE = DC->getGenericEnvironmentOfContext(); auto DeclType = (Decl->hasType() ? Decl->getType() : DC->mapTypeIntoContext(Decl->getInterfaceType())); if (DeclType->isEqual(LowTy)) Type = DeclType.getPointer(); } DebugTypeInfo DbgTy(DC, GE, Type, StorageTy, size, align, hasDefaultAlignment(Type)); assert(StorageTy && "StorageType is a nullptr"); assert(!DbgTy.isArchetype() && "type of a global var cannot contain an archetype"); assert(align.getValue() != 0); return DbgTy; } DebugTypeInfo DebugTypeInfo::getObjCClass(ClassDecl *theClass, llvm::Type *StorageType, Size size, Alignment align) { DebugTypeInfo DbgTy(nullptr, nullptr, theClass->getInterfaceType().getPointer(), StorageType, size, align, true); assert(!DbgTy.isArchetype() && "type of an objc class cannot contain an archetype"); return DbgTy; } bool DebugTypeInfo::operator==(DebugTypeInfo T) const { return (getType() == T.getType() && size == T.size && align == T.align); } bool DebugTypeInfo::operator!=(DebugTypeInfo T) const { return !operator==(T); } TypeDecl *DebugTypeInfo::getDecl() const { if (auto *N = dyn_cast<NominalType>(Type)) return N->getDecl(); if (auto *TA = dyn_cast<NameAliasType>(Type)) return TA->getDecl(); if (auto *UBG = dyn_cast<UnboundGenericType>(Type)) return UBG->getDecl(); if (auto *BG = dyn_cast<BoundGenericType>(Type)) return BG->getDecl(); return nullptr; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void DebugTypeInfo::dump() const { llvm::errs() << "[Size " << size.getValue() << " Alignment " << align.getValue() << "] "; getType()->dump(); if (StorageType) { llvm::errs() << "StorageType="; StorageType->dump(); } } #endif <commit_msg>Rename local variable (NFC)<commit_after>//===--- DebugTypeInfo.cpp - Type Info for Debugging ----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the data structure that holds all the debug info // we want to emit for types. // //===----------------------------------------------------------------------===// #include "DebugTypeInfo.h" #include "FixedTypeInfo.h" #include "swift/SIL/SILGlobalVariable.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace swift; using namespace irgen; DebugTypeInfo::DebugTypeInfo(DeclContext *DC, GenericEnvironment *GE, swift::Type Ty, llvm::Type *StorageTy, Size size, Alignment align, bool HasDefaultAlignment) : DeclCtx(DC), GenericEnv(GE), Type(Ty.getPointer()), StorageType(StorageTy), size(size), align(align), DefaultAlignment(HasDefaultAlignment) { assert(StorageType && "StorageType is a nullptr"); assert(align.getValue() != 0); } /// Determine whether this type has a custom @_alignment attribute. static bool hasDefaultAlignment(swift::Type Ty) { if (auto CanTy = Ty->getCanonicalType()) if (auto *TyDecl = CanTy.getNominalOrBoundGenericNominal()) if (TyDecl->getAttrs().getAttribute<AlignmentAttr>()) return false; return true; } DebugTypeInfo DebugTypeInfo::getFromTypeInfo(DeclContext *DC, GenericEnvironment *GE, swift::Type Ty, const TypeInfo &Info) { Size size; if (Info.isFixedSize()) { const FixedTypeInfo &FixTy = *cast<const FixedTypeInfo>(&Info); size = FixTy.getFixedSize(); } else { // FIXME: Handle NonFixedTypeInfo here or assert that we won't // encounter one. size = Size(0); } return DebugTypeInfo(DC, GE, Ty.getPointer(), Info.getStorageType(), size, Info.getBestKnownAlignment(), hasDefaultAlignment(Ty)); } DebugTypeInfo DebugTypeInfo::getLocalVariable(DeclContext *DC, GenericEnvironment *GE, VarDecl *Decl, swift::Type Ty, const TypeInfo &Info, bool Unwrap) { auto DeclType = (Decl->hasType() ? Decl->getType() : Decl->getDeclContext()->mapTypeIntoContext( Decl->getInterfaceType())); auto RealType = Ty; if (Unwrap) { DeclType = DeclType->getInOutObjectType(); RealType = RealType->getInOutObjectType(); } // DynamicSelfType is also sugar as far as debug info is concerned. auto Sugared = DeclType; if (auto DynSelfTy = DeclType->getAs<DynamicSelfType>()) Sugared = DynSelfTy->getSelfType(); // Prefer the original, potentially sugared version of the type if // the type hasn't been mucked with by an optimization pass. auto *Type = Sugared->isEqual(RealType) ? DeclType.getPointer() : RealType.getPointer(); return getFromTypeInfo(DC, GE, Type, Info); } DebugTypeInfo DebugTypeInfo::getMetadata(swift::Type Ty, llvm::Type *StorageTy, Size size, Alignment align) { DebugTypeInfo DbgTy(nullptr, nullptr, Ty.getPointer(), StorageTy, size, align, true); assert(!DbgTy.isArchetype() && "type metadata cannot contain an archetype"); return DbgTy; } DebugTypeInfo DebugTypeInfo::getGlobal(SILGlobalVariable *GV, llvm::Type *StorageTy, Size size, Alignment align) { // Prefer the original, potentially sugared version of the type if // the type hasn't been mucked with by an optimization pass. DeclContext *DC = nullptr; GenericEnvironment *GE = nullptr; auto LowTy = GV->getLoweredType().getSwiftRValueType(); auto *Type = LowTy.getPointer(); if (auto *Decl = GV->getDecl()) { DC = Decl->getDeclContext(); GE = DC->getGenericEnvironmentOfContext(); auto DeclType = (Decl->hasType() ? Decl->getType() : DC->mapTypeIntoContext(Decl->getInterfaceType())); if (DeclType->isEqual(LowTy)) Type = DeclType.getPointer(); } DebugTypeInfo DbgTy(DC, GE, Type, StorageTy, size, align, hasDefaultAlignment(Type)); assert(StorageTy && "StorageType is a nullptr"); assert(!DbgTy.isArchetype() && "type of a global var cannot contain an archetype"); assert(align.getValue() != 0); return DbgTy; } DebugTypeInfo DebugTypeInfo::getObjCClass(ClassDecl *theClass, llvm::Type *StorageType, Size size, Alignment align) { DebugTypeInfo DbgTy(nullptr, nullptr, theClass->getInterfaceType().getPointer(), StorageType, size, align, true); assert(!DbgTy.isArchetype() && "type of an objc class cannot contain an archetype"); return DbgTy; } bool DebugTypeInfo::operator==(DebugTypeInfo T) const { return (getType() == T.getType() && size == T.size && align == T.align); } bool DebugTypeInfo::operator!=(DebugTypeInfo T) const { return !operator==(T); } TypeDecl *DebugTypeInfo::getDecl() const { if (auto *N = dyn_cast<NominalType>(Type)) return N->getDecl(); if (auto *TA = dyn_cast<NameAliasType>(Type)) return TA->getDecl(); if (auto *UBG = dyn_cast<UnboundGenericType>(Type)) return UBG->getDecl(); if (auto *BG = dyn_cast<BoundGenericType>(Type)) return BG->getDecl(); return nullptr; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void DebugTypeInfo::dump() const { llvm::errs() << "[Size " << size.getValue() << " Alignment " << align.getValue() << "] "; getType()->dump(); if (StorageType) { llvm::errs() << "StorageType="; StorageType->dump(); } } #endif <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2005-2008 by the FIFE team * * http://www.fifengine.de * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes // 3rd party library includes // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "vfs/raw/rawdata.h" #include "vfs/raw/rawdatafile.h" #include "util/log/logger.h" #include "util/base/exception.h" #include "fife_boost_filesystem.h" #include "vfsdirectory.h" namespace FIFE { static Logger _log(LM_VFS); VFSDirectory::VFSDirectory(VFS* vfs, const std::string& root) : VFSSource(vfs), m_root(root) { FL_DBG(_log, LMsg("VFSDirectory created with root path ") << m_root); if(!m_root.empty() && *(m_root.end() - 1) != '/') m_root.append(1,'/'); } VFSDirectory::~VFSDirectory() { } bool VFSDirectory::fileExists(const std::string& name) const { std::string fullFilename = m_root + name; bfs::path fullPath(fullFilename); std::ifstream file(fullPath.file_string().c_str()); if (file) return true; return false; } RawData* VFSDirectory::open(const std::string& file) const { return new RawData(new RawDataFile(m_root + file)); } std::set<std::string> VFSDirectory::listFiles(const std::string& path) const { return list(path, false); } std::set<std::string> VFSDirectory::listDirectories(const std::string& path) const { return list(path, true); } std::set<std::string> VFSDirectory::list(const std::string& path, bool directorys) const { std::set<std::string> list; std::string dir = m_root; // Avoid double slashes if(path[0] == '/' && m_root[m_root.size()-1] == '/') { dir.append(path.substr(1)); } else { dir.append(path); } try { bfs::path boost_path(dir); if (!bfs::exists(boost_path) || !bfs::is_directory(boost_path)) return list; bfs::directory_iterator end; for (bfs::directory_iterator i(boost_path); i != end; ++i) { if (bfs::is_directory(*i) != directorys) continue; std::string filename = GetFilenameFromDirectoryIterator(i); if (!filename.empty()) { list.insert(filename); } } } catch (const bfs::filesystem_error& ex) { throw Exception(ex.what()); } return list; } } <commit_msg>Fixed a small bug when compiling on linux when using boost 1.64.1-3. [t:545]<commit_after>/*************************************************************************** * Copyright (C) 2005-2008 by the FIFE team * * http://www.fifengine.de * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes // 3rd party library includes // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "vfs/raw/rawdata.h" #include "vfs/raw/rawdatafile.h" #include "util/log/logger.h" #include "util/base/exception.h" #include "fife_boost_filesystem.h" #include "vfsdirectory.h" namespace FIFE { static Logger _log(LM_VFS); VFSDirectory::VFSDirectory(VFS* vfs, const std::string& root) : VFSSource(vfs), m_root(root) { FL_DBG(_log, LMsg("VFSDirectory created with root path ") << m_root); if(!m_root.empty() && *(m_root.end() - 1) != '/') m_root.append(1,'/'); } VFSDirectory::~VFSDirectory() { } bool VFSDirectory::fileExists(const std::string& name) const { std::string fullFilename = m_root + name; bfs::path fullPath(fullFilename); std::ifstream file(fullPath.string().c_str()); if (file) return true; return false; } RawData* VFSDirectory::open(const std::string& file) const { return new RawData(new RawDataFile(m_root + file)); } std::set<std::string> VFSDirectory::listFiles(const std::string& path) const { return list(path, false); } std::set<std::string> VFSDirectory::listDirectories(const std::string& path) const { return list(path, true); } std::set<std::string> VFSDirectory::list(const std::string& path, bool directorys) const { std::set<std::string> list; std::string dir = m_root; // Avoid double slashes if(path[0] == '/' && m_root[m_root.size()-1] == '/') { dir.append(path.substr(1)); } else { dir.append(path); } try { bfs::path boost_path(dir); if (!bfs::exists(boost_path) || !bfs::is_directory(boost_path)) return list; bfs::directory_iterator end; for (bfs::directory_iterator i(boost_path); i != end; ++i) { if (bfs::is_directory(*i) != directorys) continue; std::string filename = GetFilenameFromDirectoryIterator(i); if (!filename.empty()) { list.insert(filename); } } } catch (const bfs::filesystem_error& ex) { throw Exception(ex.what()); } return list; } } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2013, MAPIR group, University of Malaga | | Copyright (c) 2012-2013, University of Almeria | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are | | met: | | * Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | * Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | * Neither the name of the copyright holders nor the | | names of its contributors may be used to endorse or promote products | | derived from this software without specific prior written permission.| | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR| | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 <mrpt/hwdrivers.h> // Precompiled headers #include <mrpt/hwdrivers/CRaePID.h> #include <iostream> #include <sstream> using namespace mrpt::utils; using namespace mrpt::hwdrivers; IMPLEMENTS_GENERIC_SENSOR(CRaePID,mrpt::hwdrivers) /* ----------------------------------------------------- Constructor ----------------------------------------------------- */ CRaePID::CRaePID() { m_sensorLabel = "RAE_PID"; } /* ----------------------------------------------------- loadConfig_sensorSpecific ----------------------------------------------------- */ void CRaePID::loadConfig_sensorSpecific( const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ) { #ifdef MRPT_OS_WINDOWS com_port = configSource.read_string(iniSection, "COM_port_PID", "COM1", true ) ; #else com_port = configSource.read_string(iniSection, "COM_port_PID", "/dev/tty0", true ); #endif com_bauds = configSource.read_int( iniSection, "baudRate",9600, false ); pose_x = configSource.read_float(iniSection,"pose_x",0,true); pose_y = configSource.read_float(iniSection,"pose_y",0,true); pose_z = configSource.read_float(iniSection,"pose_z",0,true); pose_roll = configSource.read_float(iniSection,"pose_roll",0,true); pose_pitch = configSource.read_float(iniSection,"pose_pitch",0,true); pose_yaw = configSource.read_float(iniSection,"pose_yaw",0,true); } /* ----------------------------------------------------- tryToOpenTheCOM ----------------------------------------------------- */ bool CRaePID::tryToOpenTheCOM() { if (COM.isOpen()) return true; // Already open if (m_verbose) cout << "[CRaePID] Opening " << com_port << " @ " <<com_bauds << endl; try { COM.open(com_port); // Config: COM.setConfig( com_bauds, 0, 8, 1 ); //COM.setTimeouts( 1, 0, 1, 1, 1 ); COM.setTimeouts(50,1,100, 1,20); //mrpt::system::sleep(10); COM.purgeBuffers(); //mrpt::system::sleep(10); return true; // All OK! } catch (std::exception &e) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port:" << std::endl << e.what(); COM.close(); return false; } catch (...) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port." << std::endl; COM.close(); return false; } } /* ----------------------------------------------------- doProcess ----------------------------------------------------- */ void CRaePID::doProcess() { // Is the COM open? if (!tryToOpenTheCOM()) { m_state = ssError; THROW_EXCEPTION("Cannot open the serial port"); } // Send command to PID to request a measurement COM.purgeBuffers(); COM.Write("R",1); // Read PID response std::string power_reading; bool time_out = false; power_reading = COM.ReadString(500,&time_out); if (time_out) power_reading = "Time_out"; cout << "[CRaePID] " << com_port << " @ " <<com_bauds << " - measurement -> " << power_reading << endl; // Convert the text to a number (ppm) const float readnum = atof(power_reading.c_str()); const float val_ppm = readnum/1000; // Fill the observation mrpt::slam::CObservationGasSensors::TObservationENose obs; obs.readingsVoltage.push_back(val_ppm); obs.sensorTypes.push_back(0xFFFF); CObservationGasSensors obsG; obsG.sensorLabel = this->getSensorLabel(); obsG.m_readings.push_back(obs); obsG.timestamp = now(); appendObservation(CObservationGasSensorsPtr(new CObservationGasSensors(obsG))); } std::string CRaePID::getFirmware() { // Send the command cout << "Firmware version: " << endl; COM.purgeBuffers(); size_t B_written = COM.Write("F",1); // Read the returned text bool time_out = false; std::string s_read = COM.ReadString(2000,&time_out); if (time_out) s_read = "Time_out"; return s_read; } std::string CRaePID::getModel() { // Send the command COM.purgeBuffers(); COM.Write("M",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getSerialNumber() { // Send the command COM.purgeBuffers(); COM.Write("S",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getName() { // Send the command COM.purgeBuffers(); COM.Write("N",1); // Read the returned text return COM.ReadString(); } bool CRaePID::switchPower() { // Send the command COM.purgeBuffers(); COM.Write("P",1); // Read the returned text std::string reading; reading = COM.ReadString(); if (strcmp(reading.c_str(),"Sleep...")==0) return true; else return false; } CObservationGasSensors CRaePID::getFullInfo() { // Send the command COM.purgeBuffers(); COM.Write("C",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Iterate over each information component (tokenize first) // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> measurements_text(it, endit); // Convert the text to a number (ppm) mrpt::slam::CObservationGasSensors::TObservationENose obs; CObservationGasSensors obsG; for (size_t k=0; k < measurements_text.size(); k++) { const float readnum = atof(measurements_text[k].c_str()); const float val_ppm = readnum/1000.f; // Fill the observation obs.readingsVoltage.push_back(val_ppm); obsG.m_readings.push_back(obs); } obsG.sensorLabel = this->getSensorLabel(); obsG.timestamp = now(); return obsG; } bool CRaePID::errorStatus(std::string &errorString) { // Send the command COM.purgeBuffers(); COM.Write("E",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> errors_text(it, endit); // Take the first part and check the possible error condition if((strcmp(errors_text[0].c_str(),"0")==0) && (strcmp(errors_text[1].c_str(),"0")==0)) // no error { return false; } else { // By the moment, return the raw error; note that if necessary a detailed description of the error can be obtained analyzing the two error strings separately errorString = reading; return true; } } void CRaePID::getLimits(float &min, float &max) { // Send the command COM.purgeBuffers(); COM.Write("L",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> readings_text(it, endit); // read min and max max = atof(readings_text[0].c_str()); min = atof(readings_text[1].c_str()); } <commit_msg>Avoid saving observation if TimeOut is detected. It may happen on first time gathering information from PID or it not turned-on properly.<commit_after>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2013, MAPIR group, University of Malaga | | Copyright (c) 2012-2013, University of Almeria | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are | | met: | | * Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | * Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | * Neither the name of the copyright holders nor the | | names of its contributors may be used to endorse or promote products | | derived from this software without specific prior written permission.| | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR| | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 <mrpt/hwdrivers.h> // Precompiled headers #include <mrpt/hwdrivers/CRaePID.h> #include <iostream> #include <sstream> using namespace mrpt::utils; using namespace mrpt::hwdrivers; IMPLEMENTS_GENERIC_SENSOR(CRaePID,mrpt::hwdrivers) /* ----------------------------------------------------- Constructor ----------------------------------------------------- */ CRaePID::CRaePID() { m_sensorLabel = "RAE_PID"; } /* ----------------------------------------------------- loadConfig_sensorSpecific ----------------------------------------------------- */ void CRaePID::loadConfig_sensorSpecific( const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ) { #ifdef MRPT_OS_WINDOWS com_port = configSource.read_string(iniSection, "COM_port_PID", "COM1", true ) ; #else com_port = configSource.read_string(iniSection, "COM_port_PID", "/dev/tty0", true ); #endif com_bauds = configSource.read_int( iniSection, "baudRate",9600, false ); pose_x = configSource.read_float(iniSection,"pose_x",0,true); pose_y = configSource.read_float(iniSection,"pose_y",0,true); pose_z = configSource.read_float(iniSection,"pose_z",0,true); pose_roll = configSource.read_float(iniSection,"pose_roll",0,true); pose_pitch = configSource.read_float(iniSection,"pose_pitch",0,true); pose_yaw = configSource.read_float(iniSection,"pose_yaw",0,true); } /* ----------------------------------------------------- tryToOpenTheCOM ----------------------------------------------------- */ bool CRaePID::tryToOpenTheCOM() { if (COM.isOpen()) return true; // Already open if (m_verbose) cout << "[CRaePID] Opening " << com_port << " @ " <<com_bauds << endl; try { COM.open(com_port); // Config: COM.setConfig( com_bauds, 0, 8, 1 ); //COM.setTimeouts( 1, 0, 1, 1, 1 ); COM.setTimeouts(50,1,100, 1,20); //mrpt::system::sleep(10); COM.purgeBuffers(); //mrpt::system::sleep(10); return true; // All OK! } catch (std::exception &e) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port:" << std::endl << e.what(); COM.close(); return false; } catch (...) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port." << std::endl; COM.close(); return false; } } /* ----------------------------------------------------- doProcess ----------------------------------------------------- */ void CRaePID::doProcess() { // Is the COM open? if (!tryToOpenTheCOM()) { m_state = ssError; THROW_EXCEPTION("Cannot open the serial port"); } bool have_reading = false; std::string power_reading; bool time_out = false; while (!have_reading) { // Send command to PID to request a measurement COM.purgeBuffers(); COM.Write("R",1); // Read PID response power_reading = COM.ReadString(500,&time_out); if (time_out) { cout << "[CRaePID] " << com_port << " @ " <<com_bauds << " - measurement Timed-Out" << endl; sleep(10); } else have_reading = true; } cout << "[CRaePID] " << com_port << " @ " <<com_bauds << " - measurement -> " << power_reading << endl; // Convert the text to a number (ppm) const float readnum = atof(power_reading.c_str()); const float val_ppm = readnum/1000; // Fill the observation mrpt::slam::CObservationGasSensors::TObservationENose obs; obs.readingsVoltage.push_back(val_ppm); obs.sensorTypes.push_back(0xFFFF); CObservationGasSensors obsG; obsG.sensorLabel = this->getSensorLabel(); obsG.m_readings.push_back(obs); obsG.timestamp = now(); appendObservation(CObservationGasSensorsPtr(new CObservationGasSensors(obsG))); } std::string CRaePID::getFirmware() { // Send the command cout << "Firmware version: " << endl; COM.purgeBuffers(); size_t B_written = COM.Write("F",1); // Read the returned text bool time_out = false; std::string s_read = COM.ReadString(2000,&time_out); if (time_out) s_read = "Time_out"; return s_read; } std::string CRaePID::getModel() { // Send the command COM.purgeBuffers(); COM.Write("M",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getSerialNumber() { // Send the command COM.purgeBuffers(); COM.Write("S",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getName() { // Send the command COM.purgeBuffers(); COM.Write("N",1); // Read the returned text return COM.ReadString(); } bool CRaePID::switchPower() { // Send the command COM.purgeBuffers(); COM.Write("P",1); // Read the returned text std::string reading; reading = COM.ReadString(); if (strcmp(reading.c_str(),"Sleep...")==0) return true; else return false; } CObservationGasSensors CRaePID::getFullInfo() { // Send the command COM.purgeBuffers(); COM.Write("C",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Iterate over each information component (tokenize first) // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> measurements_text(it, endit); // Convert the text to a number (ppm) mrpt::slam::CObservationGasSensors::TObservationENose obs; CObservationGasSensors obsG; for (size_t k=0; k < measurements_text.size(); k++) { const float readnum = atof(measurements_text[k].c_str()); const float val_ppm = readnum/1000.f; // Fill the observation obs.readingsVoltage.push_back(val_ppm); obsG.m_readings.push_back(obs); } obsG.sensorLabel = this->getSensorLabel(); obsG.timestamp = now(); return obsG; } bool CRaePID::errorStatus(std::string &errorString) { // Send the command COM.purgeBuffers(); COM.Write("E",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> errors_text(it, endit); // Take the first part and check the possible error condition if((strcmp(errors_text[0].c_str(),"0")==0) && (strcmp(errors_text[1].c_str(),"0")==0)) // no error { return false; } else { // By the moment, return the raw error; note that if necessary a detailed description of the error can be obtained analyzing the two error strings separately errorString = reading; return true; } } void CRaePID::getLimits(float &min, float &max) { // Send the command COM.purgeBuffers(); COM.Write("L",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> readings_text(it, endit); // read min and max max = atof(readings_text[0].c_str()); min = atof(readings_text[1].c_str()); } <|endoftext|>
<commit_before>//===--- Immediate.cpp - the swift immediate mode -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the implementation of the swift interpreter, which takes a // source file and JITs it. // //===----------------------------------------------------------------------===// #include "swift/Immediate/Immediate.h" #include "ImmediateImpl.h" #include "swift/Subsystems.h" #include "swift/AST/ASTContext.h" #include "swift/AST/DiagnosticsFrontend.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Module.h" #include "swift/Basic/LLVM.h" #include "swift/Basic/LLVMContext.h" #include "swift/Frontend/Frontend.h" #include "swift/IRGen/IRGenPublic.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/LLJIT.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Linker/Linker.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Support/Path.h" #define DEBUG_TYPE "swift-immediate" #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #else #include <dlfcn.h> #endif using namespace swift; using namespace swift::immediate; static void *loadRuntimeLib(StringRef runtimeLibPathWithName) { #if defined(_WIN32) return LoadLibraryA(runtimeLibPathWithName.str().c_str()); #else return dlopen(runtimeLibPathWithName.str().c_str(), RTLD_LAZY | RTLD_GLOBAL); #endif } static void *loadRuntimeLibAtPath(StringRef sharedLibName, StringRef runtimeLibPath) { // FIXME: Need error-checking. llvm::SmallString<128> Path = runtimeLibPath; llvm::sys::path::append(Path, sharedLibName); return loadRuntimeLib(Path); } static void *loadRuntimeLib(StringRef sharedLibName, ArrayRef<std::string> runtimeLibPaths) { for (auto &runtimeLibPath : runtimeLibPaths) { if (void *handle = loadRuntimeLibAtPath(sharedLibName, runtimeLibPath)) return handle; } return nullptr; } void *swift::immediate::loadSwiftRuntime(ArrayRef<std::string> runtimeLibPaths) { #if defined(_WIN32) return loadRuntimeLib("swiftCore" LTDL_SHLIB_EXT, runtimeLibPaths); #else return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPaths); #endif } static bool tryLoadLibrary(LinkLibrary linkLib, SearchPathOptions searchPathOpts) { llvm::SmallString<128> path = linkLib.getName(); // If we have an absolute or relative path, just try to load it now. if (llvm::sys::path::has_parent_path(path.str())) { return loadRuntimeLib(path); } bool success = false; switch (linkLib.getKind()) { case LibraryKind::Library: { llvm::SmallString<32> stem; if (llvm::sys::path::has_extension(path.str())) { stem = std::move(path); } else { // FIXME: Try the appropriate extension for the current platform? stem = "lib"; stem += path; stem += LTDL_SHLIB_EXT; } // Try user-provided library search paths first. for (auto &libDir : searchPathOpts.LibrarySearchPaths) { path = libDir; llvm::sys::path::append(path, stem.str()); success = loadRuntimeLib(path); if (success) break; } // Let loadRuntimeLib determine the best search paths. if (!success) success = loadRuntimeLib(stem); // If that fails, try our runtime library paths. if (!success) success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPaths); break; } case LibraryKind::Framework: { // If we have a framework, mangle the name to point to the framework // binary. llvm::SmallString<64> frameworkPart{std::move(path)}; frameworkPart += ".framework"; llvm::sys::path::append(frameworkPart, linkLib.getName()); // Try user-provided framework search paths first; frameworks contain // binaries as well as modules. for (auto &frameworkDir : searchPathOpts.FrameworkSearchPaths) { path = frameworkDir.Path; llvm::sys::path::append(path, frameworkPart.str()); success = loadRuntimeLib(path); if (success) break; } // If that fails, let loadRuntimeLib search for system frameworks. if (!success) success = loadRuntimeLib(frameworkPart); break; } } return success; } bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries, SearchPathOptions SearchPathOpts, DiagnosticEngine &Diags) { SmallVector<bool, 4> LoadedLibraries; LoadedLibraries.append(LinkLibraries.size(), false); // Libraries are not sorted in the topological order of dependencies, and we // don't know the dependencies in advance. Try to load all libraries until // we stop making progress. bool HadProgress; do { HadProgress = false; for (unsigned i = 0; i != LinkLibraries.size(); ++i) { if (!LoadedLibraries[i] && tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) { LoadedLibraries[i] = true; HadProgress = true; } } } while (HadProgress); return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(), [](bool Value) { return Value; }); } static void linkerDiagnosticHandlerNoCtx(const llvm::DiagnosticInfo &DI) { if (DI.getSeverity() != llvm::DS_Error) return; std::string MsgStorage; { llvm::raw_string_ostream Stream(MsgStorage); llvm::DiagnosticPrinterRawOStream DP(Stream); DI.print(DP); } llvm::errs() << "Error linking swift modules\n"; llvm::errs() << MsgStorage << "\n"; } static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI, void *Context) { // This assert self documents our precondition that Context is always // nullptr. It seems that parts of LLVM are using the flexibility of having a // context. We don't really care about this. assert(Context == nullptr && "We assume Context is always a nullptr"); return linkerDiagnosticHandlerNoCtx(DI); } bool swift::immediate::linkLLVMModules(llvm::Module *Module, std::unique_ptr<llvm::Module> SubModule // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. /*, llvm::Linker::LinkerMode LinkerMode */) { llvm::LLVMContext &Ctx = SubModule->getContext(); auto OldHandler = Ctx.getDiagnosticHandlerCallBack(); void *OldDiagnosticContext = Ctx.getDiagnosticContext(); Ctx.setDiagnosticHandlerCallBack(linkerDiagnosticHandler, nullptr); bool Failed = llvm::Linker::linkModules(*Module, std::move(SubModule)); Ctx.setDiagnosticHandlerCallBack(OldHandler, OldDiagnosticContext); return !Failed; } bool swift::immediate::autolinkImportedModules(ModuleDecl *M, const IRGenOptions &IRGenOpts) { // Perform autolinking. SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries); auto addLinkLibrary = [&](LinkLibrary linkLib) { AllLinkLibraries.push_back(linkLib); }; M->collectLinkLibraries(addLinkLibrary); tryLoadLibraries(AllLinkLibraries, M->getASTContext().SearchPathOpts, M->getASTContext().Diags); return false; } int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine, const IRGenOptions &IRGenOpts, const SILOptions &SILOpts, std::unique_ptr<SILModule> &&SM) { ASTContext &Context = CI.getASTContext(); // IRGen the main module. auto *swiftModule = CI.getMainModule(); const auto PSPs = CI.getPrimarySpecificPathsForAtMostOnePrimary(); // FIXME: We shouldn't need to use the global context here, but // something is persisting across calls to performIRGeneration. auto ModuleCtx = std::make_unique<llvm::LLVMContext>(); auto Module = performIRGeneration( IRGenOpts, swiftModule, std::move(SM), swiftModule->getName().str(), PSPs, *ModuleCtx, ArrayRef<std::string>()); if (Context.hadError()) return -1; // Load libSwiftCore to setup process arguments. // // This must be done here, before any library loading has been done, to avoid // racing with the static initializers in user code. auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPaths); if (!stdlib) { CI.getDiags().diagnose(SourceLoc(), diag::error_immediate_mode_missing_stdlib); return -1; } // Setup interpreted process arguments. using ArgOverride = void (*)(const char **, int); #if defined(_WIN32) auto module = static_cast<HMODULE>(stdlib); auto emplaceProcessArgs = reinterpret_cast<ArgOverride>( GetProcAddress(module, "_swift_stdlib_overrideUnsafeArgvArgc")); if (emplaceProcessArgs == nullptr) return -1; #else auto emplaceProcessArgs = (ArgOverride)dlsym(stdlib, "_swift_stdlib_overrideUnsafeArgvArgc"); if (dlerror()) return -1; #endif SmallVector<const char *, 32> argBuf; for (size_t i = 0; i < CmdLine.size(); ++i) { argBuf.push_back(CmdLine[i].c_str()); } argBuf.push_back(nullptr); (*emplaceProcessArgs)(argBuf.data(), CmdLine.size()); if (autolinkImportedModules(swiftModule, IRGenOpts)) return -1; llvm::PassManagerBuilder PMBuilder; PMBuilder.OptLevel = 2; PMBuilder.Inliner = llvm::createFunctionInliningPass(200); // Build the ExecutionEngine. llvm::TargetOptions TargetOpt; std::string CPU; std::string Triple; std::vector<std::string> Features; std::tie(TargetOpt, CPU, Features, Triple) = getIRTargetOptions(IRGenOpts, swiftModule->getASTContext()); std::unique_ptr<llvm::orc::LLJIT> JIT; { auto JITOrErr = llvm::orc::LLJITBuilder() .setJITTargetMachineBuilder( llvm::orc::JITTargetMachineBuilder(llvm::Triple(Triple)) .setRelocationModel(llvm::Reloc::PIC_) .setOptions(std::move(TargetOpt)) .setCPU(std::move(CPU)) .addFeatures(Features) .setCodeGenOptLevel(llvm::CodeGenOpt::Default)) .create(); if (!JITOrErr) { llvm::logAllUnhandledErrors(JITOrErr.takeError(), llvm::errs(), ""); return -1; } else JIT = std::move(*JITOrErr); } { // Get a generator for the process symbols and attach it to the main // JITDylib. if (auto G = llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(Module->getDataLayout().getGlobalPrefix())) JIT->getMainJITDylib().addGenerator(std::move(*G)); else { logAllUnhandledErrors(G.takeError(), llvm::errs(), ""); return -1; } } LLVM_DEBUG(llvm::dbgs() << "Module to be executed:\n"; Module->dump()); { auto TSM = llvm::orc::ThreadSafeModule(std::move(Module), std::move(ModuleCtx)); if (auto Err = JIT->addIRModule(std::move(TSM))) { llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), ""); return -1; } } using MainFnTy = int(*)(int, char*[]); if (auto Err = JIT->runConstructors()) { llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), ""); return -1; } MainFnTy JITMain = nullptr; if (auto MainFnOrErr = JIT->lookup("main")) JITMain = llvm::jitTargetAddressToFunction<MainFnTy>(MainFnOrErr->getAddress()); else { logAllUnhandledErrors(MainFnOrErr.takeError(), llvm::errs(), ""); return -1; } LLVM_DEBUG(llvm::dbgs() << "Running static constructors\n"); if (auto Err = JIT->runConstructors()) { logAllUnhandledErrors(std::move(Err), llvm::errs(), ""); return -1; } LLVM_DEBUG(llvm::dbgs() << "Running main\n"); return llvm::orc::runAsMain(JITMain, CmdLine); } <commit_msg>Patch up runConstructors() change in Immediate.cpp<commit_after>//===--- Immediate.cpp - the swift immediate mode -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the implementation of the swift interpreter, which takes a // source file and JITs it. // //===----------------------------------------------------------------------===// #include "swift/Immediate/Immediate.h" #include "ImmediateImpl.h" #include "swift/Subsystems.h" #include "swift/AST/ASTContext.h" #include "swift/AST/DiagnosticsFrontend.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Module.h" #include "swift/Basic/LLVM.h" #include "swift/Basic/LLVMContext.h" #include "swift/Frontend/Frontend.h" #include "swift/IRGen/IRGenPublic.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/LLJIT.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Linker/Linker.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Support/Path.h" #define DEBUG_TYPE "swift-immediate" #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #else #include <dlfcn.h> #endif using namespace swift; using namespace swift::immediate; static void *loadRuntimeLib(StringRef runtimeLibPathWithName) { #if defined(_WIN32) return LoadLibraryA(runtimeLibPathWithName.str().c_str()); #else return dlopen(runtimeLibPathWithName.str().c_str(), RTLD_LAZY | RTLD_GLOBAL); #endif } static void *loadRuntimeLibAtPath(StringRef sharedLibName, StringRef runtimeLibPath) { // FIXME: Need error-checking. llvm::SmallString<128> Path = runtimeLibPath; llvm::sys::path::append(Path, sharedLibName); return loadRuntimeLib(Path); } static void *loadRuntimeLib(StringRef sharedLibName, ArrayRef<std::string> runtimeLibPaths) { for (auto &runtimeLibPath : runtimeLibPaths) { if (void *handle = loadRuntimeLibAtPath(sharedLibName, runtimeLibPath)) return handle; } return nullptr; } void *swift::immediate::loadSwiftRuntime(ArrayRef<std::string> runtimeLibPaths) { #if defined(_WIN32) return loadRuntimeLib("swiftCore" LTDL_SHLIB_EXT, runtimeLibPaths); #else return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPaths); #endif } static bool tryLoadLibrary(LinkLibrary linkLib, SearchPathOptions searchPathOpts) { llvm::SmallString<128> path = linkLib.getName(); // If we have an absolute or relative path, just try to load it now. if (llvm::sys::path::has_parent_path(path.str())) { return loadRuntimeLib(path); } bool success = false; switch (linkLib.getKind()) { case LibraryKind::Library: { llvm::SmallString<32> stem; if (llvm::sys::path::has_extension(path.str())) { stem = std::move(path); } else { // FIXME: Try the appropriate extension for the current platform? stem = "lib"; stem += path; stem += LTDL_SHLIB_EXT; } // Try user-provided library search paths first. for (auto &libDir : searchPathOpts.LibrarySearchPaths) { path = libDir; llvm::sys::path::append(path, stem.str()); success = loadRuntimeLib(path); if (success) break; } // Let loadRuntimeLib determine the best search paths. if (!success) success = loadRuntimeLib(stem); // If that fails, try our runtime library paths. if (!success) success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPaths); break; } case LibraryKind::Framework: { // If we have a framework, mangle the name to point to the framework // binary. llvm::SmallString<64> frameworkPart{std::move(path)}; frameworkPart += ".framework"; llvm::sys::path::append(frameworkPart, linkLib.getName()); // Try user-provided framework search paths first; frameworks contain // binaries as well as modules. for (auto &frameworkDir : searchPathOpts.FrameworkSearchPaths) { path = frameworkDir.Path; llvm::sys::path::append(path, frameworkPart.str()); success = loadRuntimeLib(path); if (success) break; } // If that fails, let loadRuntimeLib search for system frameworks. if (!success) success = loadRuntimeLib(frameworkPart); break; } } return success; } bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries, SearchPathOptions SearchPathOpts, DiagnosticEngine &Diags) { SmallVector<bool, 4> LoadedLibraries; LoadedLibraries.append(LinkLibraries.size(), false); // Libraries are not sorted in the topological order of dependencies, and we // don't know the dependencies in advance. Try to load all libraries until // we stop making progress. bool HadProgress; do { HadProgress = false; for (unsigned i = 0; i != LinkLibraries.size(); ++i) { if (!LoadedLibraries[i] && tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) { LoadedLibraries[i] = true; HadProgress = true; } } } while (HadProgress); return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(), [](bool Value) { return Value; }); } static void linkerDiagnosticHandlerNoCtx(const llvm::DiagnosticInfo &DI) { if (DI.getSeverity() != llvm::DS_Error) return; std::string MsgStorage; { llvm::raw_string_ostream Stream(MsgStorage); llvm::DiagnosticPrinterRawOStream DP(Stream); DI.print(DP); } llvm::errs() << "Error linking swift modules\n"; llvm::errs() << MsgStorage << "\n"; } static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI, void *Context) { // This assert self documents our precondition that Context is always // nullptr. It seems that parts of LLVM are using the flexibility of having a // context. We don't really care about this. assert(Context == nullptr && "We assume Context is always a nullptr"); return linkerDiagnosticHandlerNoCtx(DI); } bool swift::immediate::linkLLVMModules(llvm::Module *Module, std::unique_ptr<llvm::Module> SubModule // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. /*, llvm::Linker::LinkerMode LinkerMode */) { llvm::LLVMContext &Ctx = SubModule->getContext(); auto OldHandler = Ctx.getDiagnosticHandlerCallBack(); void *OldDiagnosticContext = Ctx.getDiagnosticContext(); Ctx.setDiagnosticHandlerCallBack(linkerDiagnosticHandler, nullptr); bool Failed = llvm::Linker::linkModules(*Module, std::move(SubModule)); Ctx.setDiagnosticHandlerCallBack(OldHandler, OldDiagnosticContext); return !Failed; } bool swift::immediate::autolinkImportedModules(ModuleDecl *M, const IRGenOptions &IRGenOpts) { // Perform autolinking. SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries); auto addLinkLibrary = [&](LinkLibrary linkLib) { AllLinkLibraries.push_back(linkLib); }; M->collectLinkLibraries(addLinkLibrary); tryLoadLibraries(AllLinkLibraries, M->getASTContext().SearchPathOpts, M->getASTContext().Diags); return false; } int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine, const IRGenOptions &IRGenOpts, const SILOptions &SILOpts, std::unique_ptr<SILModule> &&SM) { ASTContext &Context = CI.getASTContext(); // IRGen the main module. auto *swiftModule = CI.getMainModule(); const auto PSPs = CI.getPrimarySpecificPathsForAtMostOnePrimary(); // FIXME: We shouldn't need to use the global context here, but // something is persisting across calls to performIRGeneration. auto ModuleCtx = std::make_unique<llvm::LLVMContext>(); auto Module = performIRGeneration( IRGenOpts, swiftModule, std::move(SM), swiftModule->getName().str(), PSPs, *ModuleCtx, ArrayRef<std::string>()); if (Context.hadError()) return -1; // Load libSwiftCore to setup process arguments. // // This must be done here, before any library loading has been done, to avoid // racing with the static initializers in user code. auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPaths); if (!stdlib) { CI.getDiags().diagnose(SourceLoc(), diag::error_immediate_mode_missing_stdlib); return -1; } // Setup interpreted process arguments. using ArgOverride = void (*)(const char **, int); #if defined(_WIN32) auto module = static_cast<HMODULE>(stdlib); auto emplaceProcessArgs = reinterpret_cast<ArgOverride>( GetProcAddress(module, "_swift_stdlib_overrideUnsafeArgvArgc")); if (emplaceProcessArgs == nullptr) return -1; #else auto emplaceProcessArgs = (ArgOverride)dlsym(stdlib, "_swift_stdlib_overrideUnsafeArgvArgc"); if (dlerror()) return -1; #endif SmallVector<const char *, 32> argBuf; for (size_t i = 0; i < CmdLine.size(); ++i) { argBuf.push_back(CmdLine[i].c_str()); } argBuf.push_back(nullptr); (*emplaceProcessArgs)(argBuf.data(), CmdLine.size()); if (autolinkImportedModules(swiftModule, IRGenOpts)) return -1; llvm::PassManagerBuilder PMBuilder; PMBuilder.OptLevel = 2; PMBuilder.Inliner = llvm::createFunctionInliningPass(200); // Build the ExecutionEngine. llvm::TargetOptions TargetOpt; std::string CPU; std::string Triple; std::vector<std::string> Features; std::tie(TargetOpt, CPU, Features, Triple) = getIRTargetOptions(IRGenOpts, swiftModule->getASTContext()); std::unique_ptr<llvm::orc::LLJIT> JIT; { auto JITOrErr = llvm::orc::LLJITBuilder() .setJITTargetMachineBuilder( llvm::orc::JITTargetMachineBuilder(llvm::Triple(Triple)) .setRelocationModel(llvm::Reloc::PIC_) .setOptions(std::move(TargetOpt)) .setCPU(std::move(CPU)) .addFeatures(Features) .setCodeGenOptLevel(llvm::CodeGenOpt::Default)) .create(); if (!JITOrErr) { llvm::logAllUnhandledErrors(JITOrErr.takeError(), llvm::errs(), ""); return -1; } else JIT = std::move(*JITOrErr); } { // Get a generator for the process symbols and attach it to the main // JITDylib. if (auto G = llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(Module->getDataLayout().getGlobalPrefix())) JIT->getMainJITDylib().addGenerator(std::move(*G)); else { logAllUnhandledErrors(G.takeError(), llvm::errs(), ""); return -1; } } LLVM_DEBUG(llvm::dbgs() << "Module to be executed:\n"; Module->dump()); { auto TSM = llvm::orc::ThreadSafeModule(std::move(Module), std::move(ModuleCtx)); if (auto Err = JIT->addIRModule(std::move(TSM))) { llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), ""); return -1; } } using MainFnTy = int(*)(int, char*[]); if (auto Err = JIT->initialize(JIT->getMainJITDylib())) { llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), ""); return -1; } MainFnTy JITMain = nullptr; if (auto MainFnOrErr = JIT->lookup("main")) JITMain = llvm::jitTargetAddressToFunction<MainFnTy>(MainFnOrErr->getAddress()); else { logAllUnhandledErrors(MainFnOrErr.takeError(), llvm::errs(), ""); return -1; } LLVM_DEBUG(llvm::dbgs() << "Running static constructors\n"); if (auto Err = JIT->initialize(JIT->getMainJITDylib())) { logAllUnhandledErrors(std::move(Err), llvm::errs(), ""); return -1; } LLVM_DEBUG(llvm::dbgs() << "Running main\n"); return llvm::orc::runAsMain(JITMain, CmdLine); } <|endoftext|>
<commit_before>#pragma once #include "constants.hpp" #include "filesystem.hpp" #include <fcntl.h> #include <sstream> #include <string> #include <sys/file.h> class process_utility final { public: static bool lock_single_application(const std::string& pid_file_path) { auto fd = open(pid_file_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd < 0) { throw std::runtime_error("failed to create pid file"); } if (flock(fd, LOCK_EX | LOCK_NB) == 0) { get_single_application_lock_pid_file_descriptor() = fd; std::stringstream ss; ss << getpid() << std::endl; auto string = ss.str(); write(fd, string.c_str(), string.size()); return true; } return false; } static void unlock_single_application(void) { auto& fd = get_single_application_lock_pid_file_descriptor(); if (fd >= 0) { flock(fd, LOCK_UN); close(fd); fd = -1; } } static bool lock_single_application_with_user_pid_file(const std::string& pid_file_name) { auto pid_directory = constants::get_user_pid_directory(); if (pid_directory.empty()) { throw std::runtime_error("failed to get user pid directory"); } filesystem::create_directory_with_intermediate_directories(pid_directory, 0700); if (!filesystem::is_directory(pid_directory)) { throw std::runtime_error("failed to create user pid directory"); } std::string pid_file_path = pid_directory + "/" + pid_file_name; return lock_single_application(pid_file_path); } private: static int& get_single_application_lock_pid_file_descriptor(void) { static int fd = -1; return fd; } }; <commit_msg>create pid_directory in lock_single_application<commit_after>#pragma once #include "constants.hpp" #include "filesystem.hpp" #include <fcntl.h> #include <sstream> #include <string> #include <sys/file.h> class process_utility final { public: static bool lock_single_application(const std::string& pid_file_path) { auto pid_directory = filesystem::dirname(pid_file_path); if (pid_directory.empty()) { throw std::runtime_error("failed to get user pid directory"); } filesystem::create_directory_with_intermediate_directories(pid_directory, 0700); if (!filesystem::is_directory(pid_directory)) { throw std::runtime_error("failed to create pid directory"); } auto fd = open(pid_file_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd < 0) { throw std::runtime_error("failed to create pid file"); } if (flock(fd, LOCK_EX | LOCK_NB) == 0) { get_single_application_lock_pid_file_descriptor() = fd; std::stringstream ss; ss << getpid() << std::endl; auto string = ss.str(); write(fd, string.c_str(), string.size()); return true; } return false; } static void unlock_single_application(void) { auto& fd = get_single_application_lock_pid_file_descriptor(); if (fd >= 0) { flock(fd, LOCK_UN); close(fd); fd = -1; } } static bool lock_single_application_with_user_pid_file(const std::string& pid_file_name) { auto pid_directory = constants::get_user_pid_directory(); if (pid_directory.empty()) { throw std::runtime_error("failed to get user pid directory"); } std::string pid_file_path = pid_directory + "/" + pid_file_name; return lock_single_application(pid_file_path); } private: static int& get_single_application_lock_pid_file_descriptor(void) { static int fd = -1; return fd; } }; <|endoftext|>
<commit_before> #include "register_types.h" #include "object_type_db.h" #include "reference.h" // Wrap for oda #include "engine.h" #include <vector> #include <string> using std::string; using std::vector; const static string paths[1] = {"patches"}; class ODAModule : public Reference { OBJ_TYPE(ODAModule, Reference); public: ODAModule () : engine_(vector<string>(paths, paths + sizeof(paths)/sizeof(string))) {} protected: static void _bind_methods () { // nothing } private: oda::godot::Engine engine_; }; void register_openda_types () { ObjectTypeDB::register_type<ODAModule>(); } void unregister_openda_types () { // nothing at all? } <commit_msg>Env use<commit_after> #include "register_types.h" #include "object_type_db.h" #include "reference.h" // Wrap for oda #include "engine.h" #include <vector> #include <string> using std::string; using std::vector; const static string paths[1] = {"patches"}; class ODAModule : public Reference { OBJ_TYPE(ODAModule, Reference); public: ODAModule () : engine_(vector<string>(paths, paths + sizeof(paths)/sizeof(string))) {} protected: static void _bind_methods () { // nothing } private: oda::godot::Engine engine_; }; void register_openda_types () { ObjectTypeDB::register_type<ODAModule>(); } void unregister_openda_types () { // nothing at all? } <|endoftext|>
<commit_before>#pragma once #include "constants.hpp" #include "filesystem.hpp" #include <fcntl.h> #include <sstream> #include <string> #include <sys/file.h> namespace krbn { class process_utility final { public: static bool lock_single_application(const std::string& pid_file_path) { auto pid_directory = filesystem::dirname(pid_file_path); if (pid_directory.empty()) { throw std::runtime_error("failed to get user pid directory"); } filesystem::create_directory_with_intermediate_directories(pid_directory, 0700); if (!filesystem::is_directory(pid_directory)) { throw std::runtime_error("failed to create pid directory"); } auto fd = open(pid_file_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd < 0) { throw std::runtime_error("failed to create pid file"); } if (flock(fd, LOCK_EX | LOCK_NB) == 0) { get_single_application_lock_pid_file_descriptor() = fd; std::stringstream ss; ss << getpid() << std::endl; auto string = ss.str(); write(fd, string.c_str(), string.size()); return true; } return false; } static void unlock_single_application(void) { auto& fd = get_single_application_lock_pid_file_descriptor(); if (fd >= 0) { flock(fd, LOCK_UN); close(fd); fd = -1; } } static bool lock_single_application_with_user_pid_file(const std::string& pid_file_name) { auto pid_directory = constants::get_user_pid_directory(); if (pid_directory.empty()) { throw std::runtime_error("failed to get user pid directory"); } std::string pid_file_path = pid_directory + "/" + pid_file_name; return lock_single_application(pid_file_path); } private: static int& get_single_application_lock_pid_file_descriptor(void) { static int fd = -1; return fd; } }; } // namespace krbn <commit_msg>change pid directory permission (0700 -> 0755)<commit_after>#pragma once #include "constants.hpp" #include "filesystem.hpp" #include <fcntl.h> #include <sstream> #include <string> #include <sys/file.h> namespace krbn { class process_utility final { public: static bool lock_single_application(const std::string& pid_file_path) { auto pid_directory = filesystem::dirname(pid_file_path); if (pid_directory.empty()) { throw std::runtime_error("failed to get user pid directory"); } filesystem::create_directory_with_intermediate_directories(pid_directory, 0755); if (!filesystem::is_directory(pid_directory)) { throw std::runtime_error("failed to create pid directory"); } auto fd = open(pid_file_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { throw std::runtime_error("failed to create pid file"); } if (flock(fd, LOCK_EX | LOCK_NB) == 0) { get_single_application_lock_pid_file_descriptor() = fd; std::stringstream ss; ss << getpid() << std::endl; auto string = ss.str(); write(fd, string.c_str(), string.size()); return true; } return false; } static void unlock_single_application(void) { auto& fd = get_single_application_lock_pid_file_descriptor(); if (fd >= 0) { flock(fd, LOCK_UN); close(fd); fd = -1; } } static bool lock_single_application_with_user_pid_file(const std::string& pid_file_name) { auto pid_directory = constants::get_user_pid_directory(); if (pid_directory.empty()) { throw std::runtime_error("failed to get user pid directory"); } std::string pid_file_path = pid_directory + "/" + pid_file_name; return lock_single_application(pid_file_path); } private: static int& get_single_application_lock_pid_file_descriptor(void) { static int fd = -1; return fd; } }; } // namespace krbn <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #define __STDC_FORMAT_MACROS #include "swissknife_diff_tool.h" #include <inttypes.h> #include <stdint.h> #include "cvmfs_config.h" #include <vector> #include "directory_entry.h" #include "download.h" namespace swissknife { DiffTool::DiffTool(const std::string &repo_path, const history::History::Tag &old_tag, const history::History::Tag &new_tag, const std::string &temp_dir, download::DownloadManager *download_manager, bool machine_readable) : CatalogDiffTool(repo_path, old_tag.root_hash, new_tag.root_hash, temp_dir, download_manager), old_tag_(old_tag), new_tag_(new_tag), machine_readable_(machine_readable) {} DiffTool::~DiffTool() {} std::string DiffTool::PrintEntryType(const catalog::DirectoryEntry &entry) { if (entry.IsRegular()) return machine_readable_ ? "F" : "file"; else if (entry.IsLink()) return machine_readable_ ? "S" : "symlink"; else if (entry.IsDirectory()) return machine_readable_ ? "D" : "directory"; else return machine_readable_ ? "U" : "unknown"; } std::string DiffTool::PrintDifferences( catalog::DirectoryEntryBase::Differences diff) { vector<string> result_list; if (diff & catalog::DirectoryEntryBase::Difference::kName) result_list.push_back(machine_readable_ ? "N" : "name"); if (diff & catalog::DirectoryEntryBase::Difference::kLinkcount) result_list.push_back(machine_readable_ ? "I" : "link-count"); if (diff & catalog::DirectoryEntryBase::Difference::kSize) result_list.push_back(machine_readable_ ? "S" : "size"); if (diff & catalog::DirectoryEntryBase::Difference::kMode) result_list.push_back(machine_readable_ ? "M" : "mode"); if (diff & catalog::DirectoryEntryBase::Difference::kMtime) result_list.push_back(machine_readable_ ? "T" : "timestamp"); if (diff & catalog::DirectoryEntryBase::Difference::kSymlink) result_list.push_back(machine_readable_ ? "L" : "symlink-target"); if (diff & catalog::DirectoryEntryBase::Difference::kChecksum) result_list.push_back(machine_readable_ ? "C" : "content"); if (diff & catalog::DirectoryEntryBase::Difference::kHardlinkGroup) result_list.push_back(machine_readable_ ? "G" : "hardlink-group"); if (diff & catalog::DirectoryEntryBase::Difference::kNestedCatalogTransitionFlags) { result_list.push_back(machine_readable_ ? "N" : "nested-catalog"); } if (diff & catalog::DirectoryEntryBase::Difference::kChunkedFileFlag) result_list.push_back(machine_readable_ ? "P" : "chunked-file"); if (diff & catalog::DirectoryEntryBase::Difference::kHasXattrsFlag) result_list.push_back(machine_readable_ ? "X" : "xattrs"); if (diff & catalog::DirectoryEntryBase::Difference::kExternalFileFlag) result_list.push_back(machine_readable_ ? "E" : "external-file"); if (diff & catalog::DirectoryEntryBase::Difference::kBindMountpointFlag) result_list.push_back(machine_readable_ ? "B" : "bind-mountpoint"); if (diff & catalog::DirectoryEntryBase::Difference::kHiddenFlag) result_list.push_back(machine_readable_ ? "H" : "hidden"); return machine_readable_ ? ("[" + JoinStrings(result_list, "") + "]") : (" [" + JoinStrings(result_list, ", ") + "]"); } void DiffTool::ReportHeader() { if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "# line descriptor: A - add, R - remove, M - modify, " "S - statistics; modify flags: S - size, M - mode, T - timestamp, " "C - content, L - symlink target; entry types: F - regular file, " "S - symbolic link, D - directory, N - nested catalog"); } else { LogCvmfs(kLogCvmfs, kLogStdout, "DELTA: %s/r%u (%s) --> %s/r%u (%s)", old_tag_.name.c_str(), old_tag_.revision, StringifyTime(old_tag_.timestamp, true).c_str(), new_tag_.name.c_str(), new_tag_.revision, StringifyTime(new_tag_.timestamp, true).c_str()); } } void DiffTool::ReportAddition(const PathString &path, const catalog::DirectoryEntry &entry, const XattrList & /*xattrs*/) { string operation = machine_readable_ ? "A" : "add"; if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", operation.c_str(), PrintEntryType(entry).c_str(), path.c_str()); } else { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", path.c_str(), operation.c_str(), PrintEntryType(entry).c_str()); } } void DiffTool::ReportRemoval(const PathString &path, const catalog::DirectoryEntry &entry) { string operation = machine_readable_ ? "R" : "remove"; if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", operation.c_str(), PrintEntryType(entry).c_str(), path.c_str()); } else { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", path.c_str(), operation.c_str(), PrintEntryType(entry).c_str()); } } void DiffTool::ReportModification(const PathString &path, const catalog::DirectoryEntry &entry_from, const catalog::DirectoryEntry &entry_to, const XattrList & /*xattrs*/) { catalog::DirectoryEntryBase::Differences diff = entry_from.CompareTo(entry_to); string type_from = PrintEntryType(entry_from); string type_to = PrintEntryType(entry_to); string type = type_from; if (type_from != type_to) { type += machine_readable_ ? type_to : ("->" + type_to); } string operation = machine_readable_ ? "M" : "modify"; if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %s %s", operation.c_str(), PrintDifferences(diff).c_str(), type.c_str(), path.c_str()); } else { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s%s", path.c_str(), operation.c_str(), type.c_str(), PrintDifferences(diff).c_str()); } } void DiffTool::ReportStats() { const catalog::Catalog *catalog_from = GetOldCatalog(); const catalog::Catalog *catalog_to = GetNewCatalog(); const catalog::Counters counters_from = catalog_from->GetCounters(); const catalog::Counters counters_to = catalog_to->GetCounters(); catalog::DeltaCounters counters_diff = catalog::Counters::Diff(counters_from, counters_to); string operation = machine_readable_ ? "S " : "d("; string type_file = machine_readable_ ? "F" : "# regular files):"; string type_symlink = machine_readable_ ? "S" : "# symlinks):"; string type_directory = machine_readable_ ? "D" : "# directories):"; string type_catalog = machine_readable_ ? "N" : "# catalogs):"; int64_t diff_file = counters_diff.self.regular_files + counters_diff.subtree.regular_files; int64_t diff_symlink = counters_diff.self.symlinks + counters_diff.subtree.symlinks; int64_t diff_catalog = counters_diff.self.nested_catalogs + counters_diff.subtree.nested_catalogs; // Nested catalogs make internally two directory entries int64_t diff_directory = counters_diff.self.directories + counters_diff.subtree.directories - diff_catalog; LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_file.c_str(), diff_file); LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_symlink.c_str(), diff_symlink); LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_directory.c_str(), diff_directory); LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_catalog.c_str(), diff_catalog); } } // namespace swissknife <commit_msg>Fix initialization of super class in swissknife::DiffTool<commit_after>/** * This file is part of the CernVM File System. */ #define __STDC_FORMAT_MACROS #include "swissknife_diff_tool.h" #include <inttypes.h> #include <stdint.h> #include "cvmfs_config.h" #include <vector> #include "directory_entry.h" #include "download.h" namespace swissknife { DiffTool::DiffTool(const std::string &repo_path, const history::History::Tag &old_tag, const history::History::Tag &new_tag, const std::string &temp_dir, download::DownloadManager *download_manager, bool machine_readable) : CatalogDiffTool<catalog::SimpleCatalogManager>( repo_path, old_tag.root_hash, new_tag.root_hash, temp_dir, download_manager), old_tag_(old_tag), new_tag_(new_tag), machine_readable_(machine_readable) {} DiffTool::~DiffTool() {} std::string DiffTool::PrintEntryType(const catalog::DirectoryEntry &entry) { if (entry.IsRegular()) return machine_readable_ ? "F" : "file"; else if (entry.IsLink()) return machine_readable_ ? "S" : "symlink"; else if (entry.IsDirectory()) return machine_readable_ ? "D" : "directory"; else return machine_readable_ ? "U" : "unknown"; } std::string DiffTool::PrintDifferences( catalog::DirectoryEntryBase::Differences diff) { vector<string> result_list; if (diff & catalog::DirectoryEntryBase::Difference::kName) result_list.push_back(machine_readable_ ? "N" : "name"); if (diff & catalog::DirectoryEntryBase::Difference::kLinkcount) result_list.push_back(machine_readable_ ? "I" : "link-count"); if (diff & catalog::DirectoryEntryBase::Difference::kSize) result_list.push_back(machine_readable_ ? "S" : "size"); if (diff & catalog::DirectoryEntryBase::Difference::kMode) result_list.push_back(machine_readable_ ? "M" : "mode"); if (diff & catalog::DirectoryEntryBase::Difference::kMtime) result_list.push_back(machine_readable_ ? "T" : "timestamp"); if (diff & catalog::DirectoryEntryBase::Difference::kSymlink) result_list.push_back(machine_readable_ ? "L" : "symlink-target"); if (diff & catalog::DirectoryEntryBase::Difference::kChecksum) result_list.push_back(machine_readable_ ? "C" : "content"); if (diff & catalog::DirectoryEntryBase::Difference::kHardlinkGroup) result_list.push_back(machine_readable_ ? "G" : "hardlink-group"); if (diff & catalog::DirectoryEntryBase::Difference::kNestedCatalogTransitionFlags) { result_list.push_back(machine_readable_ ? "N" : "nested-catalog"); } if (diff & catalog::DirectoryEntryBase::Difference::kChunkedFileFlag) result_list.push_back(machine_readable_ ? "P" : "chunked-file"); if (diff & catalog::DirectoryEntryBase::Difference::kHasXattrsFlag) result_list.push_back(machine_readable_ ? "X" : "xattrs"); if (diff & catalog::DirectoryEntryBase::Difference::kExternalFileFlag) result_list.push_back(machine_readable_ ? "E" : "external-file"); if (diff & catalog::DirectoryEntryBase::Difference::kBindMountpointFlag) result_list.push_back(machine_readable_ ? "B" : "bind-mountpoint"); if (diff & catalog::DirectoryEntryBase::Difference::kHiddenFlag) result_list.push_back(machine_readable_ ? "H" : "hidden"); return machine_readable_ ? ("[" + JoinStrings(result_list, "") + "]") : (" [" + JoinStrings(result_list, ", ") + "]"); } void DiffTool::ReportHeader() { if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "# line descriptor: A - add, R - remove, M - modify, " "S - statistics; modify flags: S - size, M - mode, T - timestamp, " "C - content, L - symlink target; entry types: F - regular file, " "S - symbolic link, D - directory, N - nested catalog"); } else { LogCvmfs(kLogCvmfs, kLogStdout, "DELTA: %s/r%u (%s) --> %s/r%u (%s)", old_tag_.name.c_str(), old_tag_.revision, StringifyTime(old_tag_.timestamp, true).c_str(), new_tag_.name.c_str(), new_tag_.revision, StringifyTime(new_tag_.timestamp, true).c_str()); } } void DiffTool::ReportAddition(const PathString &path, const catalog::DirectoryEntry &entry, const XattrList & /*xattrs*/) { string operation = machine_readable_ ? "A" : "add"; if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", operation.c_str(), PrintEntryType(entry).c_str(), path.c_str()); } else { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", path.c_str(), operation.c_str(), PrintEntryType(entry).c_str()); } } void DiffTool::ReportRemoval(const PathString &path, const catalog::DirectoryEntry &entry) { string operation = machine_readable_ ? "R" : "remove"; if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", operation.c_str(), PrintEntryType(entry).c_str(), path.c_str()); } else { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s", path.c_str(), operation.c_str(), PrintEntryType(entry).c_str()); } } void DiffTool::ReportModification(const PathString &path, const catalog::DirectoryEntry &entry_from, const catalog::DirectoryEntry &entry_to, const XattrList & /*xattrs*/) { catalog::DirectoryEntryBase::Differences diff = entry_from.CompareTo(entry_to); string type_from = PrintEntryType(entry_from); string type_to = PrintEntryType(entry_to); string type = type_from; if (type_from != type_to) { type += machine_readable_ ? type_to : ("->" + type_to); } string operation = machine_readable_ ? "M" : "modify"; if (machine_readable_) { LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %s %s", operation.c_str(), PrintDifferences(diff).c_str(), type.c_str(), path.c_str()); } else { LogCvmfs(kLogCvmfs, kLogStdout, "%s %s %s%s", path.c_str(), operation.c_str(), type.c_str(), PrintDifferences(diff).c_str()); } } void DiffTool::ReportStats() { const catalog::Catalog *catalog_from = GetOldCatalog(); const catalog::Catalog *catalog_to = GetNewCatalog(); const catalog::Counters counters_from = catalog_from->GetCounters(); const catalog::Counters counters_to = catalog_to->GetCounters(); catalog::DeltaCounters counters_diff = catalog::Counters::Diff(counters_from, counters_to); string operation = machine_readable_ ? "S " : "d("; string type_file = machine_readable_ ? "F" : "# regular files):"; string type_symlink = machine_readable_ ? "S" : "# symlinks):"; string type_directory = machine_readable_ ? "D" : "# directories):"; string type_catalog = machine_readable_ ? "N" : "# catalogs):"; int64_t diff_file = counters_diff.self.regular_files + counters_diff.subtree.regular_files; int64_t diff_symlink = counters_diff.self.symlinks + counters_diff.subtree.symlinks; int64_t diff_catalog = counters_diff.self.nested_catalogs + counters_diff.subtree.nested_catalogs; // Nested catalogs make internally two directory entries int64_t diff_directory = counters_diff.self.directories + counters_diff.subtree.directories - diff_catalog; LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_file.c_str(), diff_file); LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_symlink.c_str(), diff_symlink); LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_directory.c_str(), diff_directory); LogCvmfs(kLogCvmfs, kLogStdout, "%s%s %" PRId64, operation.c_str(), type_catalog.c_str(), diff_catalog); } } // namespace swissknife <|endoftext|>
<commit_before><commit_msg>svx: simplify this<commit_after><|endoftext|>
<commit_before><commit_msg>Don't set Referer when accessing embedded media<commit_after><|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <time.h> #include <unistd.h> using namespace std; double pi = 3.141592653589793238463; double todeg = 180.0 / pi; double torad = pi / 180.0; double hstep = 1.0 / 24; double mstep = 1.0 / 1440; double sstep = 1.0 / 86400; double riseduration = sstep * 5400; struct julian { double jrise; double jset; }; // display fraction of a day in hours and minutes, but return a string string j2h(double jd) { int hr, mn; char buffer[10]; hr = (int)(jd * 24); mn = (int)(((jd * 24) - (double(hr))) * 60); snprintf(buffer, sizeof(buffer), "%02d:%02d", hr, mn); return buffer; } void setlights(double dayhour, double dawn, double rise, double set, double dusk) { bool lights; bool riseordawn; double riseduration_red = riseduration; double riseduration_green = riseduration * 0.8; double riseduration_blue = riseduration * 0.6; double rperc = 1 / riseduration_red; double gperc = 1 / riseduration_green; double bperc = 1 / riseduration_blue; double red = 0, green = 0, blue = 0; ofstream filehandler; string filename; // first check if the main lights should be turned on or off if ((dayhour < rise) || (dayhour > set)) { lights = 0; } else { lights = 1; } // now check if we are in sunrise if ((dayhour >= dawn) && (dayhour <= (rise + mstep))) { riseordawn = 1; red = (dayhour - dawn) * rperc; if (dayhour >= (dawn + (riseduration_red - riseduration_green))) { green = (dayhour - (dawn + (riseduration_red - riseduration_green))) * gperc; } if (dayhour >= (dawn + (riseduration_red - riseduration_blue))) { blue = (dayhour - (dawn + (riseduration_red - riseduration_blue))) * bperc; } } else if ((dayhour >= (set - mstep)) && (dayhour <= dusk)) { // or are we in sunset red = 1 - ((dayhour - (dusk - riseduration_red)) * rperc); green = 1 - ((dayhour - (dusk - riseduration_red)) * gperc); blue = 1 - ((dayhour - (dusk - riseduration_red)) * bperc); riseordawn = 1; } else { // or no twilight riseordawn = 0; red = green = blue = 0; } // failsafe if calculations took a wrong direction somewhere if (red > 1) { red = 1; } if (green > 1) { green = 1; } if (blue > 1) { blue = 1; } if (red < 0) { red = 0; } if (green < 0) { green = 0; } if (blue < 0) { blue = 0; } /* // debugging cout << "dayhour " << dayhour << ", lights " << lights << ", riseordawn " << riseordawn << ", red " << red << ", green " << green << ", blue " << blue << endl; */ // write the calculated values to the system // the pins are hardcoded - that's not very // nice, but it works... filename = "/dev/shm/pin_8"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << (int)lights << endl; filehandler.close(); } else { cout << "ERROR: could not write to " << filename << endl; } filename = "/dev/shm/pin_9"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << (int)riseordawn << endl; filehandler.close(); } else { cout << "ERROR: could not write to " << filename << endl; } if ((red > 0) && (red < 1)) { filename = "/dev/pi-blaster"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << "14=" << red << endl; filehandler << "15=" << green << endl; filehandler << "18=" << blue << endl; filehandler.close(); } else { cout << "ERROR: could not write to " << filename << endl; } } } struct julian calcjtimes(time_t t) { struct tm *current_time = gmtime(&t); // longitude west of magdeburg double low = -11.6322; // latitude of magdeburg double lam = 52.1243; // latitude of madagascar (if it were on northern hemishpere) // double lam=22.5; // calculate julian day number based on // https://de.wikipedia.org/wiki/Julianisches_Datum int m = current_time->tm_mon + 1; int y = current_time->tm_year + 1900; if (m <= 2) { m += 12; y--; } int d = current_time->tm_mday; int a = floor((y) / 100); double b = 2 - a + floor(a / 4); double jd = floor(365.25 * (y + 4716)) + floor(30.6001 * (m + 1)) + d + b - 1524.5; // calculation of sunrise based on // https://en.wikipedia.org/wiki/Sunrise_equation // current julian day double n = jd - 2451545 + 0.0008; // mean solar noon double js = low / 360 + n; // mean anomaly double ma = fmod((357.5291 + 0.98560028 * js), 360); // equation of the center double c = 1.9148 * sin(ma * torad) + 0.02 * sin(2 * ma * torad) + 0.0003 * sin(3 * ma * torad); // ecliptic longitude double l = fmod((ma + c + 180 + 102.9372), 360); // solar transit - it seems they have forgotten the 2451545.5 on the wikipedia // page. or i did not understand correctly. double jt = 2451545.5 + js + 0.0053 * sin(ma * torad) - 0.0069 * sin(2 * l * torad); // declination of the sun double de = asin(sin(l * torad) * sin(23.44 * torad)) * todeg; // hour angle double w = acos((sin(-0.83 * torad) - sin(lam * torad) * sin(de * torad)) / (cos(lam * torad) * cos(de * torad))) * todeg; double jset = jt + w / 360; double jrise = jt - w / 360; struct julian cjt = {jrise, jset}; return cjt; } int main() { cout << "starting up..." << endl; time_t now = time(0); struct tm *nowt; int nowd = gmtime(&now)->tm_yday; int curd = nowd + 1; struct julian jt; double sunrise; double sunset; double lightson; double lightsoff; double dawn; double dusk; // better float precision for debugging purposes std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(10); // here is the main loop, that just loops over and over again while (true) { now = time(0); nowt = localtime(&now); nowd = nowt->tm_yday; if (nowd != curd) { cout << "a new day" << endl; // the day changed, so this is a new day curd = nowd; jt = calcjtimes(now); // now we have the correct times. first skip the acutal // date because i only need the times. as julian day .5 is // 00:00 gmt we have to subtract .5 so we get the correct // values for hour, minute and second. // they will be shifted so // the day of the terrarium matches the day of the owners and // also i want to have a nice dawn and dusk. // the dawn and dusk will spread evenly before and after // the actal sunrise sunrise = (jt.jrise - .5 - floor(jt.jrise - .5)) + mstep * 60; sunset = (jt.jset - .5 - floor(jt.jset - .5)) + mstep * 60; lightson = sunrise + riseduration / 2; lightsoff = sunset - riseduration / 2; dawn = sunrise - riseduration / 2; dusk = sunset + riseduration / 2; // write everything to the log cout << "name julian time | utc" << endl; cout << "sunrise: " << sunrise << "|" << j2h(sunrise) << endl; cout << "sunset: " << sunset << "|" << j2h(sunset) << endl; cout << "lights on: " << lightson << "|" << j2h(lightson) << endl; cout << "lights off: " << lightsoff << "|" << j2h(lightsoff) << endl; cout << "dawn start: " << dawn << "|" << j2h(dawn) << endl; cout << "dusk stop: " << dusk << "|" << j2h(dusk) << endl; // write everything to a file ofstream filehandler; string filename = "/dev/shm/terrarium_times"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << "sunrise " << sunrise << " " << j2h(sunrise) << endl; filehandler << "sunset " << sunrise << " " << j2h(sunset) << endl; filehandler << "start_dawn " << sunrise << " " << j2h(dawn) << endl; filehandler << "start_daylight " << sunrise << " " << j2h(lightson) << endl; filehandler << "stop_daylight " << sunrise << " " << j2h(lightsoff) << endl; filehandler << "stop_dusk " << sunrise << " " << j2h(dusk) << endl; filehandler.close(); } } // set the lights setlights(nowt->tm_hour * hstep + nowt->tm_min * mstep + nowt->tm_sec * sstep, dawn, lightson, lightsoff, dusk); // sleep for 5 seconds usleep(5000000); } // this will never be reached, but anyway return 0; } <commit_msg>correct julian times<commit_after>#include <fstream> #include <iostream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <time.h> #include <unistd.h> using namespace std; double pi = 3.141592653589793238463; double todeg = 180.0 / pi; double torad = pi / 180.0; double hstep = 1.0 / 24; double mstep = 1.0 / 1440; double sstep = 1.0 / 86400; double riseduration = sstep * 5400; struct julian { double jrise; double jset; }; // display fraction of a day in hours and minutes, but return a string string j2h(double jd) { int hr, mn; char buffer[10]; hr = (int)(jd * 24); mn = (int)(((jd * 24) - (double(hr))) * 60); snprintf(buffer, sizeof(buffer), "%02d:%02d", hr, mn); return buffer; } void setlights(double dayhour, double dawn, double rise, double set, double dusk) { bool lights; bool riseordawn; double riseduration_red = riseduration; double riseduration_green = riseduration * 0.8; double riseduration_blue = riseduration * 0.6; double rperc = 1 / riseduration_red; double gperc = 1 / riseduration_green; double bperc = 1 / riseduration_blue; double red = 0, green = 0, blue = 0; ofstream filehandler; string filename; // first check if the main lights should be turned on or off if ((dayhour < rise) || (dayhour > set)) { lights = 0; } else { lights = 1; } // now check if we are in sunrise if ((dayhour >= dawn) && (dayhour <= (rise + mstep))) { riseordawn = 1; red = (dayhour - dawn) * rperc; if (dayhour >= (dawn + (riseduration_red - riseduration_green))) { green = (dayhour - (dawn + (riseduration_red - riseduration_green))) * gperc; } if (dayhour >= (dawn + (riseduration_red - riseduration_blue))) { blue = (dayhour - (dawn + (riseduration_red - riseduration_blue))) * bperc; } } else if ((dayhour >= (set - mstep)) && (dayhour <= dusk)) { // or are we in sunset red = 1 - ((dayhour - (dusk - riseduration_red)) * rperc); green = 1 - ((dayhour - (dusk - riseduration_red)) * gperc); blue = 1 - ((dayhour - (dusk - riseduration_red)) * bperc); riseordawn = 1; } else { // or no twilight riseordawn = 0; red = green = blue = 0; } // failsafe if calculations took a wrong direction somewhere if (red > 1) { red = 1; } if (green > 1) { green = 1; } if (blue > 1) { blue = 1; } if (red < 0) { red = 0; } if (green < 0) { green = 0; } if (blue < 0) { blue = 0; } /* // debugging cout << "dayhour " << dayhour << ", lights " << lights << ", riseordawn " << riseordawn << ", red " << red << ", green " << green << ", blue " << blue << endl; */ // write the calculated values to the system // the pins are hardcoded - that's not very // nice, but it works... filename = "/dev/shm/pin_8"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << (int)lights << endl; filehandler.close(); } else { cout << "ERROR: could not write to " << filename << endl; } filename = "/dev/shm/pin_9"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << (int)riseordawn << endl; filehandler.close(); } else { cout << "ERROR: could not write to " << filename << endl; } if ((red > 0) && (red < 1)) { filename = "/dev/pi-blaster"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << "14=" << red << endl; filehandler << "15=" << green << endl; filehandler << "18=" << blue << endl; filehandler.close(); } else { cout << "ERROR: could not write to " << filename << endl; } } } struct julian calcjtimes(time_t t) { struct tm *current_time = gmtime(&t); // longitude west of magdeburg double low = -11.6322; // latitude of magdeburg double lam = 52.1243; // latitude of madagascar (if it were on northern hemishpere) // double lam=22.5; // calculate julian day number based on // https://de.wikipedia.org/wiki/Julianisches_Datum int m = current_time->tm_mon + 1; int y = current_time->tm_year + 1900; if (m <= 2) { m += 12; y--; } int d = current_time->tm_mday; int a = floor((y) / 100); double b = 2 - a + floor(a / 4); double jd = floor(365.25 * (y + 4716)) + floor(30.6001 * (m + 1)) + d + b - 1524.5; // calculation of sunrise based on // https://en.wikipedia.org/wiki/Sunrise_equation // current julian day double n = jd - 2451545 + 0.0008; // mean solar noon double js = low / 360 + n; // mean anomaly double ma = fmod((357.5291 + 0.98560028 * js), 360); // equation of the center double c = 1.9148 * sin(ma * torad) + 0.02 * sin(2 * ma * torad) + 0.0003 * sin(3 * ma * torad); // ecliptic longitude double l = fmod((ma + c + 180 + 102.9372), 360); // solar transit - it seems they have forgotten the 2451545.5 on the wikipedia // page. or i did not understand correctly. double jt = 2451545.5 + js + 0.0053 * sin(ma * torad) - 0.0069 * sin(2 * l * torad); // declination of the sun double de = asin(sin(l * torad) * sin(23.44 * torad)) * todeg; // hour angle double w = acos((sin(-0.83 * torad) - sin(lam * torad) * sin(de * torad)) / (cos(lam * torad) * cos(de * torad))) * todeg; double jset = jt + w / 360; double jrise = jt - w / 360; struct julian cjt = {jrise, jset}; return cjt; } int main() { cout << "starting up..." << endl; time_t now = time(0); struct tm *nowt; int nowd = gmtime(&now)->tm_yday; int curd = nowd + 1; struct julian jt; double sunrise; double sunset; double lightson; double lightsoff; double dawn; double dusk; // better float precision for debugging purposes std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(10); // here is the main loop, that just loops over and over again while (true) { now = time(0); nowt = localtime(&now); nowd = nowt->tm_yday; if (nowd != curd) { cout << "a new day" << endl; // the day changed, so this is a new day curd = nowd; jt = calcjtimes(now); // now we have the correct times. first skip the acutal // date because i only need the times. as julian day .5 is // 00:00 gmt we have to subtract .5 so we get the correct // values for hour, minute and second. // they will be shifted so // the day of the terrarium matches the day of the owners and // also i want to have a nice dawn and dusk. // the dawn and dusk will spread evenly before and after // the actal sunrise sunrise = (jt.jrise - .5 - floor(jt.jrise - .5)) + mstep * 60; sunset = (jt.jset - .5 - floor(jt.jset - .5)) + mstep * 60; lightson = sunrise + riseduration / 2; lightsoff = sunset - riseduration / 2; dawn = sunrise - riseduration / 2; dusk = sunset + riseduration / 2; // write everything to the log cout << "name julian time | utc" << endl; cout << "sunrise: " << sunrise << "|" << j2h(sunrise) << endl; cout << "sunset: " << sunset << "|" << j2h(sunset) << endl; cout << "lights on: " << lightson << "|" << j2h(lightson) << endl; cout << "lights off: " << lightsoff << "|" << j2h(lightsoff) << endl; cout << "dawn start: " << dawn << "|" << j2h(dawn) << endl; cout << "dusk stop: " << dusk << "|" << j2h(dusk) << endl; // write everything to a file ofstream filehandler; string filename = "/dev/shm/terrarium_times"; filehandler.open(filename.c_str()); if (filehandler.is_open()) { filehandler << "sunrise " << sunrise << " " << j2h(sunrise) << endl; filehandler << "sunset " << sunset << " " << j2h(sunset) << endl; filehandler << "start_dawn " << dawn << " " << j2h(dawn) << endl; filehandler << "start_daylight " << lightson << " " << j2h(lightson) << endl; filehandler << "stop_daylight " << lightsoff << " " << j2h(lightsoff) << endl; filehandler << "stop_dusk " << dusk << " " << j2h(dusk) << endl; filehandler.close(); } } // set the lights setlights(nowt->tm_hour * hstep + nowt->tm_min * mstep + nowt->tm_sec * sstep, dawn, lightson, lightsoff, dusk); // sleep for 5 seconds usleep(5000000); } // this will never be reached, but anyway return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unoctabl.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: af $ $Date: 2002-02-13 10:48:59 $ * * 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 INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #include <cppuhelper/implbase2.hxx> #include "xtable.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoColorTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo > { private: XColorTable* pTable; public: SvxUnoColorTable() throw(); virtual ~SvxUnoColorTable() throw(); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); static OUString getImplementationName_Static() throw() { return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.SvxUnoColorTable")); } static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw(); // XNameContainer virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException); virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameAccess virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException); }; SvxUnoColorTable::SvxUnoColorTable() throw() { pTable = new XColorTable( SvtPathOptions().GetPalettePath() ); } SvxUnoColorTable::~SvxUnoColorTable() throw() { delete pTable; } sal_Bool SAL_CALL SvxUnoColorTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException) { uno::Sequence< OUString > aSNL( getSupportedServiceNames() ); const OUString * pArray = aSNL.getConstArray(); for( INT32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return TRUE; return FALSE; } OUString SAL_CALL SvxUnoColorTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoColorTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { return getSupportedServiceNames_Static(); } uno::Sequence< OUString > SvxUnoColorTable::getSupportedServiceNames_Static(void) throw() { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.ColorTable" )); return aSNS; } // XNameContainer void SAL_CALL SvxUnoColorTable::insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException ) { if( hasByName( aName ) ) throw container::ElementExistException(); INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); if( pTable ) { XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); pTable->Insert( pTable->Count(), pEntry ); } } void SAL_CALL SvxUnoColorTable::removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( Name ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); pTable->Remove( nIndex ); } // XNameReplace void SAL_CALL SvxUnoColorTable::replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException ) { INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); delete pTable->Replace( nIndex, pEntry ); } // XNameAccess uno::Any SAL_CALL SvxUnoColorTable::getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = pTable->Get( nIndex ); uno::Any aAny; aAny <<= (sal_Int32) pEntry->GetColor().GetRGBColor(); return aAny; } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getElementNames( ) throw( uno::RuntimeException ) { const long nCount = pTable ? pTable->Count() : 0; uno::Sequence< OUString > aSeq( nCount ); OUString* pStrings = aSeq.getArray(); for( long nIndex = 0; nIndex < nCount; nIndex++ ) { XColorEntry* pEntry = pTable->Get( nIndex ); pStrings[nIndex] = pEntry->GetName(); } return aSeq; } sal_Bool SAL_CALL SvxUnoColorTable::hasByName( const OUString& aName ) throw( uno::RuntimeException ) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; return nIndex != -1; } // XElementAccess uno::Type SAL_CALL SvxUnoColorTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType((const sal_Int32*)0); } sal_Bool SAL_CALL SvxUnoColorTable::hasElements( ) throw( uno::RuntimeException ) { return pTable && pTable->Count() != 0; } /** * Create a colortable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoColorTable_createInstance(const uno::Reference< lang::XMultiServiceFactory > & rSMgr) throw(uno::Exception) { return *new SvxUnoColorTable(); } // // export this service // #ifndef SVX_LIGHT #include "UnoGraphicExporter.hxx" #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <cppuhelper/factory.hxx> #include <uno/lbnames.h> extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void SAL_CALL writeInfo( registry::XRegistryKey * pRegistryKey, const OUString& rImplementationName, const uno::Sequence< OUString >& rServices ) { uno::Reference< registry::XRegistryKey > xNewKey( pRegistryKey->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + rImplementationName + OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ) ); for( sal_Int32 i = 0; i < rServices.getLength(); i++ ) xNewKey->createKey( rServices.getConstArray()[i]); } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if( pRegistryKey ) { try { registry::XRegistryKey *pKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey ); writeInfo( pKey, SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable::getSupportedServiceNames_Static() ); #ifndef SVX_LIGHT writeInfo( pKey, svx::GraphicExporter_getImplementationName(), svx::GraphicExporter_getSupportedServiceNames() ); #endif } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_True; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; if( pServiceManager ) { uno::Reference< lang::XSingleServiceFactory > xFactory; if( rtl_str_compare( pImplName, "com.sun.star.drawing.SvxUnoColorTable" ) == 0 ) { xFactory = createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable_createInstance, SvxUnoColorTable::getSupportedServiceNames_Static() ); } #ifndef SVX_LIGHT else if( svx::GraphicExporter_getImplementationName().equalsAscii( pImplName ) ) { xFactory = ::cppu::createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), svx::GraphicExporter_getImplementationName(), svx::GraphicExporter_createInstance, svx::GraphicExporter_getSupportedServiceNames() ); } #endif if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } <commit_msg>INTEGRATION: CWS fwkq1 (1.7.286); FILE MERGED 2003/07/15 06:31:29 mba 1.7.286.1: #110843#: get rid of factories<commit_after>/************************************************************************* * * $RCSfile: unoctabl.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2003-09-19 08:32:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #include <cppuhelper/implbase2.hxx> #include "xtable.hxx" #include "unoshcol.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoColorTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo > { private: XColorTable* pTable; public: SvxUnoColorTable() throw(); virtual ~SvxUnoColorTable() throw(); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); static OUString getImplementationName_Static() throw() { return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.SvxUnoColorTable")); } static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw(); // XNameContainer virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException); virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameAccess virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException); }; SvxUnoColorTable::SvxUnoColorTable() throw() { pTable = new XColorTable( SvtPathOptions().GetPalettePath() ); } SvxUnoColorTable::~SvxUnoColorTable() throw() { delete pTable; } sal_Bool SAL_CALL SvxUnoColorTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException) { uno::Sequence< OUString > aSNL( getSupportedServiceNames() ); const OUString * pArray = aSNL.getConstArray(); for( INT32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return TRUE; return FALSE; } OUString SAL_CALL SvxUnoColorTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoColorTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { return getSupportedServiceNames_Static(); } uno::Sequence< OUString > SvxUnoColorTable::getSupportedServiceNames_Static(void) throw() { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.ColorTable" )); return aSNS; } // XNameContainer void SAL_CALL SvxUnoColorTable::insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException ) { if( hasByName( aName ) ) throw container::ElementExistException(); INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); if( pTable ) { XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); pTable->Insert( pTable->Count(), pEntry ); } } void SAL_CALL SvxUnoColorTable::removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( Name ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); pTable->Remove( nIndex ); } // XNameReplace void SAL_CALL SvxUnoColorTable::replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException ) { INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); delete pTable->Replace( nIndex, pEntry ); } // XNameAccess uno::Any SAL_CALL SvxUnoColorTable::getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = pTable->Get( nIndex ); uno::Any aAny; aAny <<= (sal_Int32) pEntry->GetColor().GetRGBColor(); return aAny; } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getElementNames( ) throw( uno::RuntimeException ) { const long nCount = pTable ? pTable->Count() : 0; uno::Sequence< OUString > aSeq( nCount ); OUString* pStrings = aSeq.getArray(); for( long nIndex = 0; nIndex < nCount; nIndex++ ) { XColorEntry* pEntry = pTable->Get( nIndex ); pStrings[nIndex] = pEntry->GetName(); } return aSeq; } sal_Bool SAL_CALL SvxUnoColorTable::hasByName( const OUString& aName ) throw( uno::RuntimeException ) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; return nIndex != -1; } // XElementAccess uno::Type SAL_CALL SvxUnoColorTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType((const sal_Int32*)0); } sal_Bool SAL_CALL SvxUnoColorTable::hasElements( ) throw( uno::RuntimeException ) { return pTable && pTable->Count() != 0; } /** * Create a colortable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoColorTable_createInstance(const uno::Reference< lang::XMultiServiceFactory > & rSMgr) throw(uno::Exception) { return *new SvxUnoColorTable(); } // // export this service // #ifndef SVX_LIGHT #include "UnoGraphicExporter.hxx" #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <cppuhelper/factory.hxx> #include <uno/lbnames.h> extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void SAL_CALL writeInfo( registry::XRegistryKey * pRegistryKey, const OUString& rImplementationName, const uno::Sequence< OUString >& rServices ) { uno::Reference< registry::XRegistryKey > xNewKey( pRegistryKey->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + rImplementationName + OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ) ); for( sal_Int32 i = 0; i < rServices.getLength(); i++ ) xNewKey->createKey( rServices.getConstArray()[i]); } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if( pRegistryKey ) { try { registry::XRegistryKey *pKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey ); writeInfo( pKey, SvxShapeCollection::getImplementationName_Static(), SvxShapeCollection::getSupportedServiceNames_Static() ); writeInfo( pKey, SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable::getSupportedServiceNames_Static() ); #ifndef SVX_LIGHT writeInfo( pKey, svx::GraphicExporter_getImplementationName(), svx::GraphicExporter_getSupportedServiceNames() ); #endif } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_True; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; if( pServiceManager ) { uno::Reference< lang::XSingleServiceFactory > xFactory; if( rtl_str_compare( pImplName, "com.sun.star.drawing.SvxUnoColorTable" ) == 0 ) { xFactory = createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable_createInstance, SvxUnoColorTable::getSupportedServiceNames_Static() ); } else if( rtl_str_compare( pImplName, "com.sun.star.drawing.SvxShapeCollection" ) == 0 ) { xFactory = createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), SvxShapeCollection::getImplementationName_Static(), SvxShapeCollection_createInstance, SvxShapeCollection::getSupportedServiceNames_Static() ); } #ifndef SVX_LIGHT else if( svx::GraphicExporter_getImplementationName().equalsAscii( pImplName ) ) { xFactory = ::cppu::createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), svx::GraphicExporter_getImplementationName(), svx::GraphicExporter_createInstance, svx::GraphicExporter_getSupportedServiceNames() ); } #endif if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } <|endoftext|>
<commit_before>/** * This file is part of TelepathyQt4 * * @copyright Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * @copyright Copyright (C) 2010 Nokia Corporation * @license LGPL 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/LocationInfo> #include <QDBusArgument> namespace Tp { struct TELEPATHY_QT4_NO_EXPORT LocationInfo::Private : public QSharedData { QVariantMap location; }; /** * \class LocationInfo * \ingroup clientconn * \headerfile TelepathyQt4/contact-location.h <TelepathyQt4/LocationInfo> * * \brief The LocationInfo class provides an object representing the * location of a Contact. */ /** * Construct a new LocationInfo object. */ LocationInfo::LocationInfo() : mPriv(new Private) { } LocationInfo::LocationInfo(const QVariantMap &location) : mPriv(new Private) { mPriv->location = location; } LocationInfo::LocationInfo(const LocationInfo &other) : mPriv(other.mPriv) { } /** * Class destructor. */ LocationInfo::~LocationInfo() { } LocationInfo &LocationInfo::operator=(const LocationInfo &other) { this->mPriv = other.mPriv; return *this; } QString LocationInfo::countryCode() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("countrycode"))); } QString LocationInfo::country() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("country"))); } QString LocationInfo::region() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("region"))); } QString LocationInfo::locality() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("locality"))); } QString LocationInfo::area() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("area"))); } QString LocationInfo::postalCode() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("postalcode"))); } QString LocationInfo::street() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("street"))); } QString LocationInfo::building() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("building"))); } QString LocationInfo::floor() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("floor"))); } QString LocationInfo::room() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("room"))); } QString LocationInfo::text() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("text"))); } QString LocationInfo::description() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("description"))); } QString LocationInfo::uri() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("uri"))); } QString LocationInfo::language() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("language"))); } double LocationInfo::latitude() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("lat"))); } double LocationInfo::longitude() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("lon"))); } double LocationInfo::altitude() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("alt"))); } double LocationInfo::accuracy() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("accuracy"))); } double LocationInfo::speed() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("speed"))); } double LocationInfo::bearing() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("bearing"))); } QDateTime LocationInfo::timestamp() const { // FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690 qlonglong t = qdbus_cast<qlonglong>(mPriv->location.value( QLatin1String("timestamp"))); if (t != 0) { return QDateTime::fromTime_t((uint) t); } return QDateTime(); } QVariantMap LocationInfo::allDetails() const { return mPriv->location; } void LocationInfo::updateData(const QVariantMap &location) { if (!isValid()) { mPriv = new Private; } mPriv->location = location; } } // Tp <commit_msg>LocationInfo: Fix headerfile doc<commit_after>/** * This file is part of TelepathyQt4 * * @copyright Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * @copyright Copyright (C) 2010 Nokia Corporation * @license LGPL 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/LocationInfo> #include <QDBusArgument> namespace Tp { struct TELEPATHY_QT4_NO_EXPORT LocationInfo::Private : public QSharedData { QVariantMap location; }; /** * \class LocationInfo * \ingroup clientconn * \headerfile TelepathyQt4/location-info.h <TelepathyQt4/LocationInfo> * * \brief The LocationInfo class provides an object representing the * location of a Contact. */ /** * Construct a new LocationInfo object. */ LocationInfo::LocationInfo() : mPriv(new Private) { } LocationInfo::LocationInfo(const QVariantMap &location) : mPriv(new Private) { mPriv->location = location; } LocationInfo::LocationInfo(const LocationInfo &other) : mPriv(other.mPriv) { } /** * Class destructor. */ LocationInfo::~LocationInfo() { } LocationInfo &LocationInfo::operator=(const LocationInfo &other) { this->mPriv = other.mPriv; return *this; } QString LocationInfo::countryCode() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("countrycode"))); } QString LocationInfo::country() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("country"))); } QString LocationInfo::region() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("region"))); } QString LocationInfo::locality() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("locality"))); } QString LocationInfo::area() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("area"))); } QString LocationInfo::postalCode() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("postalcode"))); } QString LocationInfo::street() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("street"))); } QString LocationInfo::building() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("building"))); } QString LocationInfo::floor() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("floor"))); } QString LocationInfo::room() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("room"))); } QString LocationInfo::text() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("text"))); } QString LocationInfo::description() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("description"))); } QString LocationInfo::uri() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("uri"))); } QString LocationInfo::language() const { return qdbus_cast<QString>(mPriv->location.value( QLatin1String("language"))); } double LocationInfo::latitude() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("lat"))); } double LocationInfo::longitude() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("lon"))); } double LocationInfo::altitude() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("alt"))); } double LocationInfo::accuracy() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("accuracy"))); } double LocationInfo::speed() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("speed"))); } double LocationInfo::bearing() const { return qdbus_cast<double>(mPriv->location.value( QLatin1String("bearing"))); } QDateTime LocationInfo::timestamp() const { // FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690 qlonglong t = qdbus_cast<qlonglong>(mPriv->location.value( QLatin1String("timestamp"))); if (t != 0) { return QDateTime::fromTime_t((uint) t); } return QDateTime(); } QVariantMap LocationInfo::allDetails() const { return mPriv->location; } void LocationInfo::updateData(const QVariantMap &location) { if (!isValid()) { mPriv = new Private; } mPriv->location = location; } } // Tp <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unoedsrc.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: svesik $ $Date: 2004-04-21 14:14:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef GCC #pragma hdrstop #endif #ifndef _SFXBRDCST_HXX #include <svtools/brdcst.hxx> #endif #include "unoedsrc.hxx" //------------------------------------------------------------------------ SvxTextForwarder::~SvxTextForwarder() { } //------------------------------------------------------------------------ SvxViewForwarder::~SvxViewForwarder() { } //------------------------------------------------------------------------ SvxEditSource::~SvxEditSource() { } SvxViewForwarder* SvxEditSource::GetViewForwarder() { return NULL; } SvxEditViewForwarder* SvxEditSource::GetEditViewForwarder( sal_Bool bCreate ) { return NULL; } SfxBroadcaster& SvxEditSource::GetBroadcaster() const { DBG_ERROR("SvxEditSource::GetBroadcaster called for implementation missing this feature!"); static SfxBroadcaster aBroadcaster; return aBroadcaster; } <commit_msg>INTEGRATION: CWS presentationengine01 (1.7.162); FILE MERGED 2004/09/22 11:55:13 cl 1.7.162.1: added support for unique interfaces for paragraphs<commit_after>/************************************************************************* * * $RCSfile: unoedsrc.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2004-11-26 18:16:27 $ * * 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 GCC #pragma hdrstop #endif #ifndef _SFXBRDCST_HXX #include <svtools/brdcst.hxx> #endif #include "unoedsrc.hxx" //------------------------------------------------------------------------ void SvxEditSource::addRange( SvxUnoTextRangeBase* pNewRange ) { } //------------------------------------------------------------------------ void SvxEditSource::removeRange( SvxUnoTextRangeBase* pOldRange ) { } //------------------------------------------------------------------------ const SvxUnoTextRangeBaseList& SvxEditSource::getRanges() const { static SvxUnoTextRangeBaseList gList; return gList; } //------------------------------------------------------------------------ SvxTextForwarder::~SvxTextForwarder() { } //------------------------------------------------------------------------ SvxViewForwarder::~SvxViewForwarder() { } //------------------------------------------------------------------------ SvxEditSource::~SvxEditSource() { } SvxViewForwarder* SvxEditSource::GetViewForwarder() { return NULL; } SvxEditViewForwarder* SvxEditSource::GetEditViewForwarder( sal_Bool bCreate ) { return NULL; } SfxBroadcaster& SvxEditSource::GetBroadcaster() const { DBG_ERROR("SvxEditSource::GetBroadcaster called for implementation missing this feature!"); static SfxBroadcaster aBroadcaster; return aBroadcaster; } <|endoftext|>
<commit_before>/* This program tests class LinkedList */ #include<iostream> #include<vector> #include "linkedlist.h" // tests insertion void testInsert(){ std::cout<<"Test Insert\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // display linked list ll.print(); // insert 100 at end ll.insertLast(100); // display linked list ll.print(); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); ll.valueAt(-500); } // tests valueAt() and getLength() void testB(){ std::cout<<"Test B\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // insert 100 at end ll.insertLast(1000); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); std::cout<<"Length: "<<ll.getLength(); for(int i=0;i<ll.getLength();i++){ std::cout<<"\nValut at "<<i<<": "<<ll.valueAt(i); } ll.valueAt(500); } // tests deletion void testDelete(){ std::cout<<"Test Delete\n"; // define vector of values std::vector<int> values = {20,18,16,15,14,12,10,8,6,4,1,2,0}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); std::cout<<"\nDelete index : 2\n"; ll.delete_node(2); ll.print(); std::cout<<"\nDelete index: 0\n"; ll.delete_node(0); ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); } // tests reverse void testReverse(){ std::cout<<"Test Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); for(int i=0;i<7;i++) ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); } // tests pairwiseReverse void testpairwiseReverse(){ std::cout<<"Test Pairwise Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); for(int i=0;i<6;i++) ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); } // tests hasLoop void testHasLoop(){ LinkedList l1(1); if(l1.hasLoop()!=nullptr) std::cout<<"\nl1 has loop"; else std::cout<<"\nl1 does not have loop"; LinkedList l2; for(int i=1;i<=5;i++) l2.insertLast(i); if(l2.hasLoop()!=nullptr) std::cout<<"\nl2 has loop"; else std::cout<<"\nl2 does not have loop"; LinkedList l3(2); if(l3.hasLoop()!=nullptr) std::cout<<"\nl3 has loop"; else std::cout<<"\nl3 does not have loop"; LinkedList l4(3); if(l4.hasLoop()!=nullptr) std::cout<<"\nl4 has loop"; else std::cout<<"\nl4 does not have loop"; } //tests remove loop void testRemoveLoop(){ LinkedList l1(1); Node * loopnode1 = l1.hasLoop(); if(loopnode1!=nullptr) std::cout<<"\nl1 has loop"; else std::cout<<"\nl1 does not have loop"; l1.removeLoop(loopnode1); loopnode1 = l1.hasLoop(); if(loopnode1!=nullptr) std::cout<<"\nl1 has loop"; else std::cout<<"\nl1 does not have loop"; l1.print(); LinkedList l3(2); Node * loopnode3 = l3.hasLoop(); if(loopnode3!=nullptr) std::cout<<"\nl3 has loop"; else std::cout<<"\nl3 does not have loop"; l3.removeLoop(loopnode3); loopnode3 = l3.hasLoop(); if(loopnode3!=nullptr) std::cout<<"\nl3 has loop"; else std::cout<<"\nl3 does not have loop"; l3.print(); LinkedList l4(3); Node *loopnode4 = l4.hasLoop(); if(loopnode4!=nullptr) std::cout<<"\nl4 has loop"; else std::cout<<"\nl4 does not have loop"; l4.removeLoop(loopnode4); loopnode4 = l4.hasLoop(); if(loopnode4!=nullptr) std::cout<<"\nl4 has loop"; else std::cout<<"\nl4 does not have loop"; l4.print(); } // test find length void testFindLength(){ std::cout<<"Test Find length\n"; // define vector of values std::vector<int> values = {9,8,7,6,5,4,3,2,1}; // create linked list LinkedList ll; std::cout<<"\nList: "; ll.print(); std::cout<<"Length: "<<ll.findLength()<<"\n"; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); std::cout<<"\nList: "; ll.print(); std::cout<<"Length: "<<ll.findLength()<<"\n"; } } int main(){ // test insert testInsert(); // test B testB(); // test delete testDelete(); // test reverse testReverse(); // test pairwise reverse testpairwiseReverse(); // test hasLoop testHasLoop(); // test remove loop testRemoveLoop(); // test find length testFindLength(); return 0; } <commit_msg>Add test case for swapkth() method<commit_after>/* This program tests class LinkedList */ #include<iostream> #include<vector> #include "linkedlist.h" // tests insertion void testInsert(){ std::cout<<"Test Insert\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // display linked list ll.print(); // insert 100 at end ll.insertLast(100); // display linked list ll.print(); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); ll.valueAt(-500); } // tests valueAt() and getLength() void testB(){ std::cout<<"Test B\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // insert 100 at end ll.insertLast(1000); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); std::cout<<"Length: "<<ll.getLength(); for(int i=0;i<ll.getLength();i++){ std::cout<<"\nValut at "<<i<<": "<<ll.valueAt(i); } ll.valueAt(500); } // tests deletion void testDelete(){ std::cout<<"Test Delete\n"; // define vector of values std::vector<int> values = {20,18,16,15,14,12,10,8,6,4,1,2,0}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); std::cout<<"\nDelete index : 2\n"; ll.delete_node(2); ll.print(); std::cout<<"\nDelete index: 0\n"; ll.delete_node(0); ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); } // tests reverse void testReverse(){ std::cout<<"Test Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); for(int i=0;i<7;i++) ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); } // tests pairwiseReverse void testpairwiseReverse(){ std::cout<<"Test Pairwise Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); for(int i=0;i<6;i++) ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); } // tests hasLoop void testHasLoop(){ LinkedList l1(1); if(l1.hasLoop()!=nullptr) std::cout<<"\nl1 has loop"; else std::cout<<"\nl1 does not have loop"; LinkedList l2; for(int i=1;i<=5;i++) l2.insertLast(i); if(l2.hasLoop()!=nullptr) std::cout<<"\nl2 has loop"; else std::cout<<"\nl2 does not have loop"; LinkedList l3(2); if(l3.hasLoop()!=nullptr) std::cout<<"\nl3 has loop"; else std::cout<<"\nl3 does not have loop"; LinkedList l4(3); if(l4.hasLoop()!=nullptr) std::cout<<"\nl4 has loop"; else std::cout<<"\nl4 does not have loop"; } //tests remove loop void testRemoveLoop(){ LinkedList l1(1); Node * loopnode1 = l1.hasLoop(); if(loopnode1!=nullptr) std::cout<<"\nl1 has loop"; else std::cout<<"\nl1 does not have loop"; l1.removeLoop(loopnode1); loopnode1 = l1.hasLoop(); if(loopnode1!=nullptr) std::cout<<"\nl1 has loop"; else std::cout<<"\nl1 does not have loop"; l1.print(); LinkedList l3(2); Node * loopnode3 = l3.hasLoop(); if(loopnode3!=nullptr) std::cout<<"\nl3 has loop"; else std::cout<<"\nl3 does not have loop"; l3.removeLoop(loopnode3); loopnode3 = l3.hasLoop(); if(loopnode3!=nullptr) std::cout<<"\nl3 has loop"; else std::cout<<"\nl3 does not have loop"; l3.print(); LinkedList l4(3); Node *loopnode4 = l4.hasLoop(); if(loopnode4!=nullptr) std::cout<<"\nl4 has loop"; else std::cout<<"\nl4 does not have loop"; l4.removeLoop(loopnode4); loopnode4 = l4.hasLoop(); if(loopnode4!=nullptr) std::cout<<"\nl4 has loop"; else std::cout<<"\nl4 does not have loop"; l4.print(); } // test find length void testFindLength(){ std::cout<<"Test Find length\n"; // define vector of values std::vector<int> values = {9,8,7,6,5,4,3,2,1}; // create linked list LinkedList ll; std::cout<<"\nList: "; ll.print(); std::cout<<"Length: "<<ll.findLength()<<"\n"; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); std::cout<<"\nList: "; ll.print(); std::cout<<"Length: "<<ll.findLength()<<"\n"; } } // test single swap kth void testSwapKth(LinkedList ll, int k){ std::cout<<"k = "<<k<<"\n"; std::cout<<"Before: "; ll.print(); ll.swapKth(k); std::cout<<"After: "; ll.print(); } // tests swapKth() void testSwapKth(){ std::cout<<"Test Swap Kth\n"; LinkedList ll; testSwapKth(ll,2); ll.insertLast(10); testSwapKth(ll,1); ll.insertLast(15); testSwapKth(ll,1); testSwapKth(ll,2); ll.insertLast(20); testSwapKth(ll,1); testSwapKth(ll,2); testSwapKth(ll,3); testSwapKth(ll,4); for(int i=25;i<=45;i+=5) ll.insertLast(i); testSwapKth(ll,1); testSwapKth(ll,2); testSwapKth(ll,4); testSwapKth(ll,5); testSwapKth(ll,8); } int main(){ // test insert testInsert(); // test B testB(); // test delete testDelete(); // test reverse testReverse(); // test pairwise reverse testpairwiseReverse(); // test hasLoop testHasLoop(); // test remove loop testRemoveLoop(); // test find length testFindLength(); testSwapKth(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unoforou.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: cl $ $Date: 2001-08-22 14:30:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif #include <svtools/itemset.hxx> #include <editeng.hxx> #include <outliner.hxx> #ifndef _SFXPOOLITEM_HXX #include <svtools/poolitem.hxx> #endif #ifndef _SV_WRKWIN_HXX //autogen #include <vcl/wrkwin.hxx> #endif #ifndef _EEITEM_HXX //autogen #include "eeitem.hxx" #endif #include "unoforou.hxx" #include "unofored.hxx" //------------------------------------------------------------------------ SvxOutlinerForwarder::SvxOutlinerForwarder( Outliner& rOutl ) : rOutliner( rOutl ) { } SvxOutlinerForwarder::~SvxOutlinerForwarder() { // der Outliner muss ggf. von aussen geloescht werden } USHORT SvxOutlinerForwarder::GetParagraphCount() const { return (USHORT)rOutliner.GetParagraphCount(); } USHORT SvxOutlinerForwarder::GetTextLen( USHORT nParagraph ) const { return rOutliner.GetEditEngine().GetTextLen( nParagraph ); } String SvxOutlinerForwarder::GetText( const ESelection& rSel ) const { //! GetText(ESelection) sollte es wohl auch mal am Outliner geben // solange den Hack fuer die EditEngine uebernehmen: EditEngine* pEditEngine = (EditEngine*)&rOutliner.GetEditEngine(); return pEditEngine->GetText( rSel, LINEEND_LF ); } SfxItemSet SvxOutlinerForwarder::GetAttribs( const ESelection& rSel, BOOL bOnlyHardAttrib ) const { //! gibt's das nicht am Outliner ??? //! und warum ist GetAttribs an der EditEngine nicht const? EditEngine& rEditEngine = (EditEngine&)rOutliner.GetEditEngine(); SfxItemSet aSet( rEditEngine.GetAttribs( rSel, bOnlyHardAttrib ) ); SfxStyleSheet* pStyle = rEditEngine.GetStyleSheet( rSel.nStartPara ); if( pStyle ) aSet.SetParent( &(pStyle->GetItemSet() ) ); return aSet; } SfxItemSet SvxOutlinerForwarder::GetParaAttribs( USHORT nPara ) const { SfxItemSet aSet( rOutliner.GetParaAttribs( nPara ) ); EditEngine& rEditEngine = (EditEngine&)rOutliner.GetEditEngine(); SfxStyleSheet* pStyle = rEditEngine.GetStyleSheet( nPara ); if( pStyle ) aSet.SetParent( &(pStyle->GetItemSet() ) ); return aSet; } void SvxOutlinerForwarder::SetParaAttribs( USHORT nPara, const SfxItemSet& rSet ) { const SfxItemSet* pOldParent = rSet.GetParent(); if( pOldParent ) ((SfxItemSet*)&rSet)->SetParent( NULL ); rOutliner.SetParaAttribs( nPara, rSet ); if( pOldParent ) ((SfxItemSet*)&rSet)->SetParent( pOldParent ); } SfxItemPool* SvxOutlinerForwarder::GetPool() const { return rOutliner.GetEmptyItemSet().GetPool(); } void SvxOutlinerForwarder::GetPortions( USHORT nPara, SvUShorts& rList ) const { ((EditEngine&)rOutliner.GetEditEngine()).GetPortions( nPara, rList ); } void SvxOutlinerForwarder::QuickInsertText( const String& rText, const ESelection& rSel ) { if( rText.Len() == 0 ) { rOutliner.QuickDelete( rSel ); } else { rOutliner.QuickInsertText( rText, rSel ); } } void SvxOutlinerForwarder::QuickInsertLineBreak( const ESelection& rSel ) { rOutliner.QuickInsertLineBreak( rSel ); } void SvxOutlinerForwarder::QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ) { rOutliner.QuickInsertField( rFld, rSel ); } void SvxOutlinerForwarder::QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ) { rOutliner.QuickSetAttribs( rSet, rSel ); } XubString SvxOutlinerForwarder::CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor ) { return rOutliner.CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor ); } extern USHORT GetSvxEditEngineItemState( EditEngine& rEditEngine, const ESelection& rSel, USHORT nWhich ); USHORT SvxOutlinerForwarder::GetItemState( const ESelection& rSel, USHORT nWhich ) const { return GetSvxEditEngineItemState( (EditEngine&)rOutliner.GetEditEngine(), rSel, nWhich ); } USHORT SvxOutlinerForwarder::GetItemState( USHORT nPara, USHORT nWhich ) const { const SfxItemSet& rSet = rOutliner.GetParaAttribs( nPara ); return rSet.GetItemState( nWhich ); } //------------------------------------------------------------------------ <commit_msg>#90330# added a cache for sequentiel attrib access<commit_after>/************************************************************************* * * $RCSfile: unoforou.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: cl $ $Date: 2001-11-05 13:55:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif #include <svtools/itemset.hxx> #include <editeng.hxx> #include <outliner.hxx> #ifndef _SFXPOOLITEM_HXX #include <svtools/poolitem.hxx> #endif #ifndef _SV_WRKWIN_HXX //autogen #include <vcl/wrkwin.hxx> #endif #ifndef _EEITEM_HXX //autogen #include "eeitem.hxx" #endif #include "unoforou.hxx" #include "unofored.hxx" //------------------------------------------------------------------------ SvxOutlinerForwarder::SvxOutlinerForwarder( Outliner& rOutl ) : rOutliner( rOutl ), mpAttribsCache( NULL ), mpParaAttribsCache( NULL ) { } SvxOutlinerForwarder::~SvxOutlinerForwarder() { flushCache(); } USHORT SvxOutlinerForwarder::GetParagraphCount() const { return (USHORT)rOutliner.GetParagraphCount(); } USHORT SvxOutlinerForwarder::GetTextLen( USHORT nParagraph ) const { return rOutliner.GetEditEngine().GetTextLen( nParagraph ); } String SvxOutlinerForwarder::GetText( const ESelection& rSel ) const { //! GetText(ESelection) sollte es wohl auch mal am Outliner geben // solange den Hack fuer die EditEngine uebernehmen: EditEngine* pEditEngine = (EditEngine*)&rOutliner.GetEditEngine(); return pEditEngine->GetText( rSel, LINEEND_LF ); } SfxItemSet SvxOutlinerForwarder::GetAttribs( const ESelection& rSel, BOOL bOnlyHardAttrib ) const { if( mpAttribsCache && ( 0 == bOnlyHardAttrib ) ) { // have we the correct set in cache? if( ((SvxOutlinerForwarder*)this)->maAttribCacheSelection.IsEqual(rSel) ) { // yes! just return the cache return *mpAttribsCache; } else { // no, we need delete the old cache delete mpAttribsCache; mpAttribsCache = NULL; } } //! gibt's das nicht am Outliner ??? //! und warum ist GetAttribs an der EditEngine nicht const? EditEngine& rEditEngine = (EditEngine&)rOutliner.GetEditEngine(); SfxItemSet aSet( rEditEngine.GetAttribs( rSel, bOnlyHardAttrib ) ); if( 0 == bOnlyHardAttrib ) { mpAttribsCache = new SfxItemSet( aSet ); maAttribCacheSelection = rSel; } SfxStyleSheet* pStyle = rEditEngine.GetStyleSheet( rSel.nStartPara ); if( pStyle ) aSet.SetParent( &(pStyle->GetItemSet() ) ); return aSet; } SfxItemSet SvxOutlinerForwarder::GetParaAttribs( USHORT nPara ) const { if( mpParaAttribsCache ) { // have we the correct set in cache? if( nPara == mnParaAttribsCache ) { // yes! just return the cache return *mpParaAttribsCache; } else { // no, we need delete the old cache delete mpParaAttribsCache; mpParaAttribsCache = NULL; } } mpParaAttribsCache = new SfxItemSet( rOutliner.GetParaAttribs( nPara ) ); mnParaAttribsCache = nPara; EditEngine& rEditEngine = (EditEngine&)rOutliner.GetEditEngine(); SfxStyleSheet* pStyle = rEditEngine.GetStyleSheet( nPara ); if( pStyle ) mpParaAttribsCache->SetParent( &(pStyle->GetItemSet() ) ); return *mpParaAttribsCache; } void SvxOutlinerForwarder::SetParaAttribs( USHORT nPara, const SfxItemSet& rSet ) { flushCache(); const SfxItemSet* pOldParent = rSet.GetParent(); if( pOldParent ) ((SfxItemSet*)&rSet)->SetParent( NULL ); rOutliner.SetParaAttribs( nPara, rSet ); if( pOldParent ) ((SfxItemSet*)&rSet)->SetParent( pOldParent ); } SfxItemPool* SvxOutlinerForwarder::GetPool() const { return rOutliner.GetEmptyItemSet().GetPool(); } void SvxOutlinerForwarder::GetPortions( USHORT nPara, SvUShorts& rList ) const { ((EditEngine&)rOutliner.GetEditEngine()).GetPortions( nPara, rList ); } void SvxOutlinerForwarder::QuickInsertText( const String& rText, const ESelection& rSel ) { flushCache(); if( rText.Len() == 0 ) { rOutliner.QuickDelete( rSel ); } else { rOutliner.QuickInsertText( rText, rSel ); } } void SvxOutlinerForwarder::QuickInsertLineBreak( const ESelection& rSel ) { flushCache(); rOutliner.QuickInsertLineBreak( rSel ); } void SvxOutlinerForwarder::QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ) { flushCache(); rOutliner.QuickInsertField( rFld, rSel ); } void SvxOutlinerForwarder::QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ) { flushCache(); rOutliner.QuickSetAttribs( rSet, rSel ); } XubString SvxOutlinerForwarder::CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor ) { return rOutliner.CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor ); } extern USHORT GetSvxEditEngineItemState( EditEngine& rEditEngine, const ESelection& rSel, USHORT nWhich ); USHORT SvxOutlinerForwarder::GetItemState( const ESelection& rSel, USHORT nWhich ) const { return GetSvxEditEngineItemState( (EditEngine&)rOutliner.GetEditEngine(), rSel, nWhich ); } USHORT SvxOutlinerForwarder::GetItemState( USHORT nPara, USHORT nWhich ) const { const SfxItemSet& rSet = rOutliner.GetParaAttribs( nPara ); return rSet.GetItemState( nWhich ); } void SvxOutlinerForwarder::flushCache() { if( mpAttribsCache ) { delete mpAttribsCache; mpAttribsCache = NULL; } if( mpParaAttribsCache ) { delete mpParaAttribsCache; mpParaAttribsCache = NULL; } } //------------------------------------------------------------------------ <|endoftext|>
<commit_before>/*! \file ws.cpp \brief WebSocket C++ Library implementation \author Ivan Shynkarenka \date 22.05.2019 \copyright MIT License */ #include "server/ws/ws.h" #include "string/encoding.h" #include "string/format.h" #include <algorithm> #include <openssl/sha.h> namespace CppServer { namespace WS { bool WebSocket::PerformClientUpgrade(const HTTP::HTTPResponse& response, const CppCommon::UUID& id) { if (response.status() != 101) return false; bool error = false; bool accept = false; bool connection = false; bool upgrade = false; // Validate WebSocket handshake headers for (size_t i = 0; i < response.headers(); ++i) { auto header = response.header(i); auto key = std::get<0>(header); auto value = std::get<1>(header); if (key == "Connection") { if (value != "Upgrade") { error = true; onWSError("Invalid WebSocket handshaked response: 'Connection' header value must be 'Upgrade'"); break; } connection = true; } else if (key == "Upgrade") { if (value != "websocket") { error = true; onWSError("Invalid WebSocket handshaked response: 'Upgrade' header value must be 'websocket'"); break; } upgrade = true; } else if (key == "Sec-WebSocket-Accept") { // Calculate the original WebSocket hash std::string wskey = CppCommon::Encoding::Base64Encode(id.string()) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; char wshash[SHA_DIGEST_LENGTH]; SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash); // Get the received WebSocket hash wskey = CppCommon::Encoding::Base64Decode(value); // Compare original and received hashes if (std::strncmp(wskey.data(), wshash, std::min(wskey.size(), sizeof(wshash))) != 0) { error = true; onWSError("Invalid WebSocket handshaked response: 'Sec-WebSocket-Accept' value validation failed"); break; } accept = true; } } // Failed to perfrom WebSocket handshake if (!accept || !connection || !upgrade) { if (!error) onWSError("Invalid WebSocket response"); return false; } // WebSocket successfully handshaked! _ws_handshaked = true; *((uint32_t*)_ws_send_mask) = rand(); onWSConnected(response); return true; } bool WebSocket::PerformServerUpgrade(const HTTP::HTTPRequest& request, HTTP::HTTPResponse& response) { if (request.method() != "GET") return false; bool error = false; bool connection = false; bool upgrade = false; bool ws_key = false; bool ws_version = false; std::string accept; // Validate WebSocket handshake headers for (size_t i = 0; i < request.headers(); ++i) { auto header = request.header(i); auto key = std::get<0>(header); auto value = std::get<1>(header); if (key == "Connection") { if (value != "Upgrade") { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Connection' header value must be 'Upgrade'", 400); break; } connection = true; } else if (key == "Upgrade") { if (value != "websocket") { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Upgrade' header value must be 'websocket'", 400); break; } upgrade = true; } else if (key == "Sec-WebSocket-Key") { if (value.empty()) { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Sec-WebSocket-Key' header value must be non empty", 400); break; } // Calculate WebSocket accept value std::string wskey = std::string(value) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; char wshash[SHA_DIGEST_LENGTH]; SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash); accept = CppCommon::Encoding::Base64Encode(std::string(wshash, sizeof(wshash))); ws_key = true; } else if (key == "Sec-WebSocket-Version") { if (value != "13") { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Sec-WebSocket-Version' header value must be '13'", 400); break; } ws_version = true; } } // Filter out non WebSocket handshake requests if (!connection && !upgrade && !ws_key && !ws_version) return false; // Failed to perfrom WebSocket handshake if (!connection || !upgrade || !ws_key || !ws_version) { if (!error) response.MakeErrorResponse("Invalid WebSocket response", 400); SendResponse(response); return false; } // Prepare WebSocket upgrade success response response.Clear(); response.SetBegin(101); response.SetHeader("Connection", "Upgrade"); response.SetHeader("Upgrade", "websocket"); response.SetHeader("Sec-WebSocket-Accept", accept); response.SetBody(); // Validate WebSocket upgrade request and response if (!onWSConnecting(request, response)) return false; // Send WebSocket upgrade response SendResponse(response); // WebSocket successfully handshaked! _ws_handshaked = true; *((uint32_t*)_ws_send_mask) = 0; onWSConnected(request); return true; } void WebSocket::PrepareSendFrame(uint8_t opcode, bool mask, const void* buffer, size_t size, int status) { // Clear the previous WebSocket send buffer _ws_send_buffer.clear(); // Append WebSocket frame opcode _ws_send_buffer.push_back(opcode); // Append WebSocket frame size if (size <= 125) _ws_send_buffer.push_back((size & 0xFF) | (mask ? 0x80 : 0)); else if (size <= 65535) { _ws_send_buffer.push_back(126 | (mask ? 0x80 : 0)); _ws_send_buffer.push_back((size >> 8) & 0xFF); _ws_send_buffer.push_back(size & 0xFF); } else { _ws_send_buffer.push_back(127 | (mask ? 0x80 : 0)); for (int i = 7; i >= 0; --i) _ws_send_buffer.push_back((size >> (8 * i)) & 0xFF); } if (mask) { // Append WebSocket frame mask _ws_send_buffer.push_back(_ws_send_mask[0]); _ws_send_buffer.push_back(_ws_send_mask[1]); _ws_send_buffer.push_back(_ws_send_mask[2]); _ws_send_buffer.push_back(_ws_send_mask[3]); } // Resize WebSocket frame buffer size_t offset = _ws_send_buffer.size(); _ws_send_buffer.resize(offset + size); // Mask WebSocket frame content const uint8_t* data = (const uint8_t*)buffer; for (size_t i = 0; i < size; ++i) _ws_send_buffer[offset + i] = data[i] ^ _ws_send_mask[i % 4]; } void WebSocket::PrepareReceiveFrame(const void* buffer, size_t size) { const uint8_t* data = (const uint8_t*)buffer; // Clear received data after WebSocket frame was processed if (_ws_received) { _ws_received = false; _ws_header_size = 0; _ws_payload_size = 0; _ws_receive_buffer.clear(); *((uint32_t*)_ws_receive_mask) = 0; } while (size > 0) { // Clear received data after WebSocket frame was processed if (_ws_received) { _ws_received = false; _ws_header_size = 0; _ws_payload_size = 0; _ws_receive_buffer.clear(); *((uint32_t*)_ws_receive_mask) = 0; } // Prepare WebSocket frame opcode and mask flag if (_ws_receive_buffer.size() < 2) { for (size_t i = 0; i < 2; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); } } uint8_t opcode = _ws_receive_buffer[0] & 0x0F; [[maybe_unused]] bool fin = ((_ws_receive_buffer[0] >> 7) & 0x01) != 0; bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0; size_t payload = _ws_receive_buffer[1] & (~0x80); // Prepare WebSocket frame size if (payload <= 125) { _ws_header_size = 2 + (mask ? 4 : 0); _ws_payload_size = payload; _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size); } else if (payload == 126) { if (_ws_receive_buffer.size() < 4) { for (size_t i = 0; i < 2; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); } } payload = (((size_t)_ws_receive_buffer[2] << 8) | ((size_t)_ws_receive_buffer[3] << 0)); _ws_header_size = 4 + (mask ? 4 : 0); _ws_payload_size = payload; _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size); } else if (payload == 127) { if (_ws_receive_buffer.size() < 10) { for (size_t i = 0; i < 8; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); } } payload = (((size_t)_ws_receive_buffer[2] << 56) | ((size_t)_ws_receive_buffer[3] << 48) | ((size_t)_ws_receive_buffer[4] << 40) | ((size_t)_ws_receive_buffer[5] << 32) | ((size_t)_ws_receive_buffer[6] << 24) | ((size_t)_ws_receive_buffer[7] << 16) | ((size_t)_ws_receive_buffer[8] << 8) | ((size_t)_ws_receive_buffer[9] << 0)); _ws_header_size = 10 + (mask ? 4 : 0); _ws_payload_size = payload; _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size); } // Prepare WebSocket frame mask if (mask) { if (_ws_receive_buffer.size() < _ws_header_size) { for (size_t i = 0; i < 4; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); _ws_receive_mask[i] = *data; } } } size_t total = _ws_header_size + _ws_payload_size; size_t length = std::min(total - _ws_receive_buffer.size(), size); // Prepare WebSocket frame payload _ws_receive_buffer.insert(_ws_receive_buffer.end(), data, data + length); data += length; size -= length; // Process WebSocket frame if (_ws_receive_buffer.size() == total) { size_t offset = _ws_header_size; // Unmask WebSocket frame content if (mask) for (size_t i = 0; i < _ws_payload_size; ++i) _ws_receive_buffer[offset + i] ^= _ws_receive_mask[i % 4]; _ws_received = true; if ((opcode & WS_PING) == WS_PING) { // Call the WebSocket ping handler onWSPing(_ws_receive_buffer.data() + offset, _ws_payload_size); } else if ((opcode & WS_PONG) == WS_PONG) { // Call the WebSocket pong handler onWSPong(_ws_receive_buffer.data() + offset, _ws_payload_size); } else if ((opcode & WS_CLOSE) == WS_CLOSE) { // Call the WebSocket close handler onWSClose(_ws_receive_buffer.data() + offset, _ws_payload_size); } else if (((opcode & WS_TEXT) == WS_TEXT) || ((opcode & WS_BINARY) == WS_BINARY)) { // Call the WebSocket received handler onWSReceived(_ws_receive_buffer.data() + offset, _ws_payload_size); } } } } size_t WebSocket::RequiredReceiveFrameSize() { if (_ws_received) return 0; // Required WebSocket frame opcode and mask flag if (_ws_receive_buffer.size() < 2) return 2 - _ws_receive_buffer.size(); bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0; size_t payload = _ws_receive_buffer[1] & (~0x80); // Required WebSocket frame size if ((payload == 126) && (_ws_receive_buffer.size() < 4)) return 4 - _ws_receive_buffer.size(); if ((payload == 127) && (_ws_receive_buffer.size() < 10)) return 10 - _ws_receive_buffer.size(); // Required WebSocket frame mask if ((mask) && (_ws_receive_buffer.size() < _ws_header_size)) return _ws_header_size - _ws_receive_buffer.size(); // Required WebSocket frame payload return _ws_header_size + _ws_payload_size - _ws_receive_buffer.size(); } void WebSocket::ClearWSBuffers() { _ws_received = false; _ws_header_size = 0; _ws_payload_size = 0; _ws_receive_buffer.clear(); *((uint32_t*)_ws_receive_mask) = 0; std::scoped_lock locker(_ws_send_lock); _ws_send_buffer.clear(); *((uint32_t*)_ws_send_mask) = 0; } } // namespace WS } // namespace CppServer <commit_msg>Fixed WebSocket connection for Firefox browser<commit_after>/*! \file ws.cpp \brief WebSocket C++ Library implementation \author Ivan Shynkarenka \date 22.05.2019 \copyright MIT License */ #include "server/ws/ws.h" #include "string/encoding.h" #include "string/format.h" #include <algorithm> #include <openssl/sha.h> namespace CppServer { namespace WS { bool WebSocket::PerformClientUpgrade(const HTTP::HTTPResponse& response, const CppCommon::UUID& id) { if (response.status() != 101) return false; bool error = false; bool accept = false; bool connection = false; bool upgrade = false; // Validate WebSocket handshake headers for (size_t i = 0; i < response.headers(); ++i) { auto header = response.header(i); auto key = std::get<0>(header); auto value = std::get<1>(header); if (key == "Connection") { if (value != "Upgrade") { error = true; onWSError("Invalid WebSocket handshaked response: 'Connection' header value must be 'Upgrade'"); break; } connection = true; } else if (key == "Upgrade") { if (value != "websocket") { error = true; onWSError("Invalid WebSocket handshaked response: 'Upgrade' header value must be 'websocket'"); break; } upgrade = true; } else if (key == "Sec-WebSocket-Accept") { // Calculate the original WebSocket hash std::string wskey = CppCommon::Encoding::Base64Encode(id.string()) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; char wshash[SHA_DIGEST_LENGTH]; SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash); // Get the received WebSocket hash wskey = CppCommon::Encoding::Base64Decode(value); // Compare original and received hashes if (std::strncmp(wskey.data(), wshash, std::min(wskey.size(), sizeof(wshash))) != 0) { error = true; onWSError("Invalid WebSocket handshaked response: 'Sec-WebSocket-Accept' value validation failed"); break; } accept = true; } } // Failed to perfrom WebSocket handshake if (!accept || !connection || !upgrade) { if (!error) onWSError("Invalid WebSocket response"); return false; } // WebSocket successfully handshaked! _ws_handshaked = true; *((uint32_t*)_ws_send_mask) = rand(); onWSConnected(response); return true; } bool WebSocket::PerformServerUpgrade(const HTTP::HTTPRequest& request, HTTP::HTTPResponse& response) { if (request.method() != "GET") return false; bool error = false; bool connection = false; bool upgrade = false; bool ws_key = false; bool ws_version = false; std::string accept; // Validate WebSocket handshake headers for (size_t i = 0; i < request.headers(); ++i) { auto header = request.header(i); auto key = std::get<0>(header); auto value = std::get<1>(header); if (key == "Connection") { if ((value != "Upgrade") && (value != "keep-alive, Upgrade")) { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Connection' header value must be 'Upgrade' or 'keep-alive, Upgrade'", 400); break; } connection = true; } else if (key == "Upgrade") { if (value != "websocket") { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Upgrade' header value must be 'websocket'", 400); break; } upgrade = true; } else if (key == "Sec-WebSocket-Key") { if (value.empty()) { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Sec-WebSocket-Key' header value must be non empty", 400); break; } // Calculate WebSocket accept value std::string wskey = std::string(value) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; char wshash[SHA_DIGEST_LENGTH]; SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash); accept = CppCommon::Encoding::Base64Encode(std::string(wshash, sizeof(wshash))); ws_key = true; } else if (key == "Sec-WebSocket-Version") { if (value != "13") { error = true; response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Sec-WebSocket-Version' header value must be '13'", 400); break; } ws_version = true; } } // Filter out non WebSocket handshake requests if (!connection && !upgrade && !ws_key && !ws_version) return false; // Failed to perfrom WebSocket handshake if (!connection || !upgrade || !ws_key || !ws_version) { if (!error) response.MakeErrorResponse("Invalid WebSocket response", 400); SendResponse(response); return false; } // Prepare WebSocket upgrade success response response.Clear(); response.SetBegin(101); response.SetHeader("Connection", "Upgrade"); response.SetHeader("Upgrade", "websocket"); response.SetHeader("Sec-WebSocket-Accept", accept); response.SetBody(); // Validate WebSocket upgrade request and response if (!onWSConnecting(request, response)) return false; // Send WebSocket upgrade response SendResponse(response); // WebSocket successfully handshaked! _ws_handshaked = true; *((uint32_t*)_ws_send_mask) = 0; onWSConnected(request); return true; } void WebSocket::PrepareSendFrame(uint8_t opcode, bool mask, const void* buffer, size_t size, int status) { // Clear the previous WebSocket send buffer _ws_send_buffer.clear(); // Append WebSocket frame opcode _ws_send_buffer.push_back(opcode); // Append WebSocket frame size if (size <= 125) _ws_send_buffer.push_back((size & 0xFF) | (mask ? 0x80 : 0)); else if (size <= 65535) { _ws_send_buffer.push_back(126 | (mask ? 0x80 : 0)); _ws_send_buffer.push_back((size >> 8) & 0xFF); _ws_send_buffer.push_back(size & 0xFF); } else { _ws_send_buffer.push_back(127 | (mask ? 0x80 : 0)); for (int i = 7; i >= 0; --i) _ws_send_buffer.push_back((size >> (8 * i)) & 0xFF); } if (mask) { // Append WebSocket frame mask _ws_send_buffer.push_back(_ws_send_mask[0]); _ws_send_buffer.push_back(_ws_send_mask[1]); _ws_send_buffer.push_back(_ws_send_mask[2]); _ws_send_buffer.push_back(_ws_send_mask[3]); } // Resize WebSocket frame buffer size_t offset = _ws_send_buffer.size(); _ws_send_buffer.resize(offset + size); // Mask WebSocket frame content const uint8_t* data = (const uint8_t*)buffer; for (size_t i = 0; i < size; ++i) _ws_send_buffer[offset + i] = data[i] ^ _ws_send_mask[i % 4]; } void WebSocket::PrepareReceiveFrame(const void* buffer, size_t size) { const uint8_t* data = (const uint8_t*)buffer; // Clear received data after WebSocket frame was processed if (_ws_received) { _ws_received = false; _ws_header_size = 0; _ws_payload_size = 0; _ws_receive_buffer.clear(); *((uint32_t*)_ws_receive_mask) = 0; } while (size > 0) { // Clear received data after WebSocket frame was processed if (_ws_received) { _ws_received = false; _ws_header_size = 0; _ws_payload_size = 0; _ws_receive_buffer.clear(); *((uint32_t*)_ws_receive_mask) = 0; } // Prepare WebSocket frame opcode and mask flag if (_ws_receive_buffer.size() < 2) { for (size_t i = 0; i < 2; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); } } uint8_t opcode = _ws_receive_buffer[0] & 0x0F; [[maybe_unused]] bool fin = ((_ws_receive_buffer[0] >> 7) & 0x01) != 0; bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0; size_t payload = _ws_receive_buffer[1] & (~0x80); // Prepare WebSocket frame size if (payload <= 125) { _ws_header_size = 2 + (mask ? 4 : 0); _ws_payload_size = payload; _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size); } else if (payload == 126) { if (_ws_receive_buffer.size() < 4) { for (size_t i = 0; i < 2; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); } } payload = (((size_t)_ws_receive_buffer[2] << 8) | ((size_t)_ws_receive_buffer[3] << 0)); _ws_header_size = 4 + (mask ? 4 : 0); _ws_payload_size = payload; _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size); } else if (payload == 127) { if (_ws_receive_buffer.size() < 10) { for (size_t i = 0; i < 8; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); } } payload = (((size_t)_ws_receive_buffer[2] << 56) | ((size_t)_ws_receive_buffer[3] << 48) | ((size_t)_ws_receive_buffer[4] << 40) | ((size_t)_ws_receive_buffer[5] << 32) | ((size_t)_ws_receive_buffer[6] << 24) | ((size_t)_ws_receive_buffer[7] << 16) | ((size_t)_ws_receive_buffer[8] << 8) | ((size_t)_ws_receive_buffer[9] << 0)); _ws_header_size = 10 + (mask ? 4 : 0); _ws_payload_size = payload; _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size); } // Prepare WebSocket frame mask if (mask) { if (_ws_receive_buffer.size() < _ws_header_size) { for (size_t i = 0; i < 4; ++i, ++data, --size) { if (size == 0) return; _ws_receive_buffer.push_back(*data); _ws_receive_mask[i] = *data; } } } size_t total = _ws_header_size + _ws_payload_size; size_t length = std::min(total - _ws_receive_buffer.size(), size); // Prepare WebSocket frame payload _ws_receive_buffer.insert(_ws_receive_buffer.end(), data, data + length); data += length; size -= length; // Process WebSocket frame if (_ws_receive_buffer.size() == total) { size_t offset = _ws_header_size; // Unmask WebSocket frame content if (mask) for (size_t i = 0; i < _ws_payload_size; ++i) _ws_receive_buffer[offset + i] ^= _ws_receive_mask[i % 4]; _ws_received = true; if ((opcode & WS_PING) == WS_PING) { // Call the WebSocket ping handler onWSPing(_ws_receive_buffer.data() + offset, _ws_payload_size); } else if ((opcode & WS_PONG) == WS_PONG) { // Call the WebSocket pong handler onWSPong(_ws_receive_buffer.data() + offset, _ws_payload_size); } else if ((opcode & WS_CLOSE) == WS_CLOSE) { // Call the WebSocket close handler onWSClose(_ws_receive_buffer.data() + offset, _ws_payload_size); } else if (((opcode & WS_TEXT) == WS_TEXT) || ((opcode & WS_BINARY) == WS_BINARY)) { // Call the WebSocket received handler onWSReceived(_ws_receive_buffer.data() + offset, _ws_payload_size); } } } } size_t WebSocket::RequiredReceiveFrameSize() { if (_ws_received) return 0; // Required WebSocket frame opcode and mask flag if (_ws_receive_buffer.size() < 2) return 2 - _ws_receive_buffer.size(); bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0; size_t payload = _ws_receive_buffer[1] & (~0x80); // Required WebSocket frame size if ((payload == 126) && (_ws_receive_buffer.size() < 4)) return 4 - _ws_receive_buffer.size(); if ((payload == 127) && (_ws_receive_buffer.size() < 10)) return 10 - _ws_receive_buffer.size(); // Required WebSocket frame mask if ((mask) && (_ws_receive_buffer.size() < _ws_header_size)) return _ws_header_size - _ws_receive_buffer.size(); // Required WebSocket frame payload return _ws_header_size + _ws_payload_size - _ws_receive_buffer.size(); } void WebSocket::ClearWSBuffers() { _ws_received = false; _ws_header_size = 0; _ws_payload_size = 0; _ws_receive_buffer.clear(); *((uint32_t*)_ws_receive_mask) = 0; std::scoped_lock locker(_ws_send_lock); _ws_send_buffer.clear(); *((uint32_t*)_ws_send_mask) = 0; } } // namespace WS } // namespace CppServer <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief MTU サンプル @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2022 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/fixed_fifo.hpp" #include "common/sci_io.hpp" #include "common/cmt_mgr.hpp" #include "common/command.hpp" #include "common/mtu_io.hpp" #include "common/format.hpp" #include "common/input.hpp" namespace { #if defined(SIG_RX62N) #if defined(CQ_FRK) // FRK-RX62N(CQ 出版社) static const char* system_str_ = { "RX62N FRK-RX62N" }; static constexpr bool LED_ACTIVE = 0; typedef device::PORT<device::PORT1, device::bitpos::B5, LED_ACTIVE> LED; typedef device::SCI0 SCI_CH; #else // BlueBoard-RX62N_100pin static const char* system_str_ = { "RX62N BlueBoard-RX62N_100pin" }; static constexpr bool LED_ACTIVE = 0; typedef device::PORT<device::PORT0, device::bitpos::B5, LED_ACTIVE> LED; typedef device::SCI0 SCI_CH; #endif // See 'RX62x/port_map_mtu.hpp' J6_6 typedef device::MTU0 MTU_CH; #elif defined(SIG_RX24T) static const char* system_str_ = { "RX24T DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B0, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; #elif defined(SIG_RX64M) static const char* system_str_ = { "RX64M DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B7, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; #elif defined(SIG_RX71M) static const char* system_str_ = { "RX71M DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B7, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; #elif defined(SIG_RX65N) static const char* system_str_ = { "RX65N Envision Kit" }; typedef device::PORT<device::PORT7, device::bitpos::B0, false> LED; typedef device::SCI9 SCI_CH; #elif defined(SIG_RX66T) static const char* system_str_ = { "RX66T DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B0, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; #elif defined(SIG_RX72N) static const char* system_str_ = { "RX72N Envision Kit" }; typedef device::PORT<device::PORT4, device::bitpos::B0, false> LED; typedef device::SCI2 SCI_CH; #elif defined(SIG_RX72T) static const char* system_str_ = { "RX72T DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B1, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; #endif typedef utils::fixed_fifo<char, 512> RXB; // RX (受信) バッファの定義 typedef utils::fixed_fifo<char, 256> TXB; // TX (送信) バッファの定義 typedef device::sci_io<SCI_CH, RXB, TXB> SCI; // SCI ポートの第二候補を選択する場合 // typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::ORDER::SECOND> SCI; SCI sci_; typedef device::cmt_mgr<device::CMT0> CMT; CMT cmt_; typedef device::mtu_io<MTU_CH> MTU; MTU mtu_; typedef utils::command<256> CMD; CMD cmd_; } extern "C" { // syscalls.c から呼ばれる、標準出力(stdout, stderr) void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } // syscalls.c から呼ばれる、標準入力(stdin) char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::boost_master_clock(); LED::DIR = 1; LED::P = 0; { // タイマー設定(100Hz) uint8_t intr = 4; cmt_.start(100, intr); } { // SCI の開始 uint8_t intr = 2; uint32_t baud = 115200; sci_.start(baud, intr); // 標準では、8ビット、1ストップビットを選択 } auto clk = device::clock_profile::ICLK / 1'000'000; utils::format("\nStart MTU sample for '%s' %d[MHz]\n") % system_str_ % clk; { // MTU の開始(インターバルタイマー、トグル出力) uint32_t freq = 10'000; // 10KHz // if(!mtu_it_.start_normal(MTU_IT::CHANNEL::A, MTU_IT::OUTPUT::TOGGLE, freq)) { // if(!mtu_it_.start_pwm2(MTU_IT::CHANNEL::A, freq, MTU_IT::CHANNEL::D, MTU_IT::OUTPUT::LOW_TO_HIGH)) { static constexpr MTU::pwm_port_t pwmout[2] = { { MTU::CHANNEL::D, MTU::OUTPUT::LOW_TO_HIGH }, { MTU::CHANNEL::C, MTU::OUTPUT::HIGH_TO_LOW } }; if(!mtu_.start_pwm2(MTU::CHANNEL::A, freq, pwmout[0], pwmout[1])) { utils::format("MTU can't start...\n"); } } mtu_.set_pwm_duty(MTU::CHANNEL::D, 16384); mtu_.set_pwm_duty(MTU::CHANNEL::C, 16384); { // SCI/CMT/MTU の設定レポート表示 utils::format("SCI PCLK: %u\n") % SCI_CH::PCLK; utils::format("SCI Baud rate (set): %u\n") % sci_.get_baud_rate(); float rate = 1.0f - static_cast<float>(sci_.get_baud_rate()) / sci_.get_baud_rate(true); rate *= 100.0f; utils::format(" Baud rate (real): %u (%3.2f [%%])\n") % sci_.get_baud_rate(true) % rate; utils::format(" SEMR_BRME: %s\n") % utils::str::get_bool_text(SCI_CH::SEMR_BRME); utils::format(" SEMR_BGDM: %s\n") % utils::str::get_bool_text(SCI_CH::SEMR_BGDM); utils::format("CMT Timer (set): %d [Hz]\n") % cmt_.get_rate(); rate = 1.0f - static_cast<float>(cmt_.get_rate()) / cmt_.get_rate(true); rate *= 100.0f; utils::format(" Timer (real): %d [Hz] (%3.2f [%%])\n") % cmt_.get_rate(true) % rate; utils::format("MTU Interval Timer (set): %d [Hz]\n") % mtu_.get_rate(); rate = 1.0f - static_cast<float>(mtu_.get_rate()) / mtu_.get_rate(true); rate *= 100.0f; utils::format(" Interval Timer (real): %d [Hz] (%3.2f [%%])\n") % mtu_.get_rate(true) % rate; } cmd_.set_prompt("# "); uint8_t cnt = 0; while(1) { cmt_.sync(); if(cmd_.service()) { uint32_t cmdn = cmd_.get_words(); uint32_t n = 0; while(n < cmdn) { char tmp[256]; if(cmd_.get_word(n, tmp, sizeof(tmp))) { utils::format("Param%d: '%s'\n") % n % tmp; } ++n; } } ++cnt; if(cnt >= 50) { cnt = 0; } if(cnt < 25) { LED::P = 0; } else { LED::P = 1; } } } <commit_msg>Add: add new microcontroller<commit_after>//=====================================================================// /*! @file @brief MTU サンプル @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2022 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/fixed_fifo.hpp" #include "common/sci_io.hpp" #include "common/cmt_mgr.hpp" #include "common/command.hpp" #include "common/mtu_io.hpp" #include "common/format.hpp" #include "common/input.hpp" namespace { #if defined(SIG_RX62N) #if defined(CQ_FRK) // FRK-RX62N(CQ 出版社) static const char* system_str_ = { "RX62N FRK-RX62N" }; static constexpr bool LED_ACTIVE = 0; typedef device::PORT<device::PORT1, device::bitpos::B5, LED_ACTIVE> LED; typedef device::SCI0 SCI_CH; #else // BlueBoard-RX62N_100pin static const char* system_str_ = { "RX62N BlueBoard-RX62N_100pin" }; static constexpr bool LED_ACTIVE = 0; typedef device::PORT<device::PORT0, device::bitpos::B5, LED_ACTIVE> LED; typedef device::SCI0 SCI_CH; #endif // See 'RX62x/port_map_mtu.hpp' J6_6 typedef device::MTU0 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIRST; #elif defined(SIG_RX24T) static const char* system_str_ = { "RX24T DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B0, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIRST; #elif defined(SIG_RX64M) static const char* system_str_ = { "RX64M DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B7, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIRST; #elif defined(SIG_RX71M) static const char* system_str_ = { "RX71M DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B7, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIRST; #elif defined(SIG_RX65N) static const char* system_str_ = { "RX65N Envision Kit" }; typedef device::PORT<device::PORT7, device::bitpos::B0, false> LED; typedef device::SCI9 SCI_CH; // CN13 (1): PD1_AN109_IRQ1 (MTIOC4B) typedef device::MTU4 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIFTH; #elif defined(SIG_RX66T) static const char* system_str_ = { "RX66T DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B0, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIRST; #elif defined(SIG_RX72N) static const char* system_str_ = { "RX72N Envision Kit" }; typedef device::PORT<device::PORT4, device::bitpos::B0, false> LED; typedef device::SCI2 SCI_CH; // Pmod2 (8): PD1_RESET (MTIOC4B) typedef device::MTU4 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIFTH; #elif defined(SIG_RX72T) static const char* system_str_ = { "RX72T DIY" }; typedef device::PORT<device::PORT0, device::bitpos::B1, false> LED; typedef device::SCI1 SCI_CH; typedef device::MTU0 MTU_CH; static constexpr auto MTU_ORDER = device::port_map_mtu::ORDER::FIRST; #endif typedef utils::fixed_fifo<char, 512> RXB; // RX (受信) バッファの定義 typedef utils::fixed_fifo<char, 256> TXB; // TX (送信) バッファの定義 typedef device::sci_io<SCI_CH, RXB, TXB> SCI; // SCI ポートの第二候補を選択する場合 // typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::ORDER::SECOND> SCI; SCI sci_; typedef device::cmt_mgr<device::CMT0> CMT; CMT cmt_; typedef device::mtu_io<MTU_CH, utils::null_task, utils::null_task, MTU_ORDER> MTU; MTU mtu_; typedef utils::command<256> CMD; CMD cmd_; } extern "C" { // syscalls.c から呼ばれる、標準出力(stdout, stderr) void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } // syscalls.c から呼ばれる、標準入力(stdin) char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::boost_master_clock(); LED::DIR = 1; LED::P = 0; { // タイマー設定(100Hz) uint8_t intr = 4; cmt_.start(100, intr); } { // SCI の開始 uint8_t intr = 2; uint32_t baud = 115200; sci_.start(baud, intr); // 標準では、8ビット、1ストップビットを選択 } auto clk = device::clock_profile::ICLK / 1'000'000; utils::format("\nStart MTU sample for '%s' %d[MHz]\n") % system_str_ % clk; { // MTU の開始(インターバルタイマー、トグル出力) uint32_t freq = 10'000; // 10KHz // if(!mtu_it_.start_normal(MTU_IT::CHANNEL::A, MTU_IT::OUTPUT::TOGGLE, freq)) { // if(!mtu_it_.start_pwm2(MTU_IT::CHANNEL::A, freq, MTU_IT::CHANNEL::D, MTU_IT::OUTPUT::LOW_TO_HIGH)) { static constexpr MTU::pwm_port_t pwmout[2] = { { MTU::CHANNEL::D, MTU::OUTPUT::LOW_TO_HIGH }, { MTU::CHANNEL::C, MTU::OUTPUT::HIGH_TO_LOW } }; if(!mtu_.start_pwm2(MTU::CHANNEL::A, freq, pwmout[0], pwmout[1])) { utils::format("MTU can't start...\n"); } } mtu_.set_pwm_duty(MTU::CHANNEL::D, 16384); mtu_.set_pwm_duty(MTU::CHANNEL::C, 16384); { // SCI/CMT/MTU の設定レポート表示 utils::format("SCI PCLK: %u\n") % SCI_CH::PCLK; utils::format("SCI Baud rate (set): %u\n") % sci_.get_baud_rate(); float rate = 1.0f - static_cast<float>(sci_.get_baud_rate()) / sci_.get_baud_rate(true); rate *= 100.0f; utils::format(" Baud rate (real): %u (%3.2f [%%])\n") % sci_.get_baud_rate(true) % rate; utils::format(" SEMR_BRME: %s\n") % utils::str::get_bool_text(SCI_CH::SEMR_BRME); utils::format(" SEMR_BGDM: %s\n") % utils::str::get_bool_text(SCI_CH::SEMR_BGDM); utils::format("CMT Timer (set): %d [Hz]\n") % cmt_.get_rate(); rate = 1.0f - static_cast<float>(cmt_.get_rate()) / cmt_.get_rate(true); rate *= 100.0f; utils::format(" Timer (real): %d [Hz] (%3.2f [%%])\n") % cmt_.get_rate(true) % rate; utils::format("MTU Interval Timer (set): %d [Hz]\n") % mtu_.get_rate(); rate = 1.0f - static_cast<float>(mtu_.get_rate()) / mtu_.get_rate(true); rate *= 100.0f; utils::format(" Interval Timer (real): %d [Hz] (%3.2f [%%])\n") % mtu_.get_rate(true) % rate; } cmd_.set_prompt("# "); uint8_t cnt = 0; while(1) { cmt_.sync(); if(cmd_.service()) { uint32_t cmdn = cmd_.get_words(); uint32_t n = 0; while(n < cmdn) { char tmp[256]; if(cmd_.get_word(n, tmp, sizeof(tmp))) { utils::format("Param%d: '%s'\n") % n % tmp; } ++n; } } ++cnt; if(cnt >= 50) { cnt = 0; } if(cnt < 25) { LED::P = 0; } else { LED::P = 1; } } } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <float.h> #include <hintids.hxx> // fuer RES_.. #include <cellatr.hxx> #include <calc.hxx> #include <format.hxx> #include <doc.hxx> #include <swtable.hxx> #include <node.hxx> #include <hints.hxx> #include <rolbck.hxx> //TYPEINIT1( SwFmt, SwClient ); //rtti fuer SwFmt /************************************************************************* |* *************************************************************************/ SwTblBoxNumFormat::SwTblBoxNumFormat( UINT32 nFormat, BOOL bFlag ) : SfxUInt32Item( RES_BOXATR_FORMAT, nFormat ), bAuto( bFlag ) { } int SwTblBoxNumFormat::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetValue() == ((SwTblBoxNumFormat&)rAttr).GetValue() && bAuto == ((SwTblBoxNumFormat&)rAttr).bAuto; } SfxPoolItem* SwTblBoxNumFormat::Clone( SfxItemPool* ) const { return new SwTblBoxNumFormat( GetValue(), bAuto ); } /************************************************************************* |* *************************************************************************/ SwTblBoxFormula::SwTblBoxFormula( const String& rFormula ) : SfxPoolItem( RES_BOXATR_FORMULA ), SwTableFormula( rFormula ), pDefinedIn( 0 ) { } int SwTblBoxFormula::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetFormula() == ((SwTblBoxFormula&)rAttr).GetFormula() && pDefinedIn == ((SwTblBoxFormula&)rAttr).pDefinedIn; } SfxPoolItem* SwTblBoxFormula::Clone( SfxItemPool* ) const { // auf externe Darstellung umschalten!! SwTblBoxFormula* pNew = new SwTblBoxFormula( GetFormula() ); pNew->SwTableFormula::operator=( *this ); return pNew; } // suche den Node, in dem die Formel steht: // TextFeld -> TextNode, // BoxAttribut -> BoxStartNode // !!! MUSS VON JEDER ABLEITUNG UEBERLADEN WERDEN !!! const SwNode* SwTblBoxFormula::GetNodeOfFormula() const { const SwNode* pRet = 0; if( pDefinedIn ) { SwClient* pBox = SwClientIter( *pDefinedIn ).First( TYPE( SwTableBox )); if( pBox ) pRet = ((SwTableBox*)pBox)->GetSttNd(); } return pRet; } SwTableBox* SwTblBoxFormula::GetTableBox() { SwTableBox* pBox = 0; if( pDefinedIn ) pBox = (SwTableBox*)SwClientIter( *pDefinedIn ). First( TYPE( SwTableBox )); return pBox; } void SwTblBoxFormula::ChangeState( const SfxPoolItem* pItem ) { if( !pDefinedIn ) return ; SwTableFmlUpdate* pUpdtFld; if( !pItem || RES_TABLEFML_UPDATE != pItem->Which() ) { // setze bei allen das Value-Flag zurueck ChgValid( FALSE ); return ; } pUpdtFld = (SwTableFmlUpdate*)pItem; // bestimme die Tabelle, in der das Attribut steht const SwTableNode* pTblNd; const SwNode* pNd = GetNodeOfFormula(); if( pNd && &pNd->GetNodes() == &pNd->GetDoc()->GetNodes() && 0 != ( pTblNd = pNd->FindTableNode() )) { switch( pUpdtFld->eFlags ) { case TBL_CALC: // setze das Value-Flag zurueck // JP 17.06.96: interne Darstellung auf alle Formeln // (Referenzen auf andere Tabellen!!!) // if( VF_CMD & pFld->GetFormat() ) // pFld->PtrToBoxNm( pUpdtFld->pTbl ); // else ChgValid( FALSE ); break; case TBL_BOXNAME: // ist es die gesuchte Tabelle ?? if( &pTblNd->GetTable() == pUpdtFld->pTbl ) // zur externen Darstellung PtrToBoxNm( pUpdtFld->pTbl ); break; case TBL_BOXPTR: // zur internen Darstellung // JP 17.06.96: interne Darstellung auf alle Formeln // (Referenzen auf andere Tabellen!!!) BoxNmToPtr( &pTblNd->GetTable() ); break; case TBL_RELBOXNAME: // ist es die gesuchte Tabelle ?? if( &pTblNd->GetTable() == pUpdtFld->pTbl ) // zur relativen Darstellung ToRelBoxNm( pUpdtFld->pTbl ); break; case TBL_SPLITTBL: if( &pTblNd->GetTable() == pUpdtFld->pTbl ) { USHORT nLnPos = SwTableFormula::GetLnPosInTbl( pTblNd->GetTable(), GetTableBox() ); pUpdtFld->bBehindSplitLine = USHRT_MAX != nLnPos && pUpdtFld->nSplitLine <= nLnPos; } else pUpdtFld->bBehindSplitLine = FALSE; // kein break case TBL_MERGETBL: if( pUpdtFld->pHistory ) { // fuer die History brauche ich aber die unveraenderte Formel SwTblBoxFormula aCopy( *this ); pUpdtFld->bModified = FALSE; ToSplitMergeBoxNm( *pUpdtFld ); if( pUpdtFld->bModified ) { // und dann in der externen Darstellung aCopy.PtrToBoxNm( &pTblNd->GetTable() ); pUpdtFld->pHistory->Add( &aCopy, &aCopy, pNd->FindTableBoxStartNode()->GetIndex() ); } } else ToSplitMergeBoxNm( *pUpdtFld ); break; } } } void SwTblBoxFormula::Calc( SwTblCalcPara& rCalcPara, double& rValue ) { if( !rCalcPara.rCalc.IsCalcError() ) // ist schon Fehler gesetzt ? { // erzeuge aus den BoxNamen die Pointer BoxNmToPtr( rCalcPara.pTbl ); String sFml( MakeFormel( rCalcPara )); if( !rCalcPara.rCalc.IsCalcError() ) rValue = rCalcPara.rCalc.Calculate( sFml ).GetDouble(); else rValue = DBL_MAX; ChgValid( !rCalcPara.IsStackOverFlow() ); // der Wert ist wieder gueltig } } /************************************************************************* |* *************************************************************************/ SwTblBoxValue::SwTblBoxValue() : SfxPoolItem( RES_BOXATR_VALUE ), nValue( 0 ) { } SwTblBoxValue::SwTblBoxValue( const double nVal ) : SfxPoolItem( RES_BOXATR_VALUE ), nValue( nVal ) { } int SwTblBoxValue::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return nValue == ((SwTblBoxValue&)rAttr).nValue; } SfxPoolItem* SwTblBoxValue::Clone( SfxItemPool* ) const { return new SwTblBoxValue( nValue ); } <commit_msg>dba33h: #i112652#: SwTblBoxValue: items with NaN should compare equal<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <float.h> #include <rtl/math.hxx> #include <hintids.hxx> // fuer RES_.. #include <cellatr.hxx> #include <calc.hxx> #include <format.hxx> #include <doc.hxx> #include <swtable.hxx> #include <node.hxx> #include <hints.hxx> #include <rolbck.hxx> //TYPEINIT1( SwFmt, SwClient ); //rtti fuer SwFmt /************************************************************************* |* *************************************************************************/ SwTblBoxNumFormat::SwTblBoxNumFormat( UINT32 nFormat, BOOL bFlag ) : SfxUInt32Item( RES_BOXATR_FORMAT, nFormat ), bAuto( bFlag ) { } int SwTblBoxNumFormat::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetValue() == ((SwTblBoxNumFormat&)rAttr).GetValue() && bAuto == ((SwTblBoxNumFormat&)rAttr).bAuto; } SfxPoolItem* SwTblBoxNumFormat::Clone( SfxItemPool* ) const { return new SwTblBoxNumFormat( GetValue(), bAuto ); } /************************************************************************* |* *************************************************************************/ SwTblBoxFormula::SwTblBoxFormula( const String& rFormula ) : SfxPoolItem( RES_BOXATR_FORMULA ), SwTableFormula( rFormula ), pDefinedIn( 0 ) { } int SwTblBoxFormula::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetFormula() == ((SwTblBoxFormula&)rAttr).GetFormula() && pDefinedIn == ((SwTblBoxFormula&)rAttr).pDefinedIn; } SfxPoolItem* SwTblBoxFormula::Clone( SfxItemPool* ) const { // auf externe Darstellung umschalten!! SwTblBoxFormula* pNew = new SwTblBoxFormula( GetFormula() ); pNew->SwTableFormula::operator=( *this ); return pNew; } // suche den Node, in dem die Formel steht: // TextFeld -> TextNode, // BoxAttribut -> BoxStartNode // !!! MUSS VON JEDER ABLEITUNG UEBERLADEN WERDEN !!! const SwNode* SwTblBoxFormula::GetNodeOfFormula() const { const SwNode* pRet = 0; if( pDefinedIn ) { SwClient* pBox = SwClientIter( *pDefinedIn ).First( TYPE( SwTableBox )); if( pBox ) pRet = ((SwTableBox*)pBox)->GetSttNd(); } return pRet; } SwTableBox* SwTblBoxFormula::GetTableBox() { SwTableBox* pBox = 0; if( pDefinedIn ) pBox = (SwTableBox*)SwClientIter( *pDefinedIn ). First( TYPE( SwTableBox )); return pBox; } void SwTblBoxFormula::ChangeState( const SfxPoolItem* pItem ) { if( !pDefinedIn ) return ; SwTableFmlUpdate* pUpdtFld; if( !pItem || RES_TABLEFML_UPDATE != pItem->Which() ) { // setze bei allen das Value-Flag zurueck ChgValid( FALSE ); return ; } pUpdtFld = (SwTableFmlUpdate*)pItem; // bestimme die Tabelle, in der das Attribut steht const SwTableNode* pTblNd; const SwNode* pNd = GetNodeOfFormula(); if( pNd && &pNd->GetNodes() == &pNd->GetDoc()->GetNodes() && 0 != ( pTblNd = pNd->FindTableNode() )) { switch( pUpdtFld->eFlags ) { case TBL_CALC: // setze das Value-Flag zurueck // JP 17.06.96: interne Darstellung auf alle Formeln // (Referenzen auf andere Tabellen!!!) // if( VF_CMD & pFld->GetFormat() ) // pFld->PtrToBoxNm( pUpdtFld->pTbl ); // else ChgValid( FALSE ); break; case TBL_BOXNAME: // ist es die gesuchte Tabelle ?? if( &pTblNd->GetTable() == pUpdtFld->pTbl ) // zur externen Darstellung PtrToBoxNm( pUpdtFld->pTbl ); break; case TBL_BOXPTR: // zur internen Darstellung // JP 17.06.96: interne Darstellung auf alle Formeln // (Referenzen auf andere Tabellen!!!) BoxNmToPtr( &pTblNd->GetTable() ); break; case TBL_RELBOXNAME: // ist es die gesuchte Tabelle ?? if( &pTblNd->GetTable() == pUpdtFld->pTbl ) // zur relativen Darstellung ToRelBoxNm( pUpdtFld->pTbl ); break; case TBL_SPLITTBL: if( &pTblNd->GetTable() == pUpdtFld->pTbl ) { USHORT nLnPos = SwTableFormula::GetLnPosInTbl( pTblNd->GetTable(), GetTableBox() ); pUpdtFld->bBehindSplitLine = USHRT_MAX != nLnPos && pUpdtFld->nSplitLine <= nLnPos; } else pUpdtFld->bBehindSplitLine = FALSE; // kein break case TBL_MERGETBL: if( pUpdtFld->pHistory ) { // fuer die History brauche ich aber die unveraenderte Formel SwTblBoxFormula aCopy( *this ); pUpdtFld->bModified = FALSE; ToSplitMergeBoxNm( *pUpdtFld ); if( pUpdtFld->bModified ) { // und dann in der externen Darstellung aCopy.PtrToBoxNm( &pTblNd->GetTable() ); pUpdtFld->pHistory->Add( &aCopy, &aCopy, pNd->FindTableBoxStartNode()->GetIndex() ); } } else ToSplitMergeBoxNm( *pUpdtFld ); break; } } } void SwTblBoxFormula::Calc( SwTblCalcPara& rCalcPara, double& rValue ) { if( !rCalcPara.rCalc.IsCalcError() ) // ist schon Fehler gesetzt ? { // erzeuge aus den BoxNamen die Pointer BoxNmToPtr( rCalcPara.pTbl ); String sFml( MakeFormel( rCalcPara )); if( !rCalcPara.rCalc.IsCalcError() ) rValue = rCalcPara.rCalc.Calculate( sFml ).GetDouble(); else rValue = DBL_MAX; ChgValid( !rCalcPara.IsStackOverFlow() ); // der Wert ist wieder gueltig } } /************************************************************************* |* *************************************************************************/ SwTblBoxValue::SwTblBoxValue() : SfxPoolItem( RES_BOXATR_VALUE ), nValue( 0 ) { } SwTblBoxValue::SwTblBoxValue( const double nVal ) : SfxPoolItem( RES_BOXATR_VALUE ), nValue( nVal ) { } int SwTblBoxValue::operator==( const SfxPoolItem& rAttr ) const { ASSERT(SfxPoolItem::operator==(rAttr), "SwTblBoxValue: item not equal"); SwTblBoxValue const& rOther( static_cast<SwTblBoxValue const&>(rAttr) ); // items with NaN should be equal to enable pooling return ::rtl::math::isNan(nValue) ? ::rtl::math::isNan(rOther.nValue) : (nValue == rOther.nValue); } SfxPoolItem* SwTblBoxValue::Clone( SfxItemPool* ) const { return new SwTblBoxValue( nValue ); } <|endoftext|>
<commit_before>//== HTMLRewrite.cpp - Translate source code into prettified HTML --*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the HTMLRewriter clas, which is used to translate the // text of a source file into prettified HTML. // //===----------------------------------------------------------------------===// #include "clang/Rewrite/Rewriter.h" #include "clang/Rewrite/HTMLRewrite.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/MemoryBuffer.h" #include <sstream> using namespace clang; void html::EscapeText(Rewriter& R, unsigned FileID, bool EscapeSpaces) { const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID); const char* C = Buf->getBufferStart(); const char* FileEnd = Buf->getBufferEnd(); assert (C <= FileEnd); for (unsigned FilePos = 0; C != FileEnd ; ++C, ++FilePos) { SourceLocation Loc = SourceLocation::getFileLoc(FileID, FilePos); switch (*C) { default: break; case ' ': if (EscapeSpaces) R.ReplaceText(Loc, 1, "&#32;", 5); break; case '<': R.ReplaceText(Loc, 1, "&lt;", 4); break; case '>': R.ReplaceText(Loc, 1, "&gt;", 4); break; case '&': R.ReplaceText(Loc, 1, "&amp;", 5); break; } } } std::string html::EscapeText(const std::string& s, bool EscapeSpaces) { unsigned len = s.size(); std::ostringstream os; for (unsigned i = 0 ; i < len; ++i) { char c = s[i]; switch (c) { default: os << c; break; case ' ': if (EscapeSpaces) os << "&#32;"; break; case '<': os << "&lt;"; break; case '>': os << "&gt;"; break; case '&': os << "&amp;"; break; } } return os.str(); } static void AddLineNumber(Rewriter& R, unsigned LineNo, SourceLocation B, SourceLocation E) { // Put the closing </tr> first. R.InsertCStrBefore(E, "</tr>"); if (B == E) // Handle empty lines. R.InsertCStrBefore(B, "<td class=\"line\"> </td>"); else { R.InsertCStrBefore(E, "</td>"); R.InsertCStrBefore(B, "<td class=\"line\">"); } // Insert a div tag for the line number. std::ostringstream os; os << "<td class=\"num\">" << LineNo << "</td>"; R.InsertStrBefore(B, os.str()); // Now prepend the <tr>. R.InsertCStrBefore(B, "<tr>"); } void html::AddLineNumbers(Rewriter& R, unsigned FileID) { const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID); const char* FileBeg = Buf->getBufferStart(); const char* FileEnd = Buf->getBufferEnd(); const char* C = FileBeg; assert (C <= FileEnd); unsigned LineNo = 0; unsigned FilePos = 0; while (C != FileEnd) { ++LineNo; unsigned LineStartPos = FilePos; unsigned LineEndPos = FileEnd - FileBeg; assert (FilePos <= LineEndPos); assert (C < FileEnd); // Scan until the newline (or end-of-file). for ( ; C != FileEnd ; ++C, ++FilePos) if (*C == '\n') { LineEndPos = FilePos; break; } AddLineNumber(R, LineNo, SourceLocation::getFileLoc(FileID, LineStartPos), SourceLocation::getFileLoc(FileID, LineEndPos)); if (C != FileEnd) { ++C; ++FilePos; } } // Add one big div tag that surrounds all of the code. R.InsertCStrBefore(SourceLocation::getFileLoc(FileID, 0), "<table class=\"code\">\n"); R.InsertCStrAfter(SourceLocation::getFileLoc(FileID, FileEnd - FileBeg), "</table>"); } void html::AddHeaderFooterInternalBuiltinCSS(Rewriter& R, unsigned FileID) { const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID); const char* FileStart = Buf->getBufferStart(); const char* FileEnd = Buf->getBufferEnd(); SourceLocation StartLoc = SourceLocation::getFileLoc(FileID, 0); SourceLocation EndLoc = SourceLocation::getFileLoc(FileID, FileEnd-FileStart); // Generate header { std::ostringstream os; os << "<html>\n<head>\n" << "<style type=\"text/css\">\n" << " body { color:#000000; background-color:#ffffff }\n" << " body { font-family:Helvetica, sans-serif }\n" << " .code { border-spacing:0px; width:100%; }\n" << " .code { font-family: \"Andale Mono\", fixed; font-size:10pt }\n" << " .code { line-height: 1.2em }\n" << " .num { width:2.5em; padding-right:2ex; background-color:#eeeeee }\n" << " .num { text-align:right; font-size: smaller }\n" << " .num { color:#444444 }\n" << " .line { padding-left: 1ex; border-left: 3px solid #ccc }\n" << " .line { white-space: pre }\n" << " .msg { background-color:#ff8000; color:#000000 }\n" << " .msg { -webkit-box-shadow:1px 1px 7px #000 }\n" << " .msg { -webkit-border-radius:5px }\n" << " .msg { border: solid 1px #944a00 }\n" << " .msg { font-family:Helvetica, sans-serif; font-size: smaller }\n" << " .msg { font-weight: bold }\n" << " .msg { float:left }\n" << " .msg { padding:0.5em 1ex 0.5em 1ex }\n" << " .msg { margin-top:10px; margin-bottom:10px }\n" << " .mrange { background-color:#ffcc66 }\n" << " .mrange { border-bottom: 1px solid #ff8000 }\n" << "</style>\n</head>\n<body>"; R.InsertStrBefore(StartLoc, os.str()); } // Generate footer { std::ostringstream os; os << "</body></html>\n"; R.InsertStrAfter(EndLoc, os.str()); } } <commit_msg>Minor CSS tweaking (smaller h1 tags). Bug fix in EscapeText (for std::string) where spaces were not properly emitted.<commit_after>//== HTMLRewrite.cpp - Translate source code into prettified HTML --*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the HTMLRewriter clas, which is used to translate the // text of a source file into prettified HTML. // //===----------------------------------------------------------------------===// #include "clang/Rewrite/Rewriter.h" #include "clang/Rewrite/HTMLRewrite.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/MemoryBuffer.h" #include <sstream> using namespace clang; void html::EscapeText(Rewriter& R, unsigned FileID, bool EscapeSpaces) { const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID); const char* C = Buf->getBufferStart(); const char* FileEnd = Buf->getBufferEnd(); assert (C <= FileEnd); for (unsigned FilePos = 0; C != FileEnd ; ++C, ++FilePos) { SourceLocation Loc = SourceLocation::getFileLoc(FileID, FilePos); switch (*C) { default: break; case ' ': if (EscapeSpaces) R.ReplaceText(Loc, 1, "&#32;", 5); break; case '<': R.ReplaceText(Loc, 1, "&lt;", 4); break; case '>': R.ReplaceText(Loc, 1, "&gt;", 4); break; case '&': R.ReplaceText(Loc, 1, "&amp;", 5); break; } } } std::string html::EscapeText(const std::string& s, bool EscapeSpaces) { unsigned len = s.size(); std::ostringstream os; for (unsigned i = 0 ; i < len; ++i) { char c = s[i]; switch (c) { default: os << c; break; case ' ': if (EscapeSpaces) os << "&#32;"; else os << ' '; break; case '<': os << "&lt;"; break; case '>': os << "&gt;"; break; case '&': os << "&amp;"; break; } } return os.str(); } static void AddLineNumber(Rewriter& R, unsigned LineNo, SourceLocation B, SourceLocation E) { // Put the closing </tr> first. R.InsertCStrBefore(E, "</tr>"); if (B == E) // Handle empty lines. R.InsertCStrBefore(B, "<td class=\"line\"> </td>"); else { R.InsertCStrBefore(E, "</td>"); R.InsertCStrBefore(B, "<td class=\"line\">"); } // Insert a div tag for the line number. std::ostringstream os; os << "<td class=\"num\">" << LineNo << "</td>"; R.InsertStrBefore(B, os.str()); // Now prepend the <tr>. R.InsertCStrBefore(B, "<tr>"); } void html::AddLineNumbers(Rewriter& R, unsigned FileID) { const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID); const char* FileBeg = Buf->getBufferStart(); const char* FileEnd = Buf->getBufferEnd(); const char* C = FileBeg; assert (C <= FileEnd); unsigned LineNo = 0; unsigned FilePos = 0; while (C != FileEnd) { ++LineNo; unsigned LineStartPos = FilePos; unsigned LineEndPos = FileEnd - FileBeg; assert (FilePos <= LineEndPos); assert (C < FileEnd); // Scan until the newline (or end-of-file). for ( ; C != FileEnd ; ++C, ++FilePos) if (*C == '\n') { LineEndPos = FilePos; break; } AddLineNumber(R, LineNo, SourceLocation::getFileLoc(FileID, LineStartPos), SourceLocation::getFileLoc(FileID, LineEndPos)); if (C != FileEnd) { ++C; ++FilePos; } } // Add one big div tag that surrounds all of the code. R.InsertCStrBefore(SourceLocation::getFileLoc(FileID, 0), "<table class=\"code\">\n"); R.InsertCStrAfter(SourceLocation::getFileLoc(FileID, FileEnd - FileBeg), "</table>"); } void html::AddHeaderFooterInternalBuiltinCSS(Rewriter& R, unsigned FileID) { const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID); const char* FileStart = Buf->getBufferStart(); const char* FileEnd = Buf->getBufferEnd(); SourceLocation StartLoc = SourceLocation::getFileLoc(FileID, 0); SourceLocation EndLoc = SourceLocation::getFileLoc(FileID, FileEnd-FileStart); // Generate header { std::ostringstream os; os << "<html>\n<head>\n" << "<style type=\"text/css\">\n" << " body { color:#000000; background-color:#ffffff }\n" << " body { font-family:Helvetica, sans-serif; font-size:10pt }\n" << " h1 { font-size:12pt }\n" << " .code { border-spacing:0px; width:100%; }\n" << " .code { font-family: \"Andale Mono\", fixed; font-size:10pt }\n" << " .code { line-height: 1.2em }\n" << " .num { width:2.5em; padding-right:2ex; background-color:#eeeeee }\n" << " .num { text-align:right; font-size: smaller }\n" << " .num { color:#444444 }\n" << " .line { padding-left: 1ex; border-left: 3px solid #ccc }\n" << " .line { white-space: pre }\n" << " .msg { background-color:#ff8000; color:#000000 }\n" << " .msg { -webkit-box-shadow:1px 1px 7px #000 }\n" << " .msg { -webkit-border-radius:5px }\n" << " .msg { border: solid 1px #944a00 }\n" << " .msg { font-family:Helvetica, sans-serif; font-size: smaller }\n" << " .msg { font-weight: bold }\n" << " .msg { float:left }\n" << " .msg { padding:0.5em 1ex 0.5em 1ex }\n" << " .msg { margin-top:10px; margin-bottom:10px }\n" << " .mrange { background-color:#ffcc66 }\n" << " .mrange { border-bottom: 1px solid #ff8000 }\n" << "</style>\n</head>\n<body>"; R.InsertStrBefore(StartLoc, os.str()); } // Generate footer { std::ostringstream os; os << "</body></html>\n"; R.InsertStrAfter(EndLoc, os.str()); } } <|endoftext|>
<commit_before><commit_msg>SwNoTextFrm::Paint: stop using SwViewShell::GetOut()<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawdoc.cxx,v $ * * $Revision: 1.22 $ * * last change: $Author: kz $ $Date: 2007-05-10 15:58:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif #ifndef _STREAM_HXX //autogen #include <tools/stream.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #include <sot/storage.hxx> #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _FORBIDDENCHARACTERSTABLE_HXX #include <svx/forbiddencharacterstable.hxx> #endif #include <unotools/ucbstreamhelper.hxx> #include <svx/xtable.hxx> #ifndef _SVX_DRAWITEM_HXX #include <svx/drawitem.hxx> #endif #ifndef _VIEWSH_HXX #include <viewsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _ROOTFRM_HXX #include <rootfrm.hxx> #endif #ifndef _DRAWDOC_HXX #include <drawdoc.hxx> #endif #ifndef _DPAGE_HXX #include <dpage.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif using namespace com::sun::star; /************************************************************************* |* |* Konstruktor |* \************************************************************************/ const String GetPalettePath() { SvtPathOptions aPathOpt; return aPathOpt.GetPalettePath(); } SwDrawDocument::SwDrawDocument( SwDoc* pD ) : FmFormModel( ::GetPalettePath(), &pD->GetAttrPool(), pD->GetDocShell(), TRUE ), pDoc( pD ) { SetScaleUnit( MAP_TWIP ); SetSwapGraphics( TRUE ); SwDocShell* pDocSh = pDoc->GetDocShell(); if ( pDocSh ) { SetObjectShell( pDocSh ); SvxColorTableItem* pColItem = ( SvxColorTableItem* ) ( pDocSh->GetItem( SID_COLOR_TABLE ) ); XColorTable *pXCol = pColItem ? pColItem->GetColorTable() : XColorTable::GetStdColorTable(); SetColorTable( pXCol ); if ( !pColItem ) pDocSh->PutItem( SvxColorTableItem( pXCol, SID_COLOR_TABLE ) ); pDocSh->PutItem( SvxGradientListItem( GetGradientList(), SID_GRADIENT_LIST )); pDocSh->PutItem( SvxHatchListItem( GetHatchList(), SID_HATCH_LIST ) ); pDocSh->PutItem( SvxBitmapListItem( GetBitmapList(), SID_BITMAP_LIST ) ); pDocSh->PutItem( SvxDashListItem( GetDashList(), SID_DASH_LIST ) ); pDocSh->PutItem( SvxLineEndListItem( GetLineEndList(), SID_LINEEND_LIST ) ); pDocSh->PutItem( SfxUInt16Item(SID_ATTR_LINEEND_WIDTH_DEFAULT, 111) ); SetObjectShell( pDocSh ); } else SetColorTable( XColorTable::GetStdColorTable() ); // copy all the default values to the SdrModel SfxItemPool* pSdrPool = pD->GetAttrPool().GetSecondaryPool(); if( pSdrPool ) { const USHORT aWhichRanges[] = { RES_CHRATR_BEGIN, RES_CHRATR_END, RES_PARATR_BEGIN, RES_PARATR_END, 0 }; SfxItemPool& rDocPool = pD->GetAttrPool(); USHORT nEdtWhich, nSlotId; const SfxPoolItem* pItem; for( const USHORT* pRangeArr = aWhichRanges; *pRangeArr; pRangeArr += 2 ) for( USHORT nW = *pRangeArr, nEnd = *(pRangeArr+1); nW < nEnd; ++nW ) if( 0 != (pItem = rDocPool.GetPoolDefaultItem( nW )) && 0 != (nSlotId = rDocPool.GetSlotId( nW ) ) && nSlotId != nW && 0 != (nEdtWhich = pSdrPool->GetWhich( nSlotId )) && nSlotId != nEdtWhich ) { SfxPoolItem* pCpy = pItem->Clone(); pCpy->SetWhich( nEdtWhich ); pSdrPool->SetPoolDefaultItem( *pCpy ); delete pCpy; } } SetForbiddenCharsTable( pD->getForbiddenCharacterTable() ); // #87795# Implementation for asian compression SetCharCompressType( pD->getCharacterCompressionType() ); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ SwDrawDocument::~SwDrawDocument() { Broadcast(SdrHint(HINT_MODELCLEARED)); // #116168# ClearModel(sal_True); //Clear(); } /************************************************************************* |* |* Diese Methode erzeugt eine neue Seite (SdPage) und gibt einen Zeiger |* darauf zurueck. Die Drawing Engine benutzt diese Methode beim Laden |* zur Erzeugung von Seiten (deren Typ sie ja nicht kennt, da es ABLEITUNGEN |* der SdrPage sind). |* \************************************************************************/ SdrPage* SwDrawDocument::AllocPage(FASTBOOL bMasterPage) { SwDPage* pPage = new SwDPage(*this, bMasterPage); pPage->SetName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "Controls" )) ); return pPage; } SvStream* SwDrawDocument::GetDocumentStream( SdrDocumentStreamInfo& rInfo ) const { SvStream* pRet = NULL; uno::Reference < embed::XStorage > xRoot( pDoc->GetDocStorage() ); if( xRoot.is() ) { if( rInfo.maUserData.Len() && ( rInfo.maUserData.GetToken( 0, ':' ) == String( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.Package" ) ) ) ) { const String aPicturePath( rInfo.maUserData.GetToken( 1, ':' ) ); // graphic from picture stream in picture storage in XML package if( aPicturePath.GetTokenCount( '/' ) == 2 ) { const String aPictureStorageName( aPicturePath.GetToken( 0, '/' ) ); const String aPictureStreamName( aPicturePath.GetToken( 1, '/' ) ); try { uno::Reference < embed::XStorage > xPictureStorage = xRoot->openStorageElement( aPictureStorageName, embed::ElementModes::READ ); uno::Reference < io::XStream > xStream = xPictureStorage->openStreamElement( aPictureStreamName, embed::ElementModes::READ ); pRet = utl::UcbStreamHelper::CreateStream( xStream ); if( pRet ) { rInfo.mbDeleteAfterUse = TRUE; rInfo.mxStorageRef = xPictureStorage; } } catch ( uno::Exception& ) { } } } } return pRet; } SdrLayerID SwDrawDocument::GetControlExportLayerId( const SdrObject & ) const { //fuer Versionen < 5.0, es gab nur Hell und Heaven return (SdrLayerID)pDoc->GetHeavenId(); } // --> OD 2006-03-01 #b6382898# uno::Reference< uno::XInterface > SwDrawDocument::createUnoModel() { uno::Reference< uno::XInterface > xModel; try { if ( GetDoc().GetDocShell() ) { xModel = GetDoc().GetDocShell()->GetModel(); } } catch( uno::RuntimeException& ) { ASSERT( false, "<SwDrawDocument::createUnoModel()> - could *not* retrieve model at <SwDocShell>" ); } return xModel; } // <-- <commit_msg>INTEGRATION: CWS swwarnings (1.20.222); FILE MERGED 2007/05/29 11:24:02 os 1.20.222.4: RESYNC: (1.20-1.22); FILE MERGED 2007/04/03 12:59:46 tl 1.20.222.3: #i69287# warning-free code 2007/02/26 08:51:09 tl 1.20.222.2: #i69287# warning-free code 2007/02/22 15:06:28 tl 1.20.222.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawdoc.cxx,v $ * * $Revision: 1.23 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:43:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif #ifndef _STREAM_HXX //autogen #include <tools/stream.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #include <sot/storage.hxx> #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _FORBIDDENCHARACTERSTABLE_HXX #include <svx/forbiddencharacterstable.hxx> #endif #include <unotools/ucbstreamhelper.hxx> #include <svx/xtable.hxx> #ifndef _SVX_DRAWITEM_HXX #include <svx/drawitem.hxx> #endif #ifndef _VIEWSH_HXX #include <viewsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _ROOTFRM_HXX #include <rootfrm.hxx> #endif #ifndef _DRAWDOC_HXX #include <drawdoc.hxx> #endif #ifndef _DPAGE_HXX #include <dpage.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif using namespace com::sun::star; /************************************************************************* |* |* Konstruktor |* \************************************************************************/ const String GetPalettePath() { SvtPathOptions aPathOpt; return aPathOpt.GetPalettePath(); } SwDrawDocument::SwDrawDocument( SwDoc* pD ) : FmFormModel( ::GetPalettePath(), &pD->GetAttrPool(), pD->GetDocShell(), TRUE ), pDoc( pD ) { SetScaleUnit( MAP_TWIP ); SetSwapGraphics( TRUE ); SwDocShell* pDocSh = pDoc->GetDocShell(); if ( pDocSh ) { SetObjectShell( pDocSh ); SvxColorTableItem* pColItem = ( SvxColorTableItem* ) ( pDocSh->GetItem( SID_COLOR_TABLE ) ); XColorTable *pXCol = pColItem ? pColItem->GetColorTable() : XColorTable::GetStdColorTable(); SetColorTable( pXCol ); if ( !pColItem ) pDocSh->PutItem( SvxColorTableItem( pXCol, SID_COLOR_TABLE ) ); pDocSh->PutItem( SvxGradientListItem( GetGradientList(), SID_GRADIENT_LIST )); pDocSh->PutItem( SvxHatchListItem( GetHatchList(), SID_HATCH_LIST ) ); pDocSh->PutItem( SvxBitmapListItem( GetBitmapList(), SID_BITMAP_LIST ) ); pDocSh->PutItem( SvxDashListItem( GetDashList(), SID_DASH_LIST ) ); pDocSh->PutItem( SvxLineEndListItem( GetLineEndList(), SID_LINEEND_LIST ) ); pDocSh->PutItem( SfxUInt16Item(SID_ATTR_LINEEND_WIDTH_DEFAULT, 111) ); SetObjectShell( pDocSh ); } else SetColorTable( XColorTable::GetStdColorTable() ); // copy all the default values to the SdrModel SfxItemPool* pSdrPool = pD->GetAttrPool().GetSecondaryPool(); if( pSdrPool ) { const USHORT aWhichRanges[] = { RES_CHRATR_BEGIN, RES_CHRATR_END, RES_PARATR_BEGIN, RES_PARATR_END, 0 }; SfxItemPool& rDocPool = pD->GetAttrPool(); USHORT nEdtWhich, nSlotId; const SfxPoolItem* pItem; for( const USHORT* pRangeArr = aWhichRanges; *pRangeArr; pRangeArr += 2 ) for( USHORT nW = *pRangeArr, nEnd = *(pRangeArr+1); nW < nEnd; ++nW ) if( 0 != (pItem = rDocPool.GetPoolDefaultItem( nW )) && 0 != (nSlotId = rDocPool.GetSlotId( nW ) ) && nSlotId != nW && 0 != (nEdtWhich = pSdrPool->GetWhich( nSlotId )) && nSlotId != nEdtWhich ) { SfxPoolItem* pCpy = pItem->Clone(); pCpy->SetWhich( nEdtWhich ); pSdrPool->SetPoolDefaultItem( *pCpy ); delete pCpy; } } SetForbiddenCharsTable( pD->getForbiddenCharacterTable() ); // #87795# Implementation for asian compression SetCharCompressType( static_cast<UINT16>(pD->getCharacterCompressionType() )); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ SwDrawDocument::~SwDrawDocument() { Broadcast(SdrHint(HINT_MODELCLEARED)); // #116168# ClearModel(sal_True); //Clear(); } /************************************************************************* |* |* Diese Methode erzeugt eine neue Seite (SdPage) und gibt einen Zeiger |* darauf zurueck. Die Drawing Engine benutzt diese Methode beim Laden |* zur Erzeugung von Seiten (deren Typ sie ja nicht kennt, da es ABLEITUNGEN |* der SdrPage sind). |* \************************************************************************/ SdrPage* SwDrawDocument::AllocPage(FASTBOOL bMasterPage) { SwDPage* pPage = new SwDPage(*this, 0 != bMasterPage); pPage->SetName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "Controls" )) ); return pPage; } SvStream* SwDrawDocument::GetDocumentStream( SdrDocumentStreamInfo& rInfo ) const { SvStream* pRet = NULL; uno::Reference < embed::XStorage > xRoot( pDoc->GetDocStorage() ); if( xRoot.is() ) { if( rInfo.maUserData.Len() && ( rInfo.maUserData.GetToken( 0, ':' ) == String( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.Package" ) ) ) ) { const String aPicturePath( rInfo.maUserData.GetToken( 1, ':' ) ); // graphic from picture stream in picture storage in XML package if( aPicturePath.GetTokenCount( '/' ) == 2 ) { const String aPictureStorageName( aPicturePath.GetToken( 0, '/' ) ); const String aPictureStreamName( aPicturePath.GetToken( 1, '/' ) ); try { uno::Reference < embed::XStorage > xPictureStorage = xRoot->openStorageElement( aPictureStorageName, embed::ElementModes::READ ); uno::Reference < io::XStream > xStream = xPictureStorage->openStreamElement( aPictureStreamName, embed::ElementModes::READ ); pRet = utl::UcbStreamHelper::CreateStream( xStream ); if( pRet ) { rInfo.mbDeleteAfterUse = TRUE; rInfo.mxStorageRef = xPictureStorage; } } catch ( uno::Exception& ) { } } } } return pRet; } SdrLayerID SwDrawDocument::GetControlExportLayerId( const SdrObject & ) const { //fuer Versionen < 5.0, es gab nur Hell und Heaven return (SdrLayerID)pDoc->GetHeavenId(); } // --> OD 2006-03-01 #b6382898# uno::Reference< uno::XInterface > SwDrawDocument::createUnoModel() { uno::Reference< uno::XInterface > xModel; try { if ( GetDoc().GetDocShell() ) { xModel = GetDoc().GetDocShell()->GetModel(); } } catch( uno::RuntimeException& ) { ASSERT( false, "<SwDrawDocument::createUnoModel()> - could *not* retrieve model at <SwDocShell>" ); } return xModel; } // <-- <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edredln.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:46:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _SV_WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #include "redline.hxx" #include "doc.hxx" #include "swundo.hxx" #include "editsh.hxx" #include "edimp.hxx" #include "frmtool.hxx" USHORT SwEditShell::GetRedlineMode() const { return GetDoc()->GetRedlineMode(); } void SwEditShell::SetRedlineMode( USHORT eMode ) { if( eMode != GetDoc()->GetRedlineMode() ) { SET_CURR_SHELL( this ); StartAllAction(); GetDoc()->SetRedlineMode( (RedlineMode_t)eMode ); EndAllAction(); } } BOOL SwEditShell::IsRedlineOn() const { return GetDoc()->IsRedlineOn(); } USHORT SwEditShell::GetRedlineCount() const { return GetDoc()->GetRedlineTbl().Count(); } const SwRedline& SwEditShell::GetRedline( USHORT nPos ) const { return *GetDoc()->GetRedlineTbl()[ nPos ]; } void lcl_InvalidateAll( ViewShell* pSh ) { ViewShell *pStop = pSh; do { if ( pSh->GetWin() ) pSh->GetWin()->Invalidate(); pSh = (ViewShell*)pSh->GetNext(); } while ( pSh != pStop ); } BOOL SwEditShell::AcceptRedline( USHORT nPos ) { SET_CURR_SHELL( this ); StartAllAction(); BOOL bRet = GetDoc()->AcceptRedline( nPos, true ); if( !nPos && !::IsExtraData( GetDoc() ) ) lcl_InvalidateAll( this ); EndAllAction(); return bRet; } BOOL SwEditShell::RejectRedline( USHORT nPos ) { SET_CURR_SHELL( this ); StartAllAction(); BOOL bRet = GetDoc()->RejectRedline( nPos, true ); if( !nPos && !::IsExtraData( GetDoc() ) ) lcl_InvalidateAll( this ); EndAllAction(); return bRet; } // Kommentar am Redline setzen BOOL SwEditShell::SetRedlineComment( const String& rS ) { BOOL bRet = FALSE; FOREACHPAM_START(this) bRet = bRet || GetDoc()->SetRedlineComment( *PCURCRSR, rS ); FOREACHPAM_END() return bRet; } const SwRedline* SwEditShell::GetCurrRedline() const { return GetDoc()->GetRedline( *GetCrsr()->GetPoint(), 0 ); } void SwEditShell::UpdateRedlineAttr() { if( ( nsRedlineMode_t::REDLINE_SHOW_INSERT | nsRedlineMode_t::REDLINE_SHOW_DELETE ) == ( nsRedlineMode_t::REDLINE_SHOW_MASK & GetDoc()->GetRedlineMode() )) { SET_CURR_SHELL( this ); StartAllAction(); GetDoc()->UpdateRedlineAttr(); EndAllAction(); } } // suche das Redline zu diesem Data und returne die Pos im Array // USHRT_MAX wird returnt, falls nicht vorhanden USHORT SwEditShell::FindRedlineOfData( const SwRedlineData& rData ) const { const SwRedlineTbl& rTbl = GetDoc()->GetRedlineTbl(); for( USHORT i = 0, nCnt = rTbl.Count(); i < nCnt; ++i ) if( &rTbl[ i ]->GetRedlineData() == &rData ) return i; return USHRT_MAX; } <commit_msg>INTEGRATION: CWS changefileheader (1.8.242); FILE MERGED 2008/04/01 15:57:04 thb 1.8.242.3: #i85898# Stripping all external header guards 2008/04/01 12:54:04 thb 1.8.242.2: #i85898# Stripping all external header guards 2008/03/31 16:54:03 rt 1.8.242.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edredln.cxx,v $ * $Revision: 1.9 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <docary.hxx> #include <vcl/window.hxx> #include "redline.hxx" #include "doc.hxx" #include "swundo.hxx" #include "editsh.hxx" #include "edimp.hxx" #include "frmtool.hxx" USHORT SwEditShell::GetRedlineMode() const { return GetDoc()->GetRedlineMode(); } void SwEditShell::SetRedlineMode( USHORT eMode ) { if( eMode != GetDoc()->GetRedlineMode() ) { SET_CURR_SHELL( this ); StartAllAction(); GetDoc()->SetRedlineMode( (RedlineMode_t)eMode ); EndAllAction(); } } BOOL SwEditShell::IsRedlineOn() const { return GetDoc()->IsRedlineOn(); } USHORT SwEditShell::GetRedlineCount() const { return GetDoc()->GetRedlineTbl().Count(); } const SwRedline& SwEditShell::GetRedline( USHORT nPos ) const { return *GetDoc()->GetRedlineTbl()[ nPos ]; } void lcl_InvalidateAll( ViewShell* pSh ) { ViewShell *pStop = pSh; do { if ( pSh->GetWin() ) pSh->GetWin()->Invalidate(); pSh = (ViewShell*)pSh->GetNext(); } while ( pSh != pStop ); } BOOL SwEditShell::AcceptRedline( USHORT nPos ) { SET_CURR_SHELL( this ); StartAllAction(); BOOL bRet = GetDoc()->AcceptRedline( nPos, true ); if( !nPos && !::IsExtraData( GetDoc() ) ) lcl_InvalidateAll( this ); EndAllAction(); return bRet; } BOOL SwEditShell::RejectRedline( USHORT nPos ) { SET_CURR_SHELL( this ); StartAllAction(); BOOL bRet = GetDoc()->RejectRedline( nPos, true ); if( !nPos && !::IsExtraData( GetDoc() ) ) lcl_InvalidateAll( this ); EndAllAction(); return bRet; } // Kommentar am Redline setzen BOOL SwEditShell::SetRedlineComment( const String& rS ) { BOOL bRet = FALSE; FOREACHPAM_START(this) bRet = bRet || GetDoc()->SetRedlineComment( *PCURCRSR, rS ); FOREACHPAM_END() return bRet; } const SwRedline* SwEditShell::GetCurrRedline() const { return GetDoc()->GetRedline( *GetCrsr()->GetPoint(), 0 ); } void SwEditShell::UpdateRedlineAttr() { if( ( nsRedlineMode_t::REDLINE_SHOW_INSERT | nsRedlineMode_t::REDLINE_SHOW_DELETE ) == ( nsRedlineMode_t::REDLINE_SHOW_MASK & GetDoc()->GetRedlineMode() )) { SET_CURR_SHELL( this ); StartAllAction(); GetDoc()->UpdateRedlineAttr(); EndAllAction(); } } // suche das Redline zu diesem Data und returne die Pos im Array // USHRT_MAX wird returnt, falls nicht vorhanden USHORT SwEditShell::FindRedlineOfData( const SwRedlineData& rData ) const { const SwRedlineTbl& rTbl = GetDoc()->GetRedlineTbl(); for( USHORT i = 0, nCnt = rTbl.Count(); i < nCnt; ++i ) if( &rTbl[ i ]->GetRedlineData() == &rData ) return i; return USHRT_MAX; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawfont.hxx,v $ * * $Revision: 1.39 $ * * last change: $Author: obo $ $Date: 2008-02-26 09:45:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DRAWFONT_HXX #define _DRAWFONT_HXX #include <tools/solar.h> #include <tools/string.hxx> #include <errhdl.hxx> class SwTxtFrm; class OutputDevice; class ViewShell; class SwScriptInfo; class Point; class SwWrongList; class Size; class SwFont; class Font; class SwUnderlineFont; /************************************************************************* * class SwDrawTextInfo * * encapsulates information for drawing text *************************************************************************/ class SwDrawTextInfo { const SwTxtFrm* pFrm; OutputDevice* pOut; ViewShell* pSh; const SwScriptInfo* pScriptInfo; const Point* pPos; const XubString* pText; const SwWrongList* pWrong; const SwWrongList* pGrammarCheck; const SwWrongList* pSmartTags; // SMARTTAGS const Size* pSize; SwFont *pFnt; SwUnderlineFont* pUnderFnt; xub_StrLen* pHyphPos; long nLeft; long nRight; long nKanaDiff; xub_StrLen nIdx; xub_StrLen nLen; xub_StrLen nOfst; USHORT nWidth; USHORT nAscent; USHORT nCompress; long nSperren; long nSpace; long nKern; xub_StrLen nNumberOfBlanks; BYTE nCursorBidiLevel; BOOL bBullet : 1; BOOL bUpper : 1; // Fuer Kapitaelchen: Grossbuchstaben-Flag BOOL bDrawSpace : 1; // Fuer Kapitaelchen: Unter/Durchstreichung BOOL bGreyWave : 1; // Graue Wellenlinie beim extended TextInput BOOL bSpaceStop : 1; // For underlining we need to know, if a portion // is right in front of a hole portion or a // fix margin portion. BOOL bSnapToGrid : 1; // Does paragraph snap to grid? BOOL bIgnoreFrmRTL : 1; // Paint text as if text has LTR direction, used for // line numbering BOOL bPosMatchesBounds :1; // GetCrsrOfst should not return the next // position if screen position is inside second // half of bound rect, used for Accessibility SwDrawTextInfo(); // nicht zulaessig public: #ifndef PRODUCT BOOL bPos : 1; // These flags should control, that the appropriate BOOL bWrong : 1; // Set-function has been called before calling BOOL bGrammarCheck : 1; // the Get-function of a member BOOL bSize : 1; BOOL bFnt : 1; BOOL bHyph : 1; BOOL bLeft : 1; BOOL bRight : 1; BOOL bKana : 1; BOOL bOfst : 1; BOOL bAscent: 1; BOOL bSperr : 1; BOOL bSpace : 1; BOOL bNumberOfBlanks : 1; BOOL bUppr : 1; BOOL bDrawSp: 1; #endif SwDrawTextInfo( ViewShell *pS, OutputDevice &rO, const SwScriptInfo* pSI, const XubString &rSt, xub_StrLen nI, xub_StrLen nL, USHORT nW = 0, BOOL bB = FALSE ) { pFrm = NULL; pSh = pS; pOut = &rO; pScriptInfo = pSI; pText = &rSt; nIdx = nI; nLen = nL; nKern = 0; nCompress = 0; nWidth = nW; nNumberOfBlanks = 0; nCursorBidiLevel = 0; bBullet = bB; pUnderFnt = 0; bGreyWave = FALSE; bSpaceStop = FALSE; bSnapToGrid = FALSE; bIgnoreFrmRTL = FALSE; bPosMatchesBounds = FALSE; // These values are initialized but, they have to be // set explicitly via their Set-function before they may // be accessed by their Get-function: pPos = 0; pWrong = 0; pGrammarCheck = 0; pSmartTags = 0; pSize = 0; pFnt = 0; pHyphPos = 0; nLeft = 0; nRight = 0; nKanaDiff = 0; nOfst = 0; nAscent = 0; nSperren = 0; nSpace = 0; bUpper = FALSE; bDrawSpace = FALSE; #ifndef PRODUCT // these flags control, whether the matching member variables have // been set by using the Set-function before they may be accessed // by their Get-function: bPos = bWrong = bGrammarCheck = bSize = bFnt = bAscent = bSpace = bNumberOfBlanks = bUppr = bDrawSp = bLeft = bRight = bKana = bOfst = bHyph = bSperr = FALSE; #endif } const SwTxtFrm* GetFrm() const { return pFrm; } void SetFrm( const SwTxtFrm* pNewFrm ) { pFrm = pNewFrm; } ViewShell *GetShell() const { return pSh; } OutputDevice& GetOut() const { return *pOut; } OutputDevice *GetpOut() const { return pOut; } const SwScriptInfo* GetScriptInfo() const { return pScriptInfo; } const Point &GetPos() const { ASSERT( bPos, "DrawTextInfo: Undefined Position" ); return *pPos; } xub_StrLen *GetHyphPos() const { ASSERT( bHyph, "DrawTextInfo: Undefined Hyph Position" ); return pHyphPos; } const XubString &GetText() const { return *pText; } const SwWrongList* GetWrong() const { ASSERT( bWrong, "DrawTextInfo: Undefined WrongList" ); return pWrong; } const SwWrongList* GetGrammarCheck() const { ASSERT( bGrammarCheck, "DrawTextInfo: Undefined GrammarCheck List" ); return pGrammarCheck; } const SwWrongList* GetSmartTags() const { return pSmartTags; } const Size &GetSize() const { ASSERT( bSize, "DrawTextInfo: Undefined Size" ); return *pSize; } SwFont* GetFont() const { ASSERT( bFnt, "DrawTextInfo: Undefined Font" ); return pFnt; } SwUnderlineFont* GetUnderFnt() const { return pUnderFnt; } xub_StrLen GetIdx() const { return nIdx; } xub_StrLen GetLen() const { return nLen; } xub_StrLen GetOfst() const { ASSERT( bOfst, "DrawTextInfo: Undefined Offset" ); return nOfst; } xub_StrLen GetEnd() const { return nIdx + nLen; } long GetLeft() const { ASSERT( bLeft, "DrawTextInfo: Undefined left range" ); return nLeft; } long GetRight() const { ASSERT( bRight, "DrawTextInfo: Undefined right range" ); return nRight; } long GetKanaDiff() const { ASSERT( bKana, "DrawTextInfo: Undefined kana difference" ); return nKanaDiff; } USHORT GetWidth() const { return nWidth; } USHORT GetAscent() const { ASSERT( bAscent, "DrawTextInfo: Undefined Ascent" ); return nAscent; } USHORT GetKanaComp() const { return nCompress; } long GetSperren() const { ASSERT( bSperr, "DrawTextInfo: Undefined >Sperren<" ); return nSperren; } long GetKern() const { return nKern; } long GetSpace() const { ASSERT( bSpace, "DrawTextInfo: Undefined Spacing" ); return nSpace; } xub_StrLen GetNumberOfBlanks() const { ASSERT( bNumberOfBlanks, "DrawTextInfo::Undefined NumberOfBlanks" ); return nNumberOfBlanks; } BYTE GetCursorBidiLevel() const { return nCursorBidiLevel; } BOOL GetBullet() const { return bBullet; } BOOL GetUpper() const { ASSERT( bUppr, "DrawTextInfo: Undefined Upperflag" ); return bUpper; } BOOL GetDrawSpace() const { ASSERT( bDrawSp, "DrawTextInfo: Undefined DrawSpaceflag" ); return bDrawSpace; } BOOL GetGreyWave() const { return bGreyWave; } BOOL IsSpaceStop() const { return bSpaceStop; } BOOL SnapToGrid() const { return bSnapToGrid; } BOOL IsIgnoreFrmRTL() const { return bIgnoreFrmRTL; } BOOL IsPosMatchesBounds() const { return bPosMatchesBounds; } void SetOut( OutputDevice &rNew ) { pOut = &rNew; } void SetPos( const Point &rNew ) { pPos = &rNew; #ifndef PRODUCT bPos = TRUE; #endif } void SetHyphPos( xub_StrLen *pNew ) { pHyphPos = pNew; #ifndef PRODUCT bHyph = TRUE; #endif } void SetText( const XubString &rNew ) { pText = &rNew; } void SetWrong( const SwWrongList* pNew ) { pWrong = pNew; #ifndef PRODUCT bWrong = TRUE; #endif } void SetGrammarCheck( const SwWrongList* pNew ) { pGrammarCheck = pNew; #ifndef PRODUCT bGrammarCheck = TRUE; #endif } void SetSmartTags( const SwWrongList* pNew ) { pSmartTags = pNew; } void SetSize( const Size &rNew ) { pSize = &rNew; #ifndef PRODUCT bSize = TRUE; #endif } void SetFont( SwFont* pNew ) { pFnt = pNew; #ifndef PRODUCT bFnt = TRUE; #endif } void SetIdx( xub_StrLen nNew ) { nIdx = nNew; } void SetLen( xub_StrLen nNew ) { nLen = nNew; } void SetOfst( xub_StrLen nNew ) { nOfst = nNew; #ifndef PRODUCT bOfst = TRUE; #endif } void SetLeft( long nNew ) { nLeft = nNew; #ifndef PRODUCT bLeft = TRUE; #endif } void SetRight( long nNew ) { nRight = nNew; #ifndef PRODUCT bRight = TRUE; #endif } void SetKanaDiff( long nNew ) { nKanaDiff = nNew; #ifndef PRODUCT bKana = TRUE; #endif } void SetWidth( USHORT nNew ) { nWidth = nNew; } void SetAscent( USHORT nNew ) { nAscent = nNew; #ifndef PRODUCT bAscent = TRUE; #endif } void SetKern( long nNew ) { nKern = nNew; } void SetSpace( long nNew ) { if( nNew < 0 ) { nSperren = -nNew; nSpace = 0; } else { nSpace = nNew; nSperren = 0; } #ifndef PRODUCT bSpace = TRUE; bSperr = TRUE; #endif } void SetNumberOfBlanks( xub_StrLen nNew ) { #ifndef PRODUCT bNumberOfBlanks = TRUE; #endif nNumberOfBlanks = nNew; } void SetCursorBidiLevel( BYTE nNew ) { nCursorBidiLevel = nNew; } void SetKanaComp( short nNew ) { nCompress = nNew; } void SetBullet( BOOL bNew ) { bBullet = bNew; } void SetUnderFnt( SwUnderlineFont* pULFnt ) { pUnderFnt = pULFnt; } void SetUpper( BOOL bNew ) { bUpper = bNew; #ifndef PRODUCT bUppr = TRUE; #endif } void SetDrawSpace( BOOL bNew ) { bDrawSpace = bNew; #ifndef PRODUCT bDrawSp = TRUE; #endif } void SetGreyWave( BOOL bNew ) { bGreyWave = bNew; } void SetSpaceStop( BOOL bNew ) { bSpaceStop = bNew; } void SetSnapToGrid( BOOL bNew ) { bSnapToGrid = bNew; } void SetIgnoreFrmRTL( BOOL bNew ) { bIgnoreFrmRTL = bNew; } void SetPosMatchesBounds( BOOL bNew ) { bPosMatchesBounds = bNew; } void Shift( USHORT nDir ); // sets a new color at the output device if necessary // if a font is passed as argument, the change if made to the font // otherwise the font at the output device is changed // returns if the font has been changed sal_Bool ApplyAutoColor( Font* pFnt = 0 ); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.39.58); FILE MERGED 2008/03/31 16:54:13 rt 1.39.58.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawfont.hxx,v $ * $Revision: 1.40 $ * * 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 _DRAWFONT_HXX #define _DRAWFONT_HXX #include <tools/solar.h> #include <tools/string.hxx> #include <errhdl.hxx> class SwTxtFrm; class OutputDevice; class ViewShell; class SwScriptInfo; class Point; class SwWrongList; class Size; class SwFont; class Font; class SwUnderlineFont; /************************************************************************* * class SwDrawTextInfo * * encapsulates information for drawing text *************************************************************************/ class SwDrawTextInfo { const SwTxtFrm* pFrm; OutputDevice* pOut; ViewShell* pSh; const SwScriptInfo* pScriptInfo; const Point* pPos; const XubString* pText; const SwWrongList* pWrong; const SwWrongList* pGrammarCheck; const SwWrongList* pSmartTags; // SMARTTAGS const Size* pSize; SwFont *pFnt; SwUnderlineFont* pUnderFnt; xub_StrLen* pHyphPos; long nLeft; long nRight; long nKanaDiff; xub_StrLen nIdx; xub_StrLen nLen; xub_StrLen nOfst; USHORT nWidth; USHORT nAscent; USHORT nCompress; long nSperren; long nSpace; long nKern; xub_StrLen nNumberOfBlanks; BYTE nCursorBidiLevel; BOOL bBullet : 1; BOOL bUpper : 1; // Fuer Kapitaelchen: Grossbuchstaben-Flag BOOL bDrawSpace : 1; // Fuer Kapitaelchen: Unter/Durchstreichung BOOL bGreyWave : 1; // Graue Wellenlinie beim extended TextInput BOOL bSpaceStop : 1; // For underlining we need to know, if a portion // is right in front of a hole portion or a // fix margin portion. BOOL bSnapToGrid : 1; // Does paragraph snap to grid? BOOL bIgnoreFrmRTL : 1; // Paint text as if text has LTR direction, used for // line numbering BOOL bPosMatchesBounds :1; // GetCrsrOfst should not return the next // position if screen position is inside second // half of bound rect, used for Accessibility SwDrawTextInfo(); // nicht zulaessig public: #ifndef PRODUCT BOOL bPos : 1; // These flags should control, that the appropriate BOOL bWrong : 1; // Set-function has been called before calling BOOL bGrammarCheck : 1; // the Get-function of a member BOOL bSize : 1; BOOL bFnt : 1; BOOL bHyph : 1; BOOL bLeft : 1; BOOL bRight : 1; BOOL bKana : 1; BOOL bOfst : 1; BOOL bAscent: 1; BOOL bSperr : 1; BOOL bSpace : 1; BOOL bNumberOfBlanks : 1; BOOL bUppr : 1; BOOL bDrawSp: 1; #endif SwDrawTextInfo( ViewShell *pS, OutputDevice &rO, const SwScriptInfo* pSI, const XubString &rSt, xub_StrLen nI, xub_StrLen nL, USHORT nW = 0, BOOL bB = FALSE ) { pFrm = NULL; pSh = pS; pOut = &rO; pScriptInfo = pSI; pText = &rSt; nIdx = nI; nLen = nL; nKern = 0; nCompress = 0; nWidth = nW; nNumberOfBlanks = 0; nCursorBidiLevel = 0; bBullet = bB; pUnderFnt = 0; bGreyWave = FALSE; bSpaceStop = FALSE; bSnapToGrid = FALSE; bIgnoreFrmRTL = FALSE; bPosMatchesBounds = FALSE; // These values are initialized but, they have to be // set explicitly via their Set-function before they may // be accessed by their Get-function: pPos = 0; pWrong = 0; pGrammarCheck = 0; pSmartTags = 0; pSize = 0; pFnt = 0; pHyphPos = 0; nLeft = 0; nRight = 0; nKanaDiff = 0; nOfst = 0; nAscent = 0; nSperren = 0; nSpace = 0; bUpper = FALSE; bDrawSpace = FALSE; #ifndef PRODUCT // these flags control, whether the matching member variables have // been set by using the Set-function before they may be accessed // by their Get-function: bPos = bWrong = bGrammarCheck = bSize = bFnt = bAscent = bSpace = bNumberOfBlanks = bUppr = bDrawSp = bLeft = bRight = bKana = bOfst = bHyph = bSperr = FALSE; #endif } const SwTxtFrm* GetFrm() const { return pFrm; } void SetFrm( const SwTxtFrm* pNewFrm ) { pFrm = pNewFrm; } ViewShell *GetShell() const { return pSh; } OutputDevice& GetOut() const { return *pOut; } OutputDevice *GetpOut() const { return pOut; } const SwScriptInfo* GetScriptInfo() const { return pScriptInfo; } const Point &GetPos() const { ASSERT( bPos, "DrawTextInfo: Undefined Position" ); return *pPos; } xub_StrLen *GetHyphPos() const { ASSERT( bHyph, "DrawTextInfo: Undefined Hyph Position" ); return pHyphPos; } const XubString &GetText() const { return *pText; } const SwWrongList* GetWrong() const { ASSERT( bWrong, "DrawTextInfo: Undefined WrongList" ); return pWrong; } const SwWrongList* GetGrammarCheck() const { ASSERT( bGrammarCheck, "DrawTextInfo: Undefined GrammarCheck List" ); return pGrammarCheck; } const SwWrongList* GetSmartTags() const { return pSmartTags; } const Size &GetSize() const { ASSERT( bSize, "DrawTextInfo: Undefined Size" ); return *pSize; } SwFont* GetFont() const { ASSERT( bFnt, "DrawTextInfo: Undefined Font" ); return pFnt; } SwUnderlineFont* GetUnderFnt() const { return pUnderFnt; } xub_StrLen GetIdx() const { return nIdx; } xub_StrLen GetLen() const { return nLen; } xub_StrLen GetOfst() const { ASSERT( bOfst, "DrawTextInfo: Undefined Offset" ); return nOfst; } xub_StrLen GetEnd() const { return nIdx + nLen; } long GetLeft() const { ASSERT( bLeft, "DrawTextInfo: Undefined left range" ); return nLeft; } long GetRight() const { ASSERT( bRight, "DrawTextInfo: Undefined right range" ); return nRight; } long GetKanaDiff() const { ASSERT( bKana, "DrawTextInfo: Undefined kana difference" ); return nKanaDiff; } USHORT GetWidth() const { return nWidth; } USHORT GetAscent() const { ASSERT( bAscent, "DrawTextInfo: Undefined Ascent" ); return nAscent; } USHORT GetKanaComp() const { return nCompress; } long GetSperren() const { ASSERT( bSperr, "DrawTextInfo: Undefined >Sperren<" ); return nSperren; } long GetKern() const { return nKern; } long GetSpace() const { ASSERT( bSpace, "DrawTextInfo: Undefined Spacing" ); return nSpace; } xub_StrLen GetNumberOfBlanks() const { ASSERT( bNumberOfBlanks, "DrawTextInfo::Undefined NumberOfBlanks" ); return nNumberOfBlanks; } BYTE GetCursorBidiLevel() const { return nCursorBidiLevel; } BOOL GetBullet() const { return bBullet; } BOOL GetUpper() const { ASSERT( bUppr, "DrawTextInfo: Undefined Upperflag" ); return bUpper; } BOOL GetDrawSpace() const { ASSERT( bDrawSp, "DrawTextInfo: Undefined DrawSpaceflag" ); return bDrawSpace; } BOOL GetGreyWave() const { return bGreyWave; } BOOL IsSpaceStop() const { return bSpaceStop; } BOOL SnapToGrid() const { return bSnapToGrid; } BOOL IsIgnoreFrmRTL() const { return bIgnoreFrmRTL; } BOOL IsPosMatchesBounds() const { return bPosMatchesBounds; } void SetOut( OutputDevice &rNew ) { pOut = &rNew; } void SetPos( const Point &rNew ) { pPos = &rNew; #ifndef PRODUCT bPos = TRUE; #endif } void SetHyphPos( xub_StrLen *pNew ) { pHyphPos = pNew; #ifndef PRODUCT bHyph = TRUE; #endif } void SetText( const XubString &rNew ) { pText = &rNew; } void SetWrong( const SwWrongList* pNew ) { pWrong = pNew; #ifndef PRODUCT bWrong = TRUE; #endif } void SetGrammarCheck( const SwWrongList* pNew ) { pGrammarCheck = pNew; #ifndef PRODUCT bGrammarCheck = TRUE; #endif } void SetSmartTags( const SwWrongList* pNew ) { pSmartTags = pNew; } void SetSize( const Size &rNew ) { pSize = &rNew; #ifndef PRODUCT bSize = TRUE; #endif } void SetFont( SwFont* pNew ) { pFnt = pNew; #ifndef PRODUCT bFnt = TRUE; #endif } void SetIdx( xub_StrLen nNew ) { nIdx = nNew; } void SetLen( xub_StrLen nNew ) { nLen = nNew; } void SetOfst( xub_StrLen nNew ) { nOfst = nNew; #ifndef PRODUCT bOfst = TRUE; #endif } void SetLeft( long nNew ) { nLeft = nNew; #ifndef PRODUCT bLeft = TRUE; #endif } void SetRight( long nNew ) { nRight = nNew; #ifndef PRODUCT bRight = TRUE; #endif } void SetKanaDiff( long nNew ) { nKanaDiff = nNew; #ifndef PRODUCT bKana = TRUE; #endif } void SetWidth( USHORT nNew ) { nWidth = nNew; } void SetAscent( USHORT nNew ) { nAscent = nNew; #ifndef PRODUCT bAscent = TRUE; #endif } void SetKern( long nNew ) { nKern = nNew; } void SetSpace( long nNew ) { if( nNew < 0 ) { nSperren = -nNew; nSpace = 0; } else { nSpace = nNew; nSperren = 0; } #ifndef PRODUCT bSpace = TRUE; bSperr = TRUE; #endif } void SetNumberOfBlanks( xub_StrLen nNew ) { #ifndef PRODUCT bNumberOfBlanks = TRUE; #endif nNumberOfBlanks = nNew; } void SetCursorBidiLevel( BYTE nNew ) { nCursorBidiLevel = nNew; } void SetKanaComp( short nNew ) { nCompress = nNew; } void SetBullet( BOOL bNew ) { bBullet = bNew; } void SetUnderFnt( SwUnderlineFont* pULFnt ) { pUnderFnt = pULFnt; } void SetUpper( BOOL bNew ) { bUpper = bNew; #ifndef PRODUCT bUppr = TRUE; #endif } void SetDrawSpace( BOOL bNew ) { bDrawSpace = bNew; #ifndef PRODUCT bDrawSp = TRUE; #endif } void SetGreyWave( BOOL bNew ) { bGreyWave = bNew; } void SetSpaceStop( BOOL bNew ) { bSpaceStop = bNew; } void SetSnapToGrid( BOOL bNew ) { bSnapToGrid = bNew; } void SetIgnoreFrmRTL( BOOL bNew ) { bIgnoreFrmRTL = bNew; } void SetPosMatchesBounds( BOOL bNew ) { bPosMatchesBounds = bNew; } void Shift( USHORT nDir ); // sets a new color at the output device if necessary // if a font is passed as argument, the change if made to the font // otherwise the font at the output device is changed // returns if the font has been changed sal_Bool ApplyAutoColor( Font* pFnt = 0 ); }; #endif <|endoftext|>
<commit_before>//===- SystemUtils.cpp - Utilities for low-level system tasks -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains functions used to do a variety of low-level, often // system-specific, tasks. // //===----------------------------------------------------------------------===// #include "llvm/Support/SystemUtils.h" #include "llvm/System/Process.h" #include "llvm/System/Program.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; bool llvm::CheckBitcodeOutputToConsole(raw_ostream &stream_to_check, bool print_warning) { if (stream_to_check.is_displayed()) { if (print_warning) { errs() << "WARNING: You're attempting to print out a bitcode file.\n" << "This is inadvisable as it may cause display problems. If\n" << "you REALLY want to taste LLVM bitcode first-hand, you\n" << "can force output with the `-f' option.\n\n"; } return true; } return false; } /// FindExecutable - Find a named executable, giving the argv[0] of program /// being executed. This allows us to find another LLVM tool if it is built in /// the same directory. If the executable cannot be found, return an /// empty string. /// @brief Find a named executable. #undef FindExecutable // needed on windows :( sys::Path llvm::FindExecutable(const std::string &ExeName, const char *Argv0, void *MainAddr) { // Check the directory that the calling program is in. We can do // this if ProgramPath contains at least one / character, indicating that it // is a relative path to the executable itself. sys::Path Result = sys::Path::GetMainExecutable(Argv0, MainAddr); Result.eraseComponent(); if (!Result.isEmpty()) { Result.appendComponent(ExeName); if (Result.canExecute()) return Result; // If the path is absolute (and it usually is), call FindProgramByName to // allow it to try platform-specific logic, such as appending a .exe suffix // on Windows. Don't do this if we somehow have a relative path, because // we don't want to go searching the PATH and accidentally find an unrelated // version of the program. if (Result.isAbsolute()) { Result = sys::Program::FindProgramByName(Result.str()); if (!Result.empty()) return Result; } } return sys::Path(); } <commit_msg>Remove an unnecessary check and an unnecessary temporary.<commit_after>//===- SystemUtils.cpp - Utilities for low-level system tasks -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains functions used to do a variety of low-level, often // system-specific, tasks. // //===----------------------------------------------------------------------===// #include "llvm/Support/SystemUtils.h" #include "llvm/System/Process.h" #include "llvm/System/Program.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; bool llvm::CheckBitcodeOutputToConsole(raw_ostream &stream_to_check, bool print_warning) { if (stream_to_check.is_displayed()) { if (print_warning) { errs() << "WARNING: You're attempting to print out a bitcode file.\n" << "This is inadvisable as it may cause display problems. If\n" << "you REALLY want to taste LLVM bitcode first-hand, you\n" << "can force output with the `-f' option.\n\n"; } return true; } return false; } /// FindExecutable - Find a named executable, giving the argv[0] of program /// being executed. This allows us to find another LLVM tool if it is built in /// the same directory. If the executable cannot be found, return an /// empty string. /// @brief Find a named executable. #undef FindExecutable // needed on windows :( sys::Path llvm::FindExecutable(const std::string &ExeName, const char *Argv0, void *MainAddr) { // Check the directory that the calling program is in. We can do // this if ProgramPath contains at least one / character, indicating that it // is a relative path to the executable itself. sys::Path Result = sys::Path::GetMainExecutable(Argv0, MainAddr); Result.eraseComponent(); if (!Result.isEmpty()) { Result.appendComponent(ExeName); if (Result.canExecute()) return Result; // If the path is absolute (and it usually is), call FindProgramByName to // allow it to try platform-specific logic, such as appending a .exe suffix // on Windows. Don't do this if we somehow have a relative path, because // we don't want to go searching the PATH and accidentally find an unrelated // version of the program. if (Result.isAbsolute()) { Result = sys::Program::FindProgramByName(Result.str()); return Result; } } return Result; } <|endoftext|>
<commit_before><commit_msg>fix a big pile of the crash tester .doc import failures<commit_after><|endoftext|>
<commit_before><commit_msg>coverity#1158240 Dereference before null check<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtxml.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2006-03-16 12:44:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _WRTXML_HXX #define _WRTXML_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif class SwDoc; class SwPaM; class SfxMedium; namespace com { namespace sun { namespace start { namespace uno { template<class A> class Reference; } namespace uno { template<class A> class Sequence; } namespace uno { class Any; } namespace lang { class XComponent; } namespace lang { class XMultiServiceFactory; } namespace beans { struct PropertyValue; } } } }; class SwXMLWriter : public StgWriter { sal_uInt32 _Write( SfxMedium* pTargetMedium = NULL ); protected: virtual ULONG WriteStorage(); virtual ULONG WriteMedium( SfxMedium& aTargetMedium ); public: SwXMLWriter( const String& rBaseURL ); virtual ~SwXMLWriter(); virtual ULONG Write( SwPaM&, SfxMedium&, const String* = 0 ); private: // helper methods to write XML streams /// write a single XML stream into the package sal_Bool WriteThroughComponent( /// the component we export const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const sal_Char* pStreamName, /// the stream name /// service factory for pServiceName const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, /// service name of the component /// the argument (XInitialization) const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, /// output descriptor const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc, sal_Bool bPlainStream ); /// neither compress nor encrypt /// write a single output stream /// (to be called either directly or by WriteThroughComponent(...)) sal_Bool WriteThroughComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> & xOutputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc ); }; #endif // _WRTXML_HXX <commit_msg>INTEGRATION: CWS writercorehandoff (1.8.252); FILE MERGED 2006/04/05 13:22:29 tra 1.8.252.4: RESYNC: (1.10-1.11); FILE MERGED 2005/11/04 12:58:09 tra 1.8.252.3: #i50348# 2005/09/13 15:44:00 tra 1.8.252.2: RESYNC: (1.8-1.9); FILE MERGED 2005/06/07 14:15:13 fme 1.8.252.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtxml.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2006-08-14 17:21:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _WRTXML_HXX #define _WRTXML_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif class SwPaM; class SfxMedium; namespace com { namespace sun { namespace start { namespace uno { template<class A> class Reference; } namespace uno { template<class A> class Sequence; } namespace uno { class Any; } namespace lang { class XComponent; } namespace lang { class XMultiServiceFactory; } namespace beans { struct PropertyValue; } } } }; class SwXMLWriter : public StgWriter { sal_uInt32 _Write( SfxMedium* pTargetMedium = NULL ); protected: virtual ULONG WriteStorage(); virtual ULONG WriteMedium( SfxMedium& aTargetMedium ); public: SwXMLWriter( const String& rBaseURL ); virtual ~SwXMLWriter(); virtual ULONG Write( SwPaM&, SfxMedium&, const String* = 0 ); private: // helper methods to write XML streams /// write a single XML stream into the package sal_Bool WriteThroughComponent( /// the component we export const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const sal_Char* pStreamName, /// the stream name /// service factory for pServiceName const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, /// service name of the component /// the argument (XInitialization) const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, /// output descriptor const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc, sal_Bool bPlainStream ); /// neither compress nor encrypt /// write a single output stream /// (to be called either directly or by WriteThroughComponent(...)) sal_Bool WriteThroughComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> & xOutputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc ); }; #endif // _WRTXML_HXX <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "OSVRUpdateCallback.h" #include "OSGMathInterop.h" #include "OSVRInterfaceData.h" #include "OSVRContext.h" // Library/third-party includes #include <osvr/ClientKit/ClientKit.h> #include <osg/ref_ptr> #include <osg/PositionAttitudeTransform> #include <osg/MatrixTransform> #include <osg/NodeCallback> #include <osg/LineWidth> #include <osg/Version> #include <osgDB/ReadFile> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> // Standard includes #include <iostream> #include <cmath> // for floor /// @brief A struct that does our casting for us. struct CallbackHelper { CallbackHelper(void *userdata) : xform(static_cast<osg::MatrixTransform *>(userdata)), iface(dynamic_cast<OSVRInterfaceData *>(xform->getUserData())) {} osg::MatrixTransform *xform; OSVRInterfaceData *iface; }; void poseCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/, const OSVR_PoseReport *report) { CallbackHelper cb(userdata); cb.xform->setMatrix(toMatrix(report->pose)); // std::cout << "Got report for " << cb.iface->getPath() << std::endl; } void orientationCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/, const OSVR_OrientationReport *report) { CallbackHelper cb(userdata); osg::Matrix mat = cb.xform->getMatrix(); mat.setRotate(toQuat(report->rotation)); cb.xform->setMatrix(mat); // std::cout << "Got report for " << cb.iface->getPath() << std::endl; } /// A little utility class to draw a simple grid. class Grid : public osg::Group { public: Grid(unsigned int line_count = 49, float line_spacing = 1.0f, unsigned int bold_every_n = 0) { this->addChild(make_grid(line_count, line_spacing)); std::cout << "Regular: count = " << line_count << ", spacing = " << line_spacing << std::endl; // Bold grid if (bold_every_n > 0) { line_count = static_cast<unsigned int>(std::floor(line_count / bold_every_n)) + 1; line_spacing *= bold_every_n; std::cout << "Bold: count = " << line_count << ", spacing = " << line_spacing << std::endl; osg::MatrixTransform* mt = make_grid(line_count, line_spacing); osg::StateSet* stateset = new osg::StateSet(); osg::LineWidth* linewidth = new osg::LineWidth(); linewidth->setWidth(2.0f); stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); mt->setStateSet(stateset); this->addChild(mt); } // Heavy origin lines this->addChild(make_axes(line_count, line_spacing)); } osg::MatrixTransform* make_grid(const unsigned int line_count, const float line_spacing) { const unsigned int numVertices = 2 * 2 * line_count; osg::Vec3Array* vertices = new osg::Vec3Array(numVertices); float length = static_cast<float>(line_count - 1) * line_spacing; osg::Vec3Array::size_type ptr = 0; for (unsigned int i = 0; i < line_count; ++i) { (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing, length / 2.0f, 0.0f); (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing, -length / 2.0f, 0.0f); } for (unsigned int i = 0; i < line_count; ++i) { (*vertices)[ptr++].set(length / 2.0f, -length / 2.0f + i * line_spacing, 0.0f); (*vertices)[ptr++].set(-length / 2.0f, -length / 2.0f + i * line_spacing, 0.0f); } osg::Geometry* geometry = new osg::Geometry; geometry->setVertexArray(vertices); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, static_cast<GLsizei>(numVertices))); osg::Geode* geode = new osg::Geode; geode->addDrawable(geometry); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0); osg::MatrixTransform* grid_transform = new osg::MatrixTransform; grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0)); grid_transform->addChild(geode); return grid_transform; } osg::MatrixTransform* make_axes(const unsigned int line_count, const float line_spacing) { const float length = (line_count - 1) * line_spacing; const int num_vertices = 6; osg::Vec3Array* vertices = new osg::Vec3Array(num_vertices); (*vertices)[0].set(-length / 2.0f, 0.0f, 0.0f); (*vertices)[1].set(length / 2.0f, 0.0f, 0.0f); (*vertices)[2].set(0.0f, -length / 2.0f, 0.0f); (*vertices)[3].set(0.0f, length / 2.0f, 0.0f); (*vertices)[4].set(0.0f, 0.0f, -length / 2.0f); (*vertices)[5].set(0.0f, 0.0f, length / 2.0f); osg::Vec4Array* colors = new osg::Vec4Array(num_vertices); (*colors)[0].set(1.0, 0.0, 0.0, 1.0); (*colors)[1].set(1.0, 0.0, 0.0, 1.0); (*colors)[2].set(0.0, 0.0, 1.0, 1.0); (*colors)[3].set(0.0, 0.0, 1.0, 1.0); (*colors)[4].set(0.0, 1.0, 0.0, 1.0); (*colors)[5].set(0.0, 1.0, 0.0, 1.0); osg::Geometry* geometry = new osg::Geometry; geometry->setVertexArray(vertices); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, num_vertices)); #if OSG_VERSION_GREATER_THAN(3,1,7) geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX); #else geometry->setColorArray(colors); geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX); #endif osg::Geode* geode = new osg::Geode; geode->addDrawable(geometry); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0); osg::MatrixTransform* grid_transform = new osg::MatrixTransform; grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0)); grid_transform->addChild(geode); osg::StateSet* stateset = new osg::StateSet(); osg::LineWidth* linewidth = new osg::LineWidth(); linewidth->setWidth(4.0f); stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); grid_transform->setStateSet(stateset); return grid_transform; } }; class TrackerViewApp { public: static double worldAxesScale() { return 0.2; } static double trackerAxesScale() { return 0.1; } TrackerViewApp() : m_ctx(new OSVRContext( "org.opengoggles.osvrtrackerview")) /// Set up OSVR: making an OSG /// ref-counted object hold /// the context. , m_scene(new osg::PositionAttitudeTransform), m_smallAxes(new osg::MatrixTransform), m_numTrackers(0) { /// Transform into default OSVR coordinate system: z near. m_scene->setAttitude(osg::Quat(90, osg::Vec3(1, 0, 0))); /// Set the root node's update callback to run the OSVR update, /// and give it the context ref m_scene->setUpdateCallback(new OSVRUpdateCallback); m_scene->setUserData(m_ctx.get()); /// Load the basic model for axes osg::ref_ptr<osg::Node> axes = osgDB::readNodeFile("RPAxes.osg"); //{ // /// World axes // osg::ref_ptr<osg::MatrixTransform> worldAxes = // new osg::MatrixTransform; // worldAxes->setMatrix(osg::Matrixd::scale( // worldAxesScale(), worldAxesScale(), worldAxesScale())); // worldAxes->addChild(axes); // m_scene->addChild(worldAxes.get()); //} /// Small axes for trackers m_smallAxes->setMatrix(osg::Matrixd::scale( trackerAxesScale(), trackerAxesScale(), trackerAxesScale())); m_smallAxes->addChild(axes.get()); /// Grid m_scene->addChild(new Grid(16, 0.1f, 5)); } osg::ref_ptr<osg::PositionAttitudeTransform> getScene() { return m_scene; } void addPoseTracker(std::string const &path) { m_addTracker(&poseCallback, path); m_numTrackers++; } void addOrientationTracker(std::string const &path) { osg::ref_ptr<osg::MatrixTransform> node = m_addTracker(&orientationCallback, path); /* /// Offset orientation-only trackers up by 1 unit (meter) osg::Matrix mat; mat.setTrans(0, 1, 0); node->setMatrix(mat); */ m_numTrackers++; } int getNumTrackers() const { return m_numTrackers; } private: template <typename CallbackType> osg::ref_ptr<osg::MatrixTransform> m_addTracker(CallbackType cb, std::string const &path) { /// Make scenegraph portion osg::ref_ptr<osg::MatrixTransform> node = new osg::MatrixTransform; node->addChild(m_smallAxes); m_scene->addChild(node); /// Get OSVR interface and set callback osg::ref_ptr<OSVRInterfaceData> data = m_ctx->getInterface(path); data->getInterface().registerCallback(cb, static_cast<void *>(node.get())); /// Transfer ownership of the interface holder to the node node->setUserData(data.get()); return node; } osg::ref_ptr<OSVRContext> m_ctx; osg::ref_ptr<osg::PositionAttitudeTransform> m_scene; osg::ref_ptr<osg::MatrixTransform> m_smallAxes; int m_numTrackers; }; int main(int argc, char **argv) { /// Parse arguments osg::ArgumentParser args(&argc, argv); args.getApplicationUsage()->setApplicationName(args.getApplicationName()); args.getApplicationUsage()->setDescription( args.getApplicationName() + " is a tool for visualizing tracking data from the OSVR system."); args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName() + " [options] osvrpath ..."); args.getApplicationUsage()->addCommandLineOption("--orientation <path>", "add an orientation tracker"); args.getApplicationUsage()->addCommandLineOption("--pose <path>", "add a pose tracker"); /// Init the OSG viewer osgViewer::Viewer viewer(args); viewer.setUpViewInWindow(20, 20, 640, 480); osg::ApplicationUsage::Type helpType; if ((helpType = args.readHelpType()) != osg::ApplicationUsage::NO_HELP) { args.getApplicationUsage()->write(std::cerr); return 1; } if (args.errors()) { args.writeErrorMessages(std::cerr); return 1; } TrackerViewApp app; std::string path; // Get pose paths while (args.read("--pose", path)) { app.addPoseTracker(path); } // Get orientation paths while (args.read("--orientation", path)) { app.addOrientationTracker(path); } // Assume free strings are pose paths for (int pos = 1; pos < args.argc(); ++pos) { if (args.isOption(pos)) continue; app.addPoseTracker(args[pos]); } // If no trackers were specified, fall back on these defaults if (0 == app.getNumTrackers()) { app.addPoseTracker("/me/hands/left"); app.addPoseTracker("/me/hands/right"); app.addOrientationTracker("/me/head"); } args.reportRemainingOptionsAsUnrecognized(); if (args.errors()) { args.writeErrorMessages(std::cerr); return 1; } viewer.setSceneData(app.getScene()); viewer.setCameraManipulator(new osgGA::TrackballManipulator()); viewer.addEventHandler(new osgViewer::WindowSizeHandler); /// Go! viewer.realize(); return viewer.run(); } <commit_msg>Change app ID<commit_after>/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "OSVRUpdateCallback.h" #include "OSGMathInterop.h" #include "OSVRInterfaceData.h" #include "OSVRContext.h" // Library/third-party includes #include <osvr/ClientKit/ClientKit.h> #include <osg/ref_ptr> #include <osg/PositionAttitudeTransform> #include <osg/MatrixTransform> #include <osg/NodeCallback> #include <osg/LineWidth> #include <osg/Version> #include <osgDB/ReadFile> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> // Standard includes #include <iostream> #include <cmath> // for floor /// @brief A struct that does our casting for us. struct CallbackHelper { CallbackHelper(void *userdata) : xform(static_cast<osg::MatrixTransform *>(userdata)), iface(dynamic_cast<OSVRInterfaceData *>(xform->getUserData())) {} osg::MatrixTransform *xform; OSVRInterfaceData *iface; }; void poseCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/, const OSVR_PoseReport *report) { CallbackHelper cb(userdata); cb.xform->setMatrix(toMatrix(report->pose)); // std::cout << "Got report for " << cb.iface->getPath() << std::endl; } void orientationCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/, const OSVR_OrientationReport *report) { CallbackHelper cb(userdata); osg::Matrix mat = cb.xform->getMatrix(); mat.setRotate(toQuat(report->rotation)); cb.xform->setMatrix(mat); // std::cout << "Got report for " << cb.iface->getPath() << std::endl; } /// A little utility class to draw a simple grid. class Grid : public osg::Group { public: Grid(unsigned int line_count = 49, float line_spacing = 1.0f, unsigned int bold_every_n = 0) { this->addChild(make_grid(line_count, line_spacing)); std::cout << "Regular: count = " << line_count << ", spacing = " << line_spacing << std::endl; // Bold grid if (bold_every_n > 0) { line_count = static_cast<unsigned int>(std::floor(line_count / bold_every_n)) + 1; line_spacing *= bold_every_n; std::cout << "Bold: count = " << line_count << ", spacing = " << line_spacing << std::endl; osg::MatrixTransform* mt = make_grid(line_count, line_spacing); osg::StateSet* stateset = new osg::StateSet(); osg::LineWidth* linewidth = new osg::LineWidth(); linewidth->setWidth(2.0f); stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); mt->setStateSet(stateset); this->addChild(mt); } // Heavy origin lines this->addChild(make_axes(line_count, line_spacing)); } osg::MatrixTransform* make_grid(const unsigned int line_count, const float line_spacing) { const unsigned int numVertices = 2 * 2 * line_count; osg::Vec3Array* vertices = new osg::Vec3Array(numVertices); float length = static_cast<float>(line_count - 1) * line_spacing; osg::Vec3Array::size_type ptr = 0; for (unsigned int i = 0; i < line_count; ++i) { (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing, length / 2.0f, 0.0f); (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing, -length / 2.0f, 0.0f); } for (unsigned int i = 0; i < line_count; ++i) { (*vertices)[ptr++].set(length / 2.0f, -length / 2.0f + i * line_spacing, 0.0f); (*vertices)[ptr++].set(-length / 2.0f, -length / 2.0f + i * line_spacing, 0.0f); } osg::Geometry* geometry = new osg::Geometry; geometry->setVertexArray(vertices); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, static_cast<GLsizei>(numVertices))); osg::Geode* geode = new osg::Geode; geode->addDrawable(geometry); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0); osg::MatrixTransform* grid_transform = new osg::MatrixTransform; grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0)); grid_transform->addChild(geode); return grid_transform; } osg::MatrixTransform* make_axes(const unsigned int line_count, const float line_spacing) { const float length = (line_count - 1) * line_spacing; const int num_vertices = 6; osg::Vec3Array* vertices = new osg::Vec3Array(num_vertices); (*vertices)[0].set(-length / 2.0f, 0.0f, 0.0f); (*vertices)[1].set(length / 2.0f, 0.0f, 0.0f); (*vertices)[2].set(0.0f, -length / 2.0f, 0.0f); (*vertices)[3].set(0.0f, length / 2.0f, 0.0f); (*vertices)[4].set(0.0f, 0.0f, -length / 2.0f); (*vertices)[5].set(0.0f, 0.0f, length / 2.0f); osg::Vec4Array* colors = new osg::Vec4Array(num_vertices); (*colors)[0].set(1.0, 0.0, 0.0, 1.0); (*colors)[1].set(1.0, 0.0, 0.0, 1.0); (*colors)[2].set(0.0, 0.0, 1.0, 1.0); (*colors)[3].set(0.0, 0.0, 1.0, 1.0); (*colors)[4].set(0.0, 1.0, 0.0, 1.0); (*colors)[5].set(0.0, 1.0, 0.0, 1.0); osg::Geometry* geometry = new osg::Geometry; geometry->setVertexArray(vertices); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, num_vertices)); #if OSG_VERSION_GREATER_THAN(3,1,7) geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX); #else geometry->setColorArray(colors); geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX); #endif osg::Geode* geode = new osg::Geode; geode->addDrawable(geometry); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0); osg::MatrixTransform* grid_transform = new osg::MatrixTransform; grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0)); grid_transform->addChild(geode); osg::StateSet* stateset = new osg::StateSet(); osg::LineWidth* linewidth = new osg::LineWidth(); linewidth->setWidth(4.0f); stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); grid_transform->setStateSet(stateset); return grid_transform; } }; class TrackerViewApp { public: static double worldAxesScale() { return 0.2; } static double trackerAxesScale() { return 0.1; } TrackerViewApp() : m_ctx(new OSVRContext( "org.osvr.trackerview")) /// Set up OSVR: making an OSG /// ref-counted object hold /// the context. , m_scene(new osg::PositionAttitudeTransform), m_smallAxes(new osg::MatrixTransform), m_numTrackers(0) { /// Transform into default OSVR coordinate system: z near. m_scene->setAttitude(osg::Quat(90, osg::Vec3(1, 0, 0))); /// Set the root node's update callback to run the OSVR update, /// and give it the context ref m_scene->setUpdateCallback(new OSVRUpdateCallback); m_scene->setUserData(m_ctx.get()); /// Load the basic model for axes osg::ref_ptr<osg::Node> axes = osgDB::readNodeFile("RPAxes.osg"); //{ // /// World axes // osg::ref_ptr<osg::MatrixTransform> worldAxes = // new osg::MatrixTransform; // worldAxes->setMatrix(osg::Matrixd::scale( // worldAxesScale(), worldAxesScale(), worldAxesScale())); // worldAxes->addChild(axes); // m_scene->addChild(worldAxes.get()); //} /// Small axes for trackers m_smallAxes->setMatrix(osg::Matrixd::scale( trackerAxesScale(), trackerAxesScale(), trackerAxesScale())); m_smallAxes->addChild(axes.get()); /// Grid m_scene->addChild(new Grid(16, 0.1f, 5)); } osg::ref_ptr<osg::PositionAttitudeTransform> getScene() { return m_scene; } void addPoseTracker(std::string const &path) { m_addTracker(&poseCallback, path); m_numTrackers++; } void addOrientationTracker(std::string const &path) { osg::ref_ptr<osg::MatrixTransform> node = m_addTracker(&orientationCallback, path); /* /// Offset orientation-only trackers up by 1 unit (meter) osg::Matrix mat; mat.setTrans(0, 1, 0); node->setMatrix(mat); */ m_numTrackers++; } int getNumTrackers() const { return m_numTrackers; } private: template <typename CallbackType> osg::ref_ptr<osg::MatrixTransform> m_addTracker(CallbackType cb, std::string const &path) { /// Make scenegraph portion osg::ref_ptr<osg::MatrixTransform> node = new osg::MatrixTransform; node->addChild(m_smallAxes); m_scene->addChild(node); /// Get OSVR interface and set callback osg::ref_ptr<OSVRInterfaceData> data = m_ctx->getInterface(path); data->getInterface().registerCallback(cb, static_cast<void *>(node.get())); /// Transfer ownership of the interface holder to the node node->setUserData(data.get()); return node; } osg::ref_ptr<OSVRContext> m_ctx; osg::ref_ptr<osg::PositionAttitudeTransform> m_scene; osg::ref_ptr<osg::MatrixTransform> m_smallAxes; int m_numTrackers; }; int main(int argc, char **argv) { /// Parse arguments osg::ArgumentParser args(&argc, argv); args.getApplicationUsage()->setApplicationName(args.getApplicationName()); args.getApplicationUsage()->setDescription( args.getApplicationName() + " is a tool for visualizing tracking data from the OSVR system."); args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName() + " [options] osvrpath ..."); args.getApplicationUsage()->addCommandLineOption("--orientation <path>", "add an orientation tracker"); args.getApplicationUsage()->addCommandLineOption("--pose <path>", "add a pose tracker"); /// Init the OSG viewer osgViewer::Viewer viewer(args); viewer.setUpViewInWindow(20, 20, 640, 480); osg::ApplicationUsage::Type helpType; if ((helpType = args.readHelpType()) != osg::ApplicationUsage::NO_HELP) { args.getApplicationUsage()->write(std::cerr); return 1; } if (args.errors()) { args.writeErrorMessages(std::cerr); return 1; } TrackerViewApp app; std::string path; // Get pose paths while (args.read("--pose", path)) { app.addPoseTracker(path); } // Get orientation paths while (args.read("--orientation", path)) { app.addOrientationTracker(path); } // Assume free strings are pose paths for (int pos = 1; pos < args.argc(); ++pos) { if (args.isOption(pos)) continue; app.addPoseTracker(args[pos]); } // If no trackers were specified, fall back on these defaults if (0 == app.getNumTrackers()) { app.addPoseTracker("/me/hands/left"); app.addPoseTracker("/me/hands/right"); app.addOrientationTracker("/me/head"); } args.reportRemainingOptionsAsUnrecognized(); if (args.errors()) { args.writeErrorMessages(std::cerr); return 1; } viewer.setSceneData(app.getScene()); viewer.setCameraManipulator(new osgGA::TrackballManipulator()); viewer.addEventHandler(new osgViewer::WindowSizeHandler); /// Go! viewer.realize(); return viewer.run(); } <|endoftext|>
<commit_before>//===-- asan_malloc_mac.cc ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Mac-specific malloc interception. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_MAC #include <AvailabilityMacros.h> #include <CoreFoundation/CFBase.h> #include <dlfcn.h> #include <malloc/malloc.h> #include <sys/mman.h> #include "asan_allocator.h" #include "asan_interceptors.h" #include "asan_internal.h" #include "asan_report.h" #include "asan_stack.h" #include "asan_stats.h" #include "sanitizer_common/sanitizer_mac.h" // Similar code is used in Google Perftools, // http://code.google.com/p/google-perftools. // ---------------------- Replacement functions ---------------- {{{1 using namespace __asan; // NOLINT // TODO(glider): do we need both zones? static malloc_zone_t *system_malloc_zone = 0; static malloc_zone_t asan_zone; INTERCEPTOR(malloc_zone_t *, malloc_create_zone, vm_size_t start_size, unsigned zone_flags) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; uptr page_size = GetPageSizeCached(); uptr allocated_size = RoundUpTo(sizeof(asan_zone), page_size); malloc_zone_t *new_zone = (malloc_zone_t*)asan_memalign(page_size, allocated_size, &stack, FROM_MALLOC); internal_memcpy(new_zone, &asan_zone, sizeof(asan_zone)); new_zone->zone_name = NULL; // The name will be changed anyway. if (GetMacosVersion() >= MACOS_VERSION_LION) { // Prevent the client app from overwriting the zone contents. // Library functions that need to modify the zone will set PROT_WRITE on it. // This matches the behavior of malloc_create_zone() on OSX 10.7 and higher. mprotect(new_zone, allocated_size, PROT_READ); } return new_zone; } INTERCEPTOR(malloc_zone_t *, malloc_default_zone, void) { ENSURE_ASAN_INITED(); return &asan_zone; } INTERCEPTOR(malloc_zone_t *, malloc_default_purgeable_zone, void) { // FIXME: ASan should support purgeable allocations. // https://code.google.com/p/address-sanitizer/issues/detail?id=139 ENSURE_ASAN_INITED(); return &asan_zone; } INTERCEPTOR(void, malloc_make_purgeable, void *ptr) { // FIXME: ASan should support purgeable allocations. Ignoring them is fine // for now. ENSURE_ASAN_INITED(); } INTERCEPTOR(int, malloc_make_nonpurgeable, void *ptr) { // FIXME: ASan should support purgeable allocations. Ignoring them is fine // for now. ENSURE_ASAN_INITED(); // Must return 0 if the contents were not purged since the last call to // malloc_make_purgeable(). return 0; } INTERCEPTOR(void, malloc_set_zone_name, malloc_zone_t *zone, const char *name) { ENSURE_ASAN_INITED(); // Allocate |strlen("asan-") + 1 + internal_strlen(name)| bytes. size_t buflen = 6 + (name ? internal_strlen(name) : 0); InternalScopedString new_name(buflen); if (name && zone->introspect == asan_zone.introspect) { new_name.append("asan-%s", name); name = new_name.data(); } // Call the system malloc's implementation for both external and our zones, // since that appropriately changes VM region protections on the zone. REAL(malloc_set_zone_name)(zone, name); } INTERCEPTOR(void *, malloc, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; void *res = asan_malloc(size, &stack); return res; } INTERCEPTOR(void, free, void *ptr) { ENSURE_ASAN_INITED(); if (!ptr) return; GET_STACK_TRACE_FREE; asan_free(ptr, &stack, FROM_MALLOC); } INTERCEPTOR(void *, realloc, void *ptr, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } INTERCEPTOR(void *, calloc, size_t nmemb, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } INTERCEPTOR(void *, valloc, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; return asan_memalign(GetPageSizeCached(), size, &stack, FROM_MALLOC); } INTERCEPTOR(size_t, malloc_good_size, size_t size) { ENSURE_ASAN_INITED(); return asan_zone.introspect->good_size(&asan_zone, size); } INTERCEPTOR(int, posix_memalign, void **memptr, size_t alignment, size_t size) { ENSURE_ASAN_INITED(); CHECK(memptr); GET_STACK_TRACE_MALLOC; void *result = asan_memalign(alignment, size, &stack, FROM_MALLOC); if (result) { *memptr = result; return 0; } return -1; } namespace { // TODO(glider): the __asan_mz_* functions should be united with the Linux // wrappers, as they are basically copied from there. extern "C" SANITIZER_INTERFACE_ATTRIBUTE size_t __asan_mz_size(malloc_zone_t* zone, const void* ptr) { return asan_mz_size(ptr); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_malloc(malloc_zone_t *zone, uptr size) { if (UNLIKELY(!asan_inited)) { CHECK(system_malloc_zone); return malloc_zone_malloc(system_malloc_zone, size); } GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_calloc(malloc_zone_t *zone, size_t nmemb, size_t size) { if (UNLIKELY(!asan_inited)) { // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. const size_t kCallocPoolSize = 1024; static uptr calloc_memory_for_dlsym[kCallocPoolSize]; static size_t allocated; size_t size_in_words = ((nmemb * size) + kWordSize - 1) / kWordSize; void *mem = (void*)&calloc_memory_for_dlsym[allocated]; allocated += size_in_words; CHECK(allocated < kCallocPoolSize); return mem; } GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_valloc(malloc_zone_t *zone, size_t size) { if (UNLIKELY(!asan_inited)) { CHECK(system_malloc_zone); return malloc_zone_valloc(system_malloc_zone, size); } GET_STACK_TRACE_MALLOC; return asan_memalign(GetPageSizeCached(), size, &stack, FROM_MALLOC); } #define GET_ZONE_FOR_PTR(ptr) \ malloc_zone_t *zone_ptr = malloc_zone_from_ptr(ptr); \ const char *zone_name = (zone_ptr == 0) ? 0 : zone_ptr->zone_name void ALWAYS_INLINE free_common(void *context, void *ptr) { if (!ptr) return; GET_STACK_TRACE_FREE; // FIXME: need to retire this flag. if (!flags()->mac_ignore_invalid_free) { asan_free(ptr, &stack, FROM_MALLOC); } else { GET_ZONE_FOR_PTR(ptr); WarnMacFreeUnallocated((uptr)ptr, (uptr)zone_ptr, zone_name, &stack); return; } } // TODO(glider): the allocation callbacks need to be refactored. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __asan_mz_free(malloc_zone_t *zone, void *ptr) { free_common(zone, ptr); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_realloc(malloc_zone_t *zone, void *ptr, size_t size) { if (!ptr) { GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } else { if (asan_mz_size(ptr)) { GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } else { // We can't recover from reallocating an unknown address, because // this would require reading at most |size| bytes from // potentially unaccessible memory. GET_STACK_TRACE_FREE; GET_ZONE_FOR_PTR(ptr); ReportMacMzReallocUnknown((uptr)ptr, (uptr)zone_ptr, zone_name, &stack); } } } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __asan_mz_destroy(malloc_zone_t* zone) { // A no-op -- we will not be destroyed! Report("__asan_mz_destroy() called -- ignoring\n"); } // from AvailabilityMacros.h #if defined(MAC_OS_X_VERSION_10_6) && \ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_memalign(malloc_zone_t *zone, size_t align, size_t size) { if (UNLIKELY(!asan_inited)) { CHECK(system_malloc_zone); return malloc_zone_memalign(system_malloc_zone, align, size); } GET_STACK_TRACE_MALLOC; return asan_memalign(align, size, &stack, FROM_MALLOC); } // This function is currently unused, and we build with -Werror. #if 0 void __asan_mz_free_definite_size( malloc_zone_t* zone, void *ptr, size_t size) { // TODO(glider): check that |size| is valid. UNIMPLEMENTED(); } #endif #endif kern_return_t mi_enumerator(task_t task, void *, unsigned type_mask, vm_address_t zone_address, memory_reader_t reader, vm_range_recorder_t recorder) { // Should enumerate all the pointers we have. Seems like a lot of work. return KERN_FAILURE; } size_t mi_good_size(malloc_zone_t *zone, size_t size) { // I think it's always safe to return size, but we maybe could do better. return size; } boolean_t mi_check(malloc_zone_t *zone) { UNIMPLEMENTED(); } void mi_print(malloc_zone_t *zone, boolean_t verbose) { UNIMPLEMENTED(); } void mi_log(malloc_zone_t *zone, void *address) { // I don't think we support anything like this } void mi_force_lock(malloc_zone_t *zone) { asan_mz_force_lock(); } void mi_force_unlock(malloc_zone_t *zone) { asan_mz_force_unlock(); } void mi_statistics(malloc_zone_t *zone, malloc_statistics_t *stats) { AsanMallocStats malloc_stats; FillMallocStatistics(&malloc_stats); CHECK(sizeof(malloc_statistics_t) == sizeof(AsanMallocStats)); internal_memcpy(stats, &malloc_stats, sizeof(malloc_statistics_t)); } #if defined(MAC_OS_X_VERSION_10_6) && \ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 boolean_t mi_zone_locked(malloc_zone_t *zone) { // UNIMPLEMENTED(); return false; } #endif } // unnamed namespace namespace __asan { void ReplaceSystemMalloc() { static malloc_introspection_t asan_introspection; // Ok to use internal_memset, these places are not performance-critical. internal_memset(&asan_introspection, 0, sizeof(asan_introspection)); asan_introspection.enumerator = &mi_enumerator; asan_introspection.good_size = &mi_good_size; asan_introspection.check = &mi_check; asan_introspection.print = &mi_print; asan_introspection.log = &mi_log; asan_introspection.force_lock = &mi_force_lock; asan_introspection.force_unlock = &mi_force_unlock; asan_introspection.statistics = &mi_statistics; internal_memset(&asan_zone, 0, sizeof(malloc_zone_t)); // Start with a version 4 zone which is used for OS X 10.4 and 10.5. asan_zone.version = 4; asan_zone.zone_name = "asan"; asan_zone.size = &__asan_mz_size; asan_zone.malloc = &__asan_mz_malloc; asan_zone.calloc = &__asan_mz_calloc; asan_zone.valloc = &__asan_mz_valloc; asan_zone.free = &__asan_mz_free; asan_zone.realloc = &__asan_mz_realloc; asan_zone.destroy = &__asan_mz_destroy; asan_zone.batch_malloc = 0; asan_zone.batch_free = 0; asan_zone.introspect = &asan_introspection; // from AvailabilityMacros.h #if defined(MAC_OS_X_VERSION_10_6) && \ MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 // Switch to version 6 on OSX 10.6 to support memalign. asan_zone.version = 6; asan_zone.free_definite_size = 0; asan_zone.memalign = &__asan_mz_memalign; asan_introspection.zone_locked = &mi_zone_locked; #endif // Register the ASan zone. malloc_zone_register(&asan_zone); } } // namespace __asan #endif // SANITIZER_MAC <commit_msg>[ASan] Remove ifdefs for MAC_OS_X_VERSION_10_6, as ASan assumes OSX >= 10.6<commit_after>//===-- asan_malloc_mac.cc ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Mac-specific malloc interception. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_MAC #include <AvailabilityMacros.h> #include <CoreFoundation/CFBase.h> #include <dlfcn.h> #include <malloc/malloc.h> #include <sys/mman.h> #include "asan_allocator.h" #include "asan_interceptors.h" #include "asan_internal.h" #include "asan_report.h" #include "asan_stack.h" #include "asan_stats.h" #include "sanitizer_common/sanitizer_mac.h" // Similar code is used in Google Perftools, // http://code.google.com/p/google-perftools. // ---------------------- Replacement functions ---------------- {{{1 using namespace __asan; // NOLINT // TODO(glider): do we need both zones? static malloc_zone_t *system_malloc_zone = 0; static malloc_zone_t asan_zone; INTERCEPTOR(malloc_zone_t *, malloc_create_zone, vm_size_t start_size, unsigned zone_flags) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; uptr page_size = GetPageSizeCached(); uptr allocated_size = RoundUpTo(sizeof(asan_zone), page_size); malloc_zone_t *new_zone = (malloc_zone_t*)asan_memalign(page_size, allocated_size, &stack, FROM_MALLOC); internal_memcpy(new_zone, &asan_zone, sizeof(asan_zone)); new_zone->zone_name = NULL; // The name will be changed anyway. if (GetMacosVersion() >= MACOS_VERSION_LION) { // Prevent the client app from overwriting the zone contents. // Library functions that need to modify the zone will set PROT_WRITE on it. // This matches the behavior of malloc_create_zone() on OSX 10.7 and higher. mprotect(new_zone, allocated_size, PROT_READ); } return new_zone; } INTERCEPTOR(malloc_zone_t *, malloc_default_zone, void) { ENSURE_ASAN_INITED(); return &asan_zone; } INTERCEPTOR(malloc_zone_t *, malloc_default_purgeable_zone, void) { // FIXME: ASan should support purgeable allocations. // https://code.google.com/p/address-sanitizer/issues/detail?id=139 ENSURE_ASAN_INITED(); return &asan_zone; } INTERCEPTOR(void, malloc_make_purgeable, void *ptr) { // FIXME: ASan should support purgeable allocations. Ignoring them is fine // for now. ENSURE_ASAN_INITED(); } INTERCEPTOR(int, malloc_make_nonpurgeable, void *ptr) { // FIXME: ASan should support purgeable allocations. Ignoring them is fine // for now. ENSURE_ASAN_INITED(); // Must return 0 if the contents were not purged since the last call to // malloc_make_purgeable(). return 0; } INTERCEPTOR(void, malloc_set_zone_name, malloc_zone_t *zone, const char *name) { ENSURE_ASAN_INITED(); // Allocate |strlen("asan-") + 1 + internal_strlen(name)| bytes. size_t buflen = 6 + (name ? internal_strlen(name) : 0); InternalScopedString new_name(buflen); if (name && zone->introspect == asan_zone.introspect) { new_name.append("asan-%s", name); name = new_name.data(); } // Call the system malloc's implementation for both external and our zones, // since that appropriately changes VM region protections on the zone. REAL(malloc_set_zone_name)(zone, name); } INTERCEPTOR(void *, malloc, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; void *res = asan_malloc(size, &stack); return res; } INTERCEPTOR(void, free, void *ptr) { ENSURE_ASAN_INITED(); if (!ptr) return; GET_STACK_TRACE_FREE; asan_free(ptr, &stack, FROM_MALLOC); } INTERCEPTOR(void *, realloc, void *ptr, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } INTERCEPTOR(void *, calloc, size_t nmemb, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } INTERCEPTOR(void *, valloc, size_t size) { ENSURE_ASAN_INITED(); GET_STACK_TRACE_MALLOC; return asan_memalign(GetPageSizeCached(), size, &stack, FROM_MALLOC); } INTERCEPTOR(size_t, malloc_good_size, size_t size) { ENSURE_ASAN_INITED(); return asan_zone.introspect->good_size(&asan_zone, size); } INTERCEPTOR(int, posix_memalign, void **memptr, size_t alignment, size_t size) { ENSURE_ASAN_INITED(); CHECK(memptr); GET_STACK_TRACE_MALLOC; void *result = asan_memalign(alignment, size, &stack, FROM_MALLOC); if (result) { *memptr = result; return 0; } return -1; } namespace { // TODO(glider): the __asan_mz_* functions should be united with the Linux // wrappers, as they are basically copied from there. extern "C" SANITIZER_INTERFACE_ATTRIBUTE size_t __asan_mz_size(malloc_zone_t* zone, const void* ptr) { return asan_mz_size(ptr); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_malloc(malloc_zone_t *zone, uptr size) { if (UNLIKELY(!asan_inited)) { CHECK(system_malloc_zone); return malloc_zone_malloc(system_malloc_zone, size); } GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_calloc(malloc_zone_t *zone, size_t nmemb, size_t size) { if (UNLIKELY(!asan_inited)) { // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. const size_t kCallocPoolSize = 1024; static uptr calloc_memory_for_dlsym[kCallocPoolSize]; static size_t allocated; size_t size_in_words = ((nmemb * size) + kWordSize - 1) / kWordSize; void *mem = (void*)&calloc_memory_for_dlsym[allocated]; allocated += size_in_words; CHECK(allocated < kCallocPoolSize); return mem; } GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_valloc(malloc_zone_t *zone, size_t size) { if (UNLIKELY(!asan_inited)) { CHECK(system_malloc_zone); return malloc_zone_valloc(system_malloc_zone, size); } GET_STACK_TRACE_MALLOC; return asan_memalign(GetPageSizeCached(), size, &stack, FROM_MALLOC); } #define GET_ZONE_FOR_PTR(ptr) \ malloc_zone_t *zone_ptr = malloc_zone_from_ptr(ptr); \ const char *zone_name = (zone_ptr == 0) ? 0 : zone_ptr->zone_name void ALWAYS_INLINE free_common(void *context, void *ptr) { if (!ptr) return; GET_STACK_TRACE_FREE; // FIXME: need to retire this flag. if (!flags()->mac_ignore_invalid_free) { asan_free(ptr, &stack, FROM_MALLOC); } else { GET_ZONE_FOR_PTR(ptr); WarnMacFreeUnallocated((uptr)ptr, (uptr)zone_ptr, zone_name, &stack); return; } } // TODO(glider): the allocation callbacks need to be refactored. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __asan_mz_free(malloc_zone_t *zone, void *ptr) { free_common(zone, ptr); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_realloc(malloc_zone_t *zone, void *ptr, size_t size) { if (!ptr) { GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } else { if (asan_mz_size(ptr)) { GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } else { // We can't recover from reallocating an unknown address, because // this would require reading at most |size| bytes from // potentially unaccessible memory. GET_STACK_TRACE_FREE; GET_ZONE_FOR_PTR(ptr); ReportMacMzReallocUnknown((uptr)ptr, (uptr)zone_ptr, zone_name, &stack); } } } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __asan_mz_destroy(malloc_zone_t* zone) { // A no-op -- we will not be destroyed! Report("__asan_mz_destroy() called -- ignoring\n"); } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void *__asan_mz_memalign(malloc_zone_t *zone, size_t align, size_t size) { if (UNLIKELY(!asan_inited)) { CHECK(system_malloc_zone); return malloc_zone_memalign(system_malloc_zone, align, size); } GET_STACK_TRACE_MALLOC; return asan_memalign(align, size, &stack, FROM_MALLOC); } // This function is currently unused, and we build with -Werror. #if 0 void __asan_mz_free_definite_size( malloc_zone_t* zone, void *ptr, size_t size) { // TODO(glider): check that |size| is valid. UNIMPLEMENTED(); } #endif kern_return_t mi_enumerator(task_t task, void *, unsigned type_mask, vm_address_t zone_address, memory_reader_t reader, vm_range_recorder_t recorder) { // Should enumerate all the pointers we have. Seems like a lot of work. return KERN_FAILURE; } size_t mi_good_size(malloc_zone_t *zone, size_t size) { // I think it's always safe to return size, but we maybe could do better. return size; } boolean_t mi_check(malloc_zone_t *zone) { UNIMPLEMENTED(); } void mi_print(malloc_zone_t *zone, boolean_t verbose) { UNIMPLEMENTED(); } void mi_log(malloc_zone_t *zone, void *address) { // I don't think we support anything like this } void mi_force_lock(malloc_zone_t *zone) { asan_mz_force_lock(); } void mi_force_unlock(malloc_zone_t *zone) { asan_mz_force_unlock(); } void mi_statistics(malloc_zone_t *zone, malloc_statistics_t *stats) { AsanMallocStats malloc_stats; FillMallocStatistics(&malloc_stats); CHECK(sizeof(malloc_statistics_t) == sizeof(AsanMallocStats)); internal_memcpy(stats, &malloc_stats, sizeof(malloc_statistics_t)); } boolean_t mi_zone_locked(malloc_zone_t *zone) { // UNIMPLEMENTED(); return false; } } // unnamed namespace namespace __asan { void ReplaceSystemMalloc() { static malloc_introspection_t asan_introspection; // Ok to use internal_memset, these places are not performance-critical. internal_memset(&asan_introspection, 0, sizeof(asan_introspection)); asan_introspection.enumerator = &mi_enumerator; asan_introspection.good_size = &mi_good_size; asan_introspection.check = &mi_check; asan_introspection.print = &mi_print; asan_introspection.log = &mi_log; asan_introspection.force_lock = &mi_force_lock; asan_introspection.force_unlock = &mi_force_unlock; asan_introspection.statistics = &mi_statistics; asan_introspection.zone_locked = &mi_zone_locked; internal_memset(&asan_zone, 0, sizeof(malloc_zone_t)); // Use version 6 for OSX >= 10.6. asan_zone.version = 6; asan_zone.zone_name = "asan"; asan_zone.size = &__asan_mz_size; asan_zone.malloc = &__asan_mz_malloc; asan_zone.calloc = &__asan_mz_calloc; asan_zone.valloc = &__asan_mz_valloc; asan_zone.free = &__asan_mz_free; asan_zone.realloc = &__asan_mz_realloc; asan_zone.destroy = &__asan_mz_destroy; asan_zone.batch_malloc = 0; asan_zone.batch_free = 0; asan_zone.free_definite_size = 0; asan_zone.memalign = &__asan_mz_memalign; asan_zone.introspect = &asan_introspection; // Register the ASan zone. malloc_zone_register(&asan_zone); } } // namespace __asan #endif // SANITIZER_MAC <|endoftext|>
<commit_before>/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "manifest_maker.hpp" #include <string.h> #include <stdlib.h> #include <fstream> #include <string> #include <iostream> #include <vector> #include <cstdio> using namespace std; vector<string> tmp_filenames; void remove_files() { for(auto it = tmp_filenames.begin(); it != tmp_filenames.end(); ++it) { remove(it->c_str()); } } void register_atexit() { // register an atexit to clean up files, and only ever do it once static bool registered = false; if(!registered) { atexit(remove_files); registered = true; } } string tmp_filename() { char *tmpname = strdup("/tmp/tmpfileXXXXXX"); mkstemp(tmpname); tmp_filenames.push_back(tmpname); register_atexit(); return tmpname; } string tmp_file_repeating(uint size, uint x) { // create a temp file of `size` bytes filled with uint x string tmpname = tmp_filename(); ofstream f(tmpname, ios::binary); uint repeats = size / sizeof(x); for(uint i = 0; i < repeats; ++i) { f.write(reinterpret_cast <const char*>(&x), sizeof(x)); } f.close(); return tmpname; } string tmp_manifest_file(uint num_records, vector<uint> sizes) { string tmpname = tmp_filename(); ofstream f(tmpname); for(uint i = 0; i < num_records; ++i) { // stick a unique uint into each file for(uint j = 0; j < sizes.size(); ++j) { if(j != 0) { f << ","; } f << tmp_file_repeating(sizes[j], (i * sizes.size()) + j); } f << endl; } f.close(); return tmpname; } std::string tmp_manifest_file_with_invalid_filename() { string tmpname = tmp_filename(); ofstream f(tmpname); f << tmp_filename() + "jklsfjksdklfjsd" << ','; f << tmp_filename() + "jklsfjksdklfjsd" << endl; f.close(); return tmpname; } <commit_msg>write more than one line of invalid file names for good measure<commit_after>/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "manifest_maker.hpp" #include <string.h> #include <stdlib.h> #include <fstream> #include <string> #include <iostream> #include <vector> #include <cstdio> using namespace std; vector<string> tmp_filenames; void remove_files() { for(auto it = tmp_filenames.begin(); it != tmp_filenames.end(); ++it) { remove(it->c_str()); } } void register_atexit() { // register an atexit to clean up files, and only ever do it once static bool registered = false; if(!registered) { atexit(remove_files); registered = true; } } string tmp_filename() { char *tmpname = strdup("/tmp/tmpfileXXXXXX"); mkstemp(tmpname); tmp_filenames.push_back(tmpname); register_atexit(); return tmpname; } string tmp_file_repeating(uint size, uint x) { // create a temp file of `size` bytes filled with uint x string tmpname = tmp_filename(); ofstream f(tmpname, ios::binary); uint repeats = size / sizeof(x); for(uint i = 0; i < repeats; ++i) { f.write(reinterpret_cast <const char*>(&x), sizeof(x)); } f.close(); return tmpname; } string tmp_manifest_file(uint num_records, vector<uint> sizes) { string tmpname = tmp_filename(); ofstream f(tmpname); for(uint i = 0; i < num_records; ++i) { // stick a unique uint into each file for(uint j = 0; j < sizes.size(); ++j) { if(j != 0) { f << ","; } f << tmp_file_repeating(sizes[j], (i * sizes.size()) + j); } f << endl; } f.close(); return tmpname; } std::string tmp_manifest_file_with_invalid_filename() { string tmpname = tmp_filename(); ofstream f(tmpname); for(uint i = 0; i < 10; ++i) { f << tmp_filename() + ".this_file_shouldnt_exist" << ','; f << tmp_filename() + ".this_file_shouldnt_exist" << endl; } f.close(); return tmpname; } <|endoftext|>
<commit_before>#include <iostream> // GLEW #define GLEW_STATIC #include <GL/glew.h> // GLFW #include <GLFW/glfw3.h> // SOIL #include "SOIL2/SOIL2.h" // GLM Mathematics #include <glm.hpp> #include <gtc/matrix_transform.hpp> #include <gtc/type_ptr.hpp> // Other includes #include "Shader.h" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // Window dimensions const GLuint WIDTH = 800, HEIGHT = 600; // The MAIN function, from here we start the application and run the game loop int main() { // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); // Setup OpenGL options glEnable(GL_DEPTH_TEST); // Build and compile our shader program Shader ourShader("res/shaders/core.vert", "res/shaders/core.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // World space positions for our cubes glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attributes glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Texture coordinates glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glBindVertexArray(0); // Unbind VAO // Load and generate the texture GLuint texture1; GLuint texture2; // Texture 1 glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object // Set our texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load, create texture and generate mipmaps int width, height; unsigned char* image = SOIL_load_image("res/images/wall1.png", &width, &height, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture. // Texture 2 glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // Set our texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load, create texture and generate mipmaps image = SOIL_load_image("res/images/lava1.jpg", &width, &height, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.f, 0.f, 0.f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Bind Texture using texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture1"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture2"), 1); // Avtivate shader ourShader.Use(); // Create Transformations glm::mat4 view; glm::mat4 projection; view = glm::translate(view, glm::vec3(0.f, 0.f, -3.f)); projection = glm::perspective(glm::radians(45.f), (float)width / (float)height, 0.1f, 100.f); // Get their uniform location GLint modelLoc = glGetUniformLocation(ourShader.Program, "model"); GLint viewLoc = glGetUniformLocation(ourShader.Program, "view"); GLint projLoc = glGetUniformLocation(ourShader.Program, "projection"); // Pass the matrices to the shaders glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // Note: currently we set the projection matrix each frame, but since the projection matrix rarely change it's often best practice to set it outside the main loop only once. glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); // Draw container glBindVertexArray(VAO); for (GLuint i = 0; i < 10; i++) { glm::mat4 model; model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.f, 0.3f, 0.5f)); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); }<commit_msg>Look At Transformation<commit_after>#include <iostream> // GLEW #define GLEW_STATIC #include <GL/glew.h> // GLFW #include <GLFW/glfw3.h> // SOIL #include "SOIL2/SOIL2.h" // GLM Mathematics #include <glm.hpp> #include <gtc/matrix_transform.hpp> #include <gtc/type_ptr.hpp> // Other includes #include "Shader.h" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // Window dimensions const GLuint WIDTH = 800, HEIGHT = 600; // The MAIN function, from here we start the application and run the game loop int main() { // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); // Setup OpenGL options glEnable(GL_DEPTH_TEST); // Build and compile our shader program Shader ourShader("res/shaders/core.vert", "res/shaders/core.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // World space positions for our cubes glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attributes glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Texture coordinates glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glBindVertexArray(0); // Unbind VAO // Load and generate the texture GLuint texture1; GLuint texture2; // Texture 1 glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object // Set our texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load, create texture and generate mipmaps int width, height; unsigned char* image = SOIL_load_image("res/images/wall1.png", &width, &height, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture. // Texture 2 glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // Set our texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load, create texture and generate mipmaps image = SOIL_load_image("res/images/lava1.jpg", &width, &height, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.f, 0.f, 0.f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Bind Texture using texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture1"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture2"), 1); // Avtivate shader ourShader.Use(); // Camera/view transformation glm::mat4 view; GLfloat radius = 10.f; GLfloat camX = sin(glfwGetTime()) * radius; GLfloat camZ = cos(glfwGetTime()) * radius; view = glm::lookAt(glm::vec3(camX, 0.f, camZ), glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 1.f, 0.f)); // Projections glm::mat4 projection; projection = glm::perspective(glm::radians(45.f), (float)width / (float)height, 0.1f, 100.f); // Get their uniform location GLint modelLoc = glGetUniformLocation(ourShader.Program, "model"); GLint viewLoc = glGetUniformLocation(ourShader.Program, "view"); GLint projLoc = glGetUniformLocation(ourShader.Program, "projection"); // Pass the matrices to the shaders glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // Note: currently we set the projection matrix each frame, but since the projection matrix rarely change it's often best practice to set it outside the main loop only once. glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); // Draw container glBindVertexArray(VAO); for (GLuint i = 0; i < 10; i++) { glm::mat4 model; model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.f, 0.3f, 0.5f)); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); }<|endoftext|>
<commit_before>#ifndef KENGINE_RECAST_MAX_AGENTS # define KENGINE_RECAST_MAX_AGENTS 1024 #endif #include "EntityManager.hpp" #include "data/ModelComponent.hpp" #include "data/PathfindingComponent.hpp" #include "data/PhysicsComponent.hpp" #include "data/TransformComponent.hpp" #include "helpers/instanceHelper.hpp" #include "helpers/matrixHelper.hpp" #include "Common.hpp" #include "RecastAgentComponent.hpp" #include "RecastCrowdComponent.hpp" #include "RecastNavMeshComponent.hpp" #include "lengthof.hpp" namespace kengine::recast { #pragma region declarations static void removeOldAgents(); static void createNewAgents(); static void moveChangedAgents(); static void updateCrowds(float deltaTime); #pragma endregion void doPathfinding(float deltaTime) { removeOldAgents(); moveChangedAgents(); createNewAgents(); updateCrowds(deltaTime); } static void removeOldAgents() { for (auto & [e, agent, noPathfinding] : g_em->getEntities<RecastAgentComponent, no<PathfindingComponent>>()) { auto environment = g_em->getEntity(agent.crowd); auto & crowd = environment.get<RecastCrowdComponent>(); crowd.crowd->removeAgent(agent.index); e.detach<RecastAgentComponent>(); } } #pragma region createNewAgents #pragma region declarations struct EnvironmentInfo { putils::Vector3f environmentScale; glm::mat4 modelToWorld; glm::mat4 worldToModel; }; static EnvironmentInfo getEnvironmentInfo(const Entity & environment); struct ObjectInfo { putils::Rect3f objectInNavMesh; float maxSpeed; }; static ObjectInfo getObjectInfo(const EnvironmentInfo & environment, const TransformComponent & transform, const PathfindingComponent & pathfinding); static void attachCrowdComponent(Entity & e); static void attachAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd, Entity::ID crowdId); #pragma endregion static void createNewAgents() { for (auto & [e, pathfinding, transform, noRecast] : g_em->getEntities<PathfindingComponent, TransformComponent, no<RecastAgentComponent>>()) { if (pathfinding.environment == Entity::INVALID_ID) continue; auto environment = g_em->getEntity(pathfinding.environment); if (!environment.has<RecastCrowdComponent>()) attachCrowdComponent(environment); auto & crowd = environment.get<RecastCrowdComponent>(); const auto objectInfo = getObjectInfo(getEnvironmentInfo(environment), transform, pathfinding); attachAgentComponent(e, objectInfo, crowd, environment.id); } } static EnvironmentInfo getEnvironmentInfo(const Entity & environment) { EnvironmentInfo ret; const auto & model = instanceHelper::getModel<ModelComponent>(*g_em, environment); const auto & environmentTransform = environment.get<TransformComponent>(); ret.environmentScale = model.boundingBox.size * environmentTransform.boundingBox.size; ret.modelToWorld = matrixHelper::getModelMatrix(model, environmentTransform); ret.worldToModel = glm::inverse(ret.modelToWorld); return ret; } static ObjectInfo getObjectInfo(const EnvironmentInfo & environment, const TransformComponent & transform, const PathfindingComponent & pathfinding) { ObjectInfo ret; ret.objectInNavMesh = { matrixHelper::convertToReferencial(transform.boundingBox.position, environment.worldToModel), transform.boundingBox.size / environment.environmentScale }; ret.maxSpeed = (putils::Point3f{ pathfinding.maxSpeed, 0.f, 0.f } / environment.environmentScale).getLength(); return ret; } static void attachCrowdComponent(Entity & e) { auto & crowd = e.attach<RecastCrowdComponent>(); crowd.crowd.reset(dtAllocCrowd()); const auto & navMesh = instanceHelper::getModel<RecastNavMeshComponent>(*g_em, e); crowd.crowd->init(KENGINE_RECAST_MAX_AGENTS, navMesh.navMesh->getParams()->tileWidth, navMesh.navMesh.get()); } #pragma region attachAgentComponent #pragma region declarations static void fillCrowdAgentParams(dtCrowdAgentParams & params, const ObjectInfo & objectInfo); #pragma endregion static void attachAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd, Entity::ID crowdId) { dtCrowdAgentParams params; fillCrowdAgentParams(params, objectInfo); params.separationWeight = 0.f; params.updateFlags = ~0; // All flags seem to be optimizations, enable them params.obstacleAvoidanceType = 0; // Default params, might want to change? params.queryFilterType = 0; // Default query type, might want to change? params.userData = (void *)e.id; const auto idx = crowd.crowd->addAgent(objectInfo.objectInNavMesh.position, &params); kengine_assert(*g_em, idx >= 0); e += RecastAgentComponent{ idx, crowdId }; } static void fillCrowdAgentParams(dtCrowdAgentParams & params, const ObjectInfo & objectInfo) { params.radius = std::max(objectInfo.objectInNavMesh.size.x, objectInfo.objectInNavMesh.size.z); params.height = objectInfo.objectInNavMesh.size.y; params.maxAcceleration = objectInfo.maxSpeed; params.maxSpeed = params.maxAcceleration; params.collisionQueryRange = params.radius * 2.f; params.pathOptimizationRange = params.collisionQueryRange * g_adjustables.pathOptimizationRange; } #pragma endregion attachAgentComponent #pragma endregion createNewAgents static void moveChangedAgents() { for (auto & [e, pathfinding, agent] : g_em->getEntities<PathfindingComponent, RecastAgentComponent>()) { if (pathfinding.environment == agent.crowd) continue; auto oldEnvironment = g_em->getEntity(agent.crowd); auto & oldCrowd = oldEnvironment.get<RecastCrowdComponent>(); oldCrowd.crowd->removeAgent(agent.index); auto newEnvironment = g_em->getEntity(pathfinding.environment); if (!newEnvironment.has<RecastCrowdComponent>()) attachCrowdComponent(newEnvironment); auto & newCrowd = newEnvironment.get<RecastCrowdComponent>(); const auto objectInfo = getObjectInfo(getEnvironmentInfo(newEnvironment), e.get<TransformComponent>(), pathfinding); attachAgentComponent(e, objectInfo, newCrowd, newEnvironment.id); } } #pragma region updateCrowds #pragma region declarations static void readFromAgent(TransformComponent & transform, PhysicsComponent & physics, const dtCrowdAgent & agent, const EnvironmentInfo & environmentInfo); static void writeToAgent(Entity & e, const TransformComponent & transform, const PathfindingComponent & pathfinding, const EnvironmentInfo & environmentInfo, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd); #pragma endregion static void updateCrowds(float deltaTime) { for (const auto & [environment, crowd, environmentTransform] : g_em->getEntities<RecastCrowdComponent, TransformComponent>()) { g_em->runTask([&, environment] { const auto & navMesh = instanceHelper::getModel<RecastNavMeshComponent>(*g_em, environment); const auto environmentInfo = getEnvironmentInfo(environment); static dtCrowdAgent * activeAgents[KENGINE_RECAST_MAX_AGENTS]; const auto nbAgents = crowd.crowd->getActiveAgents(activeAgents, putils::lengthof(activeAgents)); // Overwrite agent with user-updated components for (int i = 0; i < nbAgents; ++i) { const auto agent = activeAgents[i]; auto e = g_em->getEntity((Entity::ID)agent->params.userData); writeToAgent(e, e.get<TransformComponent>(), e.get<PathfindingComponent>(), environmentInfo, navMesh, crowd); } crowd.crowd->update(deltaTime, nullptr); // Update user components with agent info for (int i = 0; i < nbAgents; ++i) { const auto agent = activeAgents[i]; auto e = g_em->getEntity((Entity::ID)agent->params.userData); readFromAgent(e.get<TransformComponent>(), e.get<PhysicsComponent>(), *agent, environmentInfo); } }); } g_em->completeTasks(); } static void readFromAgent(TransformComponent & transform, PhysicsComponent & physics, const dtCrowdAgent & agent, const EnvironmentInfo & environmentInfo) { physics.movement = environmentInfo.environmentScale * putils::Point3f{ agent.vel }; transform.boundingBox.position = matrixHelper::convertToReferencial(agent.npos, environmentInfo.modelToWorld); } #pragma region writeToAgent #pragma region declarations static void updateAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd); static void updateDestination(Entity & e, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd, const putils::Point3f & destinationInModel, const putils::Point3f & searchExtents); #pragma endregion static void writeToAgent(Entity & e, const TransformComponent & transform, const PathfindingComponent & pathfinding, const EnvironmentInfo & environmentInfo, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd) { const auto objectInfo = getObjectInfo(environmentInfo, transform, pathfinding); updateAgentComponent(e, objectInfo, crowd); const auto destinationInModel = matrixHelper::convertToReferencial(pathfinding.destination, environmentInfo.worldToModel); const auto searchExtents = putils::Point3f{ pathfinding.searchDistance, pathfinding.searchDistance, pathfinding.searchDistance } / environmentInfo.environmentScale; updateDestination(e, navMesh, crowd, destinationInModel, searchExtents); } static void updateAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd) { const auto & agent = e.get<RecastAgentComponent>(); dtCrowdAgentParams params = crowd.crowd->getAgent(agent.index)->params; fillCrowdAgentParams(params, objectInfo); crowd.crowd->updateAgentParameters(agent.index, &params); } static void updateDestination(Entity & e, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd, const putils::Point3f & destinationInModel, const putils::Point3f & searchExtents) { static const dtQueryFilter filter; dtPolyRef nearestPoly; float nearestPt[3]; const auto status = navMesh.navMeshQuery->findNearestPoly(destinationInModel, searchExtents, &filter, &nearestPoly, nearestPt); if (dtStatusFailed(status) || nearestPoly == 0) return; const auto & agent = e.get<RecastAgentComponent>(); if (!crowd.crowd->requestMoveTarget(agent.index, nearestPoly, nearestPt)) kengine_assert_failed(*g_em, "[Recast] Failed to request move"); } #pragma endregion writeToAgent #pragma endregion updateCrowds }<commit_msg>fix warning<commit_after>#ifndef KENGINE_RECAST_MAX_AGENTS # define KENGINE_RECAST_MAX_AGENTS 1024 #endif #include "EntityManager.hpp" #include "data/ModelComponent.hpp" #include "data/PathfindingComponent.hpp" #include "data/PhysicsComponent.hpp" #include "data/TransformComponent.hpp" #include "helpers/instanceHelper.hpp" #include "helpers/matrixHelper.hpp" #include "Common.hpp" #include "RecastAgentComponent.hpp" #include "RecastCrowdComponent.hpp" #include "RecastNavMeshComponent.hpp" #include "lengthof.hpp" namespace kengine::recast { #pragma region declarations static void removeOldAgents(); static void createNewAgents(); static void moveChangedAgents(); static void updateCrowds(float deltaTime); #pragma endregion void doPathfinding(float deltaTime) { removeOldAgents(); moveChangedAgents(); createNewAgents(); updateCrowds(deltaTime); } static void removeOldAgents() { for (auto & [e, agent, noPathfinding] : g_em->getEntities<RecastAgentComponent, no<PathfindingComponent>>()) { auto environment = g_em->getEntity(agent.crowd); auto & crowd = environment.get<RecastCrowdComponent>(); crowd.crowd->removeAgent(agent.index); e.detach<RecastAgentComponent>(); } } #pragma region createNewAgents #pragma region declarations struct EnvironmentInfo { putils::Vector3f environmentScale; glm::mat4 modelToWorld; glm::mat4 worldToModel; }; static EnvironmentInfo getEnvironmentInfo(const Entity & environment); struct ObjectInfo { putils::Rect3f objectInNavMesh; float maxSpeed; }; static ObjectInfo getObjectInfo(const EnvironmentInfo & environment, const TransformComponent & transform, const PathfindingComponent & pathfinding); static void attachCrowdComponent(Entity & e); static void attachAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd, Entity::ID crowdId); #pragma endregion static void createNewAgents() { for (auto & [e, pathfinding, transform, noRecast] : g_em->getEntities<PathfindingComponent, TransformComponent, no<RecastAgentComponent>>()) { if (pathfinding.environment == Entity::INVALID_ID) continue; auto environment = g_em->getEntity(pathfinding.environment); if (!environment.has<RecastCrowdComponent>()) attachCrowdComponent(environment); auto & crowd = environment.get<RecastCrowdComponent>(); const auto objectInfo = getObjectInfo(getEnvironmentInfo(environment), transform, pathfinding); attachAgentComponent(e, objectInfo, crowd, environment.id); } } static EnvironmentInfo getEnvironmentInfo(const Entity & environment) { EnvironmentInfo ret; const auto & model = instanceHelper::getModel<ModelComponent>(*g_em, environment); const auto & environmentTransform = environment.get<TransformComponent>(); ret.environmentScale = model.boundingBox.size * environmentTransform.boundingBox.size; ret.modelToWorld = matrixHelper::getModelMatrix(model, environmentTransform); ret.worldToModel = glm::inverse(ret.modelToWorld); return ret; } static ObjectInfo getObjectInfo(const EnvironmentInfo & environment, const TransformComponent & transform, const PathfindingComponent & pathfinding) { ObjectInfo ret; ret.objectInNavMesh = { matrixHelper::convertToReferencial(transform.boundingBox.position, environment.worldToModel), transform.boundingBox.size / environment.environmentScale }; ret.maxSpeed = (putils::Point3f{ pathfinding.maxSpeed, 0.f, 0.f } / environment.environmentScale).getLength(); return ret; } static void attachCrowdComponent(Entity & e) { auto & crowd = e.attach<RecastCrowdComponent>(); crowd.crowd.reset(dtAllocCrowd()); const auto & navMesh = instanceHelper::getModel<RecastNavMeshComponent>(*g_em, e); crowd.crowd->init(KENGINE_RECAST_MAX_AGENTS, navMesh.navMesh->getParams()->tileWidth, navMesh.navMesh.get()); } #pragma region attachAgentComponent #pragma region declarations static void fillCrowdAgentParams(dtCrowdAgentParams & params, const ObjectInfo & objectInfo); #pragma endregion static void attachAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd, Entity::ID crowdId) { dtCrowdAgentParams params; fillCrowdAgentParams(params, objectInfo); params.separationWeight = 0.f; params.updateFlags = ~0; // All flags seem to be optimizations, enable them params.obstacleAvoidanceType = 0; // Default params, might want to change? params.queryFilterType = 0; // Default query type, might want to change? params.userData = (void *)e.id; const auto idx = crowd.crowd->addAgent(objectInfo.objectInNavMesh.position, &params); kengine_assert(*g_em, idx >= 0); e += RecastAgentComponent{ idx, crowdId }; } static void fillCrowdAgentParams(dtCrowdAgentParams & params, const ObjectInfo & objectInfo) { params.radius = std::max(objectInfo.objectInNavMesh.size.x, objectInfo.objectInNavMesh.size.z); params.height = objectInfo.objectInNavMesh.size.y; params.maxAcceleration = objectInfo.maxSpeed; params.maxSpeed = params.maxAcceleration; params.collisionQueryRange = params.radius * 2.f; params.pathOptimizationRange = params.collisionQueryRange * g_adjustables.pathOptimizationRange; } #pragma endregion attachAgentComponent #pragma endregion createNewAgents static void moveChangedAgents() { for (auto & [e, pathfinding, agent] : g_em->getEntities<PathfindingComponent, RecastAgentComponent>()) { if (pathfinding.environment == agent.crowd) continue; auto oldEnvironment = g_em->getEntity(agent.crowd); auto & oldCrowd = oldEnvironment.get<RecastCrowdComponent>(); oldCrowd.crowd->removeAgent(agent.index); auto newEnvironment = g_em->getEntity(pathfinding.environment); if (!newEnvironment.has<RecastCrowdComponent>()) attachCrowdComponent(newEnvironment); auto & newCrowd = newEnvironment.get<RecastCrowdComponent>(); const auto objectInfo = getObjectInfo(getEnvironmentInfo(newEnvironment), e.get<TransformComponent>(), pathfinding); attachAgentComponent(e, objectInfo, newCrowd, newEnvironment.id); } } #pragma region updateCrowds #pragma region declarations static void readFromAgent(TransformComponent & transform, PhysicsComponent & physics, const dtCrowdAgent & agent, const EnvironmentInfo & environmentInfo); static void writeToAgent(Entity & e, const TransformComponent & transform, const PathfindingComponent & pathfinding, const EnvironmentInfo & environmentInfo, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd); #pragma endregion static void updateCrowds(float deltaTime) { for (const auto & [environment, crowd, environmentTransform] : g_em->getEntities<RecastCrowdComponent, TransformComponent>()) { g_em->runTask([&, environment] { const auto & navMesh = instanceHelper::getModel<RecastNavMeshComponent>(*g_em, environment); const auto environmentInfo = getEnvironmentInfo(environment); static dtCrowdAgent * activeAgents[KENGINE_RECAST_MAX_AGENTS]; const auto nbAgents = crowd.crowd->getActiveAgents(activeAgents, (int)putils::lengthof(activeAgents)); // Overwrite agent with user-updated components for (int i = 0; i < nbAgents; ++i) { const auto agent = activeAgents[i]; auto e = g_em->getEntity((Entity::ID)agent->params.userData); writeToAgent(e, e.get<TransformComponent>(), e.get<PathfindingComponent>(), environmentInfo, navMesh, crowd); } crowd.crowd->update(deltaTime, nullptr); // Update user components with agent info for (int i = 0; i < nbAgents; ++i) { const auto agent = activeAgents[i]; auto e = g_em->getEntity((Entity::ID)agent->params.userData); readFromAgent(e.get<TransformComponent>(), e.get<PhysicsComponent>(), *agent, environmentInfo); } }); } g_em->completeTasks(); } static void readFromAgent(TransformComponent & transform, PhysicsComponent & physics, const dtCrowdAgent & agent, const EnvironmentInfo & environmentInfo) { physics.movement = environmentInfo.environmentScale * putils::Point3f{ agent.vel }; transform.boundingBox.position = matrixHelper::convertToReferencial(agent.npos, environmentInfo.modelToWorld); } #pragma region writeToAgent #pragma region declarations static void updateAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd); static void updateDestination(Entity & e, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd, const putils::Point3f & destinationInModel, const putils::Point3f & searchExtents); #pragma endregion static void writeToAgent(Entity & e, const TransformComponent & transform, const PathfindingComponent & pathfinding, const EnvironmentInfo & environmentInfo, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd) { const auto objectInfo = getObjectInfo(environmentInfo, transform, pathfinding); updateAgentComponent(e, objectInfo, crowd); const auto destinationInModel = matrixHelper::convertToReferencial(pathfinding.destination, environmentInfo.worldToModel); const auto searchExtents = putils::Point3f{ pathfinding.searchDistance, pathfinding.searchDistance, pathfinding.searchDistance } / environmentInfo.environmentScale; updateDestination(e, navMesh, crowd, destinationInModel, searchExtents); } static void updateAgentComponent(Entity & e, const ObjectInfo & objectInfo, const RecastCrowdComponent & crowd) { const auto & agent = e.get<RecastAgentComponent>(); dtCrowdAgentParams params = crowd.crowd->getAgent(agent.index)->params; fillCrowdAgentParams(params, objectInfo); crowd.crowd->updateAgentParameters(agent.index, &params); } static void updateDestination(Entity & e, const RecastNavMeshComponent & navMesh, const RecastCrowdComponent & crowd, const putils::Point3f & destinationInModel, const putils::Point3f & searchExtents) { static const dtQueryFilter filter; dtPolyRef nearestPoly; float nearestPt[3]; const auto status = navMesh.navMeshQuery->findNearestPoly(destinationInModel, searchExtents, &filter, &nearestPoly, nearestPt); if (dtStatusFailed(status) || nearestPoly == 0) return; const auto & agent = e.get<RecastAgentComponent>(); if (!crowd.crowd->requestMoveTarget(agent.index, nearestPoly, nearestPt)) kengine_assert_failed(*g_em, "[Recast] Failed to request move"); } #pragma endregion writeToAgent #pragma endregion updateCrowds }<|endoftext|>
<commit_before> #include "Network.hpp" #include "Server.hpp" #include "CoordinateSegmentation.hpp" #include "Message.hpp" #include "ServerMessageQueue.hpp" #include "ServerMessageReceiver.hpp" #include "Statistics.hpp" #include "Options.hpp" #include "Forwarder.hpp" #include "ObjectSegmentation.hpp" #include "OSegLookupQueue.hpp" #include "ObjectConnection.hpp" #include "ForwarderServiceQueue.hpp" #include "Random.hpp" // FIXME we shouldn't have oseg specific things here, this should be delegated // to OSeg as necessary #include "CBR_OSeg.pbj.hpp" #include <sirikata/network/IOStrandImpl.hpp> namespace CBR { class ForwarderServerMessageRouter : public Router<Message*> { public: ForwarderServerMessageRouter(ForwarderServiceQueue* svc_queues, ForwarderServiceQueue::ServiceID service_id) : mForwarderServiceQueue(svc_queues), mServiceID(service_id) { } WARN_UNUSED virtual bool route(Message* msg) { return (mForwarderServiceQueue->push(mServiceID, msg) == QueueEnum::PushSucceeded); } private: ForwarderServiceQueue* mForwarderServiceQueue; ForwarderServiceQueue::ServiceID mServiceID; }; bool AlwaysPush(const UUID&, size_t cursize , size_t totsize) {return true;} // -- First, all the boring boiler plate type stuff; initialization, // -- destruction, delegation to base classes /* Constructor for Forwarder */ Forwarder::Forwarder(SpaceContext* ctx) : mContext(ctx), mOutgoingMessages(NULL), mServerMessageQueue(NULL), mServerMessageReceiver(NULL), mOSegLookups(NULL), mUniqueConnIDs(0), mServiceIDSource(0) { mOutgoingMessages = new ForwarderServiceQueue(mContext->id(), 16384, (ForwarderServiceQueue::Listener*)this); // Fill in the rest of the context mContext->mServerRouter = this; mContext->mObjectRouter = this; mContext->mServerDispatcher = this; mContext->mObjectDispatcher = this; mSSTDatagramLayer = BaseDatagramLayer<UUID>::createDatagramLayer(UUID::null(), this, this); // Messages destined for objects are subscribed to here so we can easily pick them // out and decide whether they can be delivered directly or need forwarding this->registerMessageRecipient(SERVER_PORT_OBJECT_MESSAGE_ROUTING, this); // Generate router queues for services we provide mObjectMessageRouter = createServerMessageService("object-messages"); mOSegCacheUpdateRouter = createServerMessageService("oseg-cache-update"); } //Don't need to do anything special for destructor Forwarder::~Forwarder() { delete mObjectMessageRouter; delete mOSegCacheUpdateRouter; this->unregisterMessageRecipient(SERVER_PORT_OBJECT_MESSAGE_ROUTING, this); } /* Assigning time and mObjects, which should have been constructed in Server's constructor. */ void Forwarder::initialize(ObjectSegmentation* oseg, ServerMessageQueue* smq, ServerMessageReceiver* smr, uint32 oseg_lookup_queue_size) { mOSegLookups = new OSegLookupQueue(mContext->mainStrand, oseg, &AlwaysPush, oseg_lookup_queue_size); mServerMessageQueue = smq; mServerMessageReceiver = smr; } void Forwarder::dispatchMessage(Message*msg) const { mContext->trace()->serverDatagramReceived(mContext->time, mContext->time, msg->source_server(), msg->id(), msg->serializedSize()); ServerMessageDispatcher::dispatchMessage(msg); } void Forwarder::dispatchMessage(const CBR::Protocol::Object::ObjectMessage&msg) const { ObjectMessageDispatcher::dispatchMessage(msg); } // -- Object Connection Management - Object connections are available locally, // -- and represent direct connections to endpoints. void Forwarder::addObjectConnection(const UUID& dest_obj, ObjectConnection* conn) { UniqueObjConn uoc; uoc.id = mUniqueConnIDs; uoc.conn = conn; ++mUniqueConnIDs; mObjectConnections[dest_obj] = uoc; } void Forwarder::enableObjectConnection(const UUID& dest_obj) { ObjectConnection* conn = getObjectConnection(dest_obj); if (conn == NULL) { SILOG(forwarder,warn,"Tried to enable connection for unknown object."); return; } conn->enable(); } ObjectConnection* Forwarder::removeObjectConnection(const UUID& dest_obj) { // ObjectConnection* conn = mObjectConnections[dest_obj]; UniqueObjConn uoc = mObjectConnections[dest_obj]; ObjectConnection* conn = uoc.conn; mObjectConnections.erase(dest_obj); return conn; } ObjectConnection* Forwarder::getObjectConnection(const UUID& dest_obj) { ObjectConnectionMap::iterator it = mObjectConnections.find(dest_obj); return (it == mObjectConnections.end()) ? NULL : it->second.conn; } ObjectConnection* Forwarder::getObjectConnection(const UUID& dest_obj, uint64& ider ) { ObjectConnectionMap::iterator it = mObjectConnections.find(dest_obj); if (it == mObjectConnections.end()) { ider = 0; return NULL; } ider = it->second.id; return it->second.conn; } // -- Server message handling. These methods handle server to server messages, // -- where the payload is either an already serialized ODP message, meaning its // -- information isn't available, or may simply be between two space servers so // -- that object information doesn't even exist. Router<Message*>* Forwarder::createServerMessageService(const String& name) { ServiceMap::iterator it = mServiceIDMap.find(name); assert(it == mServiceIDMap.end()); ForwarderServiceQueue::ServiceID svc_id = mServiceIDSource++; mServiceIDMap[name] = svc_id; return new ForwarderServerMessageRouter(mOutgoingMessages, svc_id); } void Forwarder::forwarderServiceMessageReady(ServerID dest_server) { mContext->mainStrand->post( std::tr1::bind(&ServerMessageQueue::messageReady, mServerMessageQueue, dest_server) ); } // -- Object Message Entry Points - entry points into the forwarder for object // -- messages. Sources include object hosts and other space servers. // --- From object hosts void Forwarder::routeObjectHostMessage(CBR::Protocol::Object::ObjectMessage* obj_msg) { // Messages destined for the space skip the object message queue and just get dispatched if (obj_msg->dest_object() == UUID::null()) { dispatchMessage(*obj_msg); delete obj_msg; return; } bool forwarded = forward(obj_msg); if (!forwarded) { TIMESTAMP(obj_msg, Trace::DROPPED_DURING_FORWARDING); delete obj_msg; } } // --- From local space server services bool Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg) { return forward(msg, NullServerID); } // --- Forwarded from other space servers void Forwarder::receiveMessage(Message* msg) { // Forwarder only subscribes as a recipient for object messages // so it can easily check whether it can deliver directly // or needs to forward them. assert(msg->dest_port() == SERVER_PORT_OBJECT_MESSAGE_ROUTING); CBR::Protocol::Object::ObjectMessage* obj_msg = new CBR::Protocol::Object::ObjectMessage(); bool parsed = parsePBJMessage(obj_msg, msg->payload()); assert(parsed); TIMESTAMP(obj_msg, Trace::HANDLE_SPACE_MESSAGE); UUID dest = obj_msg->dest_object(); // Special case: Object 0 is the space itself if (dest == UUID::null()) { dispatchMessage(*obj_msg); delete obj_msg; return; } // Otherwise, try to forward it bool forward_success = forward(obj_msg, msg->source_server()); if (!forward_success) { TIMESTAMP(obj_msg, Trace::DROPPED_DURING_FORWARDING); delete obj_msg; } delete msg; } // -- Real Routing - Given an object message, from any source, decide where it // -- needs to go and send it out in that direction. bool Forwarder::forward(CBR::Protocol::Object::ObjectMessage* msg, ServerID forwardFrom) { UUID dest_obj = msg->dest_object(); TIMESTAMP_START(tstamp, msg); TIMESTAMP_END(tstamp, Trace::FORWARDING_STARTED); // Check if we can forward locally ObjectConnection* conn = getObjectConnection(msg->dest_object()); if (conn != NULL) { TIMESTAMP_END(tstamp, Trace::FORWARDED_LOCALLY_SLOW_PATH); bool send_success = false; if (conn->enabled()) send_success = conn->send(msg); return send_success; } // If we can't forward locally, do an OSeg lookup to find out where we need // to forward the message to TIMESTAMP_END(tstamp, Trace::OSEG_LOOKUP_STARTED); bool accepted = mOSegLookups->lookup( msg, mContext->mainStrand->wrap( boost::bind(&Forwarder::routeObjectMessageToServer, this, _1, _2, _3, forwardFrom) ) ); return accepted; } bool Forwarder::routeObjectMessageToServer(CBR::Protocol::Object::ObjectMessage* obj_msg, ServerID dest_serv, OSegLookupQueue::ResolvedFrom resolved_from, ServerID forwardFrom) { Trace::MessagePath mp = (resolved_from == OSegLookupQueue::ResolvedFromCache) ? Trace::OSEG_CACHE_LOOKUP_FINISHED : Trace::OSEG_SERVER_LOOKUP_FINISHED; // Timestamp the message as having finished an OSeg Lookup TIMESTAMP(obj_msg, mp); TIMESTAMP(obj_msg, Trace::OSEG_LOOKUP_FINISHED); //send out all server updates associated with an object with this message: UUID obj_id = obj_msg->dest_object(); Message* svr_obj_msg = new Message( mContext->id(), SERVER_PORT_OBJECT_MESSAGE_ROUTING, dest_serv, SERVER_PORT_OBJECT_MESSAGE_ROUTING, obj_msg ); TIMESTAMP(obj_msg, Trace::SPACE_TO_SPACE_ENQUEUED); bool send_success = mObjectMessageRouter->route(svr_obj_msg); if (!send_success) { delete svr_obj_msg; TIMESTAMP(obj_msg, Trace::DROPPED_AT_SPACE_ENQUEUED); }else { // timestamping handled by Message routing code delete obj_msg; } // Note that this is done *after* the real message is sent since it is an optimization and // we don't want it blocking useful traffic if (forwardFrom != NullServerID) { // FIXME we used to kind of keep track of sending the same OSeg cache fix to a server multiple // times, but it really only applied for the rate of lookups/migrations. We should a) determine // if this is actually a problem and b) if it is, take a more principled approach to solving it. #ifdef CRAQ_DEBUG std::cout<<"\n\n bftm debug Sending an oseg cache update message at time: "<<mContext->time.raw()<<"\n"; std::cout<<"\t for object: "<<obj_id.toString()<<"\n"; std::cout<<"\t to server: "<<mServersToUpdate[obj_id][s]<<"\n"; std::cout<<"\t obj on: "<<dest_serv<<"\n\n"; #endif CBR::Protocol::OSeg::UpdateOSegMessage contents; contents.set_servid_sending_update(mContext->id()); contents.set_servid_obj_on(dest_serv); contents.set_m_objid(obj_id); Message* up_os = new Message( mContext->id(), SERVER_PORT_OSEG_UPDATE, forwardFrom, SERVER_PORT_OSEG_UPDATE, serializePBJMessage(contents) ); bool oseg_cache_msg_success = mOSegCacheUpdateRouter->route(up_os); // Ignore the success of this send. If it failed the remote ends cache // will just continue to be incorrect, but forwarding will cover the error } return send_success; } Message* Forwarder::serverMessageFront(ServerID dest) { Message* next_msg = mOutgoingMessages->front(dest); return next_msg; } Message* Forwarder::serverMessagePull(ServerID dest) { Message* next_msg = mOutgoingMessages->front(dest); if (next_msg == NULL) return NULL; mContext->trace()->serverDatagramQueued(mContext->time, next_msg->dest_server(), next_msg->id(), next_msg->serializedSize()); Message* pop_msg = mOutgoingMessages->pop(dest); assert(pop_msg == next_msg); return pop_msg; } void Forwarder::serverMessageReceived(Message* msg) { assert(msg != NULL); TIMESTAMP_PAYLOAD(msg, Trace::SPACE_TO_SPACE_SMR_DEQUEUED); dispatchMessage(msg); } } //end namespace <commit_msg>Handle OSeg lookups that result in our own ServerID.<commit_after> #include "Network.hpp" #include "Server.hpp" #include "CoordinateSegmentation.hpp" #include "Message.hpp" #include "ServerMessageQueue.hpp" #include "ServerMessageReceiver.hpp" #include "Statistics.hpp" #include "Options.hpp" #include "Forwarder.hpp" #include "ObjectSegmentation.hpp" #include "OSegLookupQueue.hpp" #include "ObjectConnection.hpp" #include "ForwarderServiceQueue.hpp" #include "Random.hpp" // FIXME we shouldn't have oseg specific things here, this should be delegated // to OSeg as necessary #include "CBR_OSeg.pbj.hpp" #include <sirikata/network/IOStrandImpl.hpp> namespace CBR { class ForwarderServerMessageRouter : public Router<Message*> { public: ForwarderServerMessageRouter(ForwarderServiceQueue* svc_queues, ForwarderServiceQueue::ServiceID service_id) : mForwarderServiceQueue(svc_queues), mServiceID(service_id) { } WARN_UNUSED virtual bool route(Message* msg) { return (mForwarderServiceQueue->push(mServiceID, msg) == QueueEnum::PushSucceeded); } private: ForwarderServiceQueue* mForwarderServiceQueue; ForwarderServiceQueue::ServiceID mServiceID; }; bool AlwaysPush(const UUID&, size_t cursize , size_t totsize) {return true;} // -- First, all the boring boiler plate type stuff; initialization, // -- destruction, delegation to base classes /* Constructor for Forwarder */ Forwarder::Forwarder(SpaceContext* ctx) : mContext(ctx), mOutgoingMessages(NULL), mServerMessageQueue(NULL), mServerMessageReceiver(NULL), mOSegLookups(NULL), mUniqueConnIDs(0), mServiceIDSource(0) { mOutgoingMessages = new ForwarderServiceQueue(mContext->id(), 16384, (ForwarderServiceQueue::Listener*)this); // Fill in the rest of the context mContext->mServerRouter = this; mContext->mObjectRouter = this; mContext->mServerDispatcher = this; mContext->mObjectDispatcher = this; mSSTDatagramLayer = BaseDatagramLayer<UUID>::createDatagramLayer(UUID::null(), this, this); // Messages destined for objects are subscribed to here so we can easily pick them // out and decide whether they can be delivered directly or need forwarding this->registerMessageRecipient(SERVER_PORT_OBJECT_MESSAGE_ROUTING, this); // Generate router queues for services we provide mObjectMessageRouter = createServerMessageService("object-messages"); mOSegCacheUpdateRouter = createServerMessageService("oseg-cache-update"); } //Don't need to do anything special for destructor Forwarder::~Forwarder() { delete mObjectMessageRouter; delete mOSegCacheUpdateRouter; this->unregisterMessageRecipient(SERVER_PORT_OBJECT_MESSAGE_ROUTING, this); } /* Assigning time and mObjects, which should have been constructed in Server's constructor. */ void Forwarder::initialize(ObjectSegmentation* oseg, ServerMessageQueue* smq, ServerMessageReceiver* smr, uint32 oseg_lookup_queue_size) { mOSegLookups = new OSegLookupQueue(mContext->mainStrand, oseg, &AlwaysPush, oseg_lookup_queue_size); mServerMessageQueue = smq; mServerMessageReceiver = smr; } void Forwarder::dispatchMessage(Message*msg) const { mContext->trace()->serverDatagramReceived(mContext->time, mContext->time, msg->source_server(), msg->id(), msg->serializedSize()); ServerMessageDispatcher::dispatchMessage(msg); } void Forwarder::dispatchMessage(const CBR::Protocol::Object::ObjectMessage&msg) const { ObjectMessageDispatcher::dispatchMessage(msg); } // -- Object Connection Management - Object connections are available locally, // -- and represent direct connections to endpoints. void Forwarder::addObjectConnection(const UUID& dest_obj, ObjectConnection* conn) { UniqueObjConn uoc; uoc.id = mUniqueConnIDs; uoc.conn = conn; ++mUniqueConnIDs; mObjectConnections[dest_obj] = uoc; } void Forwarder::enableObjectConnection(const UUID& dest_obj) { ObjectConnection* conn = getObjectConnection(dest_obj); if (conn == NULL) { SILOG(forwarder,warn,"Tried to enable connection for unknown object."); return; } conn->enable(); } ObjectConnection* Forwarder::removeObjectConnection(const UUID& dest_obj) { // ObjectConnection* conn = mObjectConnections[dest_obj]; UniqueObjConn uoc = mObjectConnections[dest_obj]; ObjectConnection* conn = uoc.conn; mObjectConnections.erase(dest_obj); return conn; } ObjectConnection* Forwarder::getObjectConnection(const UUID& dest_obj) { ObjectConnectionMap::iterator it = mObjectConnections.find(dest_obj); return (it == mObjectConnections.end()) ? NULL : it->second.conn; } ObjectConnection* Forwarder::getObjectConnection(const UUID& dest_obj, uint64& ider ) { ObjectConnectionMap::iterator it = mObjectConnections.find(dest_obj); if (it == mObjectConnections.end()) { ider = 0; return NULL; } ider = it->second.id; return it->second.conn; } // -- Server message handling. These methods handle server to server messages, // -- where the payload is either an already serialized ODP message, meaning its // -- information isn't available, or may simply be between two space servers so // -- that object information doesn't even exist. Router<Message*>* Forwarder::createServerMessageService(const String& name) { ServiceMap::iterator it = mServiceIDMap.find(name); assert(it == mServiceIDMap.end()); ForwarderServiceQueue::ServiceID svc_id = mServiceIDSource++; mServiceIDMap[name] = svc_id; return new ForwarderServerMessageRouter(mOutgoingMessages, svc_id); } void Forwarder::forwarderServiceMessageReady(ServerID dest_server) { mContext->mainStrand->post( std::tr1::bind(&ServerMessageQueue::messageReady, mServerMessageQueue, dest_server) ); } // -- Object Message Entry Points - entry points into the forwarder for object // -- messages. Sources include object hosts and other space servers. // --- From object hosts void Forwarder::routeObjectHostMessage(CBR::Protocol::Object::ObjectMessage* obj_msg) { // Messages destined for the space skip the object message queue and just get dispatched if (obj_msg->dest_object() == UUID::null()) { dispatchMessage(*obj_msg); delete obj_msg; return; } bool forwarded = forward(obj_msg); if (!forwarded) { TIMESTAMP(obj_msg, Trace::DROPPED_DURING_FORWARDING); delete obj_msg; } } // --- From local space server services bool Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg) { return forward(msg, NullServerID); } // --- Forwarded from other space servers void Forwarder::receiveMessage(Message* msg) { // Forwarder only subscribes as a recipient for object messages // so it can easily check whether it can deliver directly // or needs to forward them. assert(msg->dest_port() == SERVER_PORT_OBJECT_MESSAGE_ROUTING); CBR::Protocol::Object::ObjectMessage* obj_msg = new CBR::Protocol::Object::ObjectMessage(); bool parsed = parsePBJMessage(obj_msg, msg->payload()); assert(parsed); TIMESTAMP(obj_msg, Trace::HANDLE_SPACE_MESSAGE); UUID dest = obj_msg->dest_object(); // Special case: Object 0 is the space itself if (dest == UUID::null()) { dispatchMessage(*obj_msg); delete obj_msg; return; } // Otherwise, try to forward it bool forward_success = forward(obj_msg, msg->source_server()); if (!forward_success) { TIMESTAMP(obj_msg, Trace::DROPPED_DURING_FORWARDING); delete obj_msg; } delete msg; } // -- Real Routing - Given an object message, from any source, decide where it // -- needs to go and send it out in that direction. bool Forwarder::forward(CBR::Protocol::Object::ObjectMessage* msg, ServerID forwardFrom) { UUID dest_obj = msg->dest_object(); TIMESTAMP_START(tstamp, msg); TIMESTAMP_END(tstamp, Trace::FORWARDING_STARTED); // Check if we can forward locally ObjectConnection* conn = getObjectConnection(msg->dest_object()); if (conn != NULL) { TIMESTAMP_END(tstamp, Trace::FORWARDED_LOCALLY_SLOW_PATH); bool send_success = false; if (conn->enabled()) send_success = conn->send(msg); return send_success; } // If we can't forward locally, do an OSeg lookup to find out where we need // to forward the message to TIMESTAMP_END(tstamp, Trace::OSEG_LOOKUP_STARTED); bool accepted = mOSegLookups->lookup( msg, mContext->mainStrand->wrap( boost::bind(&Forwarder::routeObjectMessageToServer, this, _1, _2, _3, forwardFrom) ) ); return accepted; } bool Forwarder::routeObjectMessageToServer(CBR::Protocol::Object::ObjectMessage* obj_msg, ServerID dest_serv, OSegLookupQueue::ResolvedFrom resolved_from, ServerID forwardFrom) { Trace::MessagePath mp = (resolved_from == OSegLookupQueue::ResolvedFromCache) ? Trace::OSEG_CACHE_LOOKUP_FINISHED : Trace::OSEG_SERVER_LOOKUP_FINISHED; // Timestamp the message as having finished an OSeg Lookup TIMESTAMP(obj_msg, mp); TIMESTAMP(obj_msg, Trace::OSEG_LOOKUP_FINISHED); // It's possible we got the object after we started the query, resulting in // use pointing the message back at ourselves. In this case, just dispatch // it. if (dest_serv == mContext->id()) { dispatchMessage(*obj_msg); delete obj_msg; return true; } //send out all server updates associated with an object with this message: UUID obj_id = obj_msg->dest_object(); Message* svr_obj_msg = new Message( mContext->id(), SERVER_PORT_OBJECT_MESSAGE_ROUTING, dest_serv, SERVER_PORT_OBJECT_MESSAGE_ROUTING, obj_msg ); TIMESTAMP(obj_msg, Trace::SPACE_TO_SPACE_ENQUEUED); bool send_success = mObjectMessageRouter->route(svr_obj_msg); if (!send_success) { delete svr_obj_msg; TIMESTAMP(obj_msg, Trace::DROPPED_AT_SPACE_ENQUEUED); }else { // timestamping handled by Message routing code delete obj_msg; } // Note that this is done *after* the real message is sent since it is an optimization and // we don't want it blocking useful traffic if (forwardFrom != NullServerID) { // FIXME we used to kind of keep track of sending the same OSeg cache fix to a server multiple // times, but it really only applied for the rate of lookups/migrations. We should a) determine // if this is actually a problem and b) if it is, take a more principled approach to solving it. #ifdef CRAQ_DEBUG std::cout<<"\n\n bftm debug Sending an oseg cache update message at time: "<<mContext->time.raw()<<"\n"; std::cout<<"\t for object: "<<obj_id.toString()<<"\n"; std::cout<<"\t to server: "<<mServersToUpdate[obj_id][s]<<"\n"; std::cout<<"\t obj on: "<<dest_serv<<"\n\n"; #endif CBR::Protocol::OSeg::UpdateOSegMessage contents; contents.set_servid_sending_update(mContext->id()); contents.set_servid_obj_on(dest_serv); contents.set_m_objid(obj_id); Message* up_os = new Message( mContext->id(), SERVER_PORT_OSEG_UPDATE, forwardFrom, SERVER_PORT_OSEG_UPDATE, serializePBJMessage(contents) ); bool oseg_cache_msg_success = mOSegCacheUpdateRouter->route(up_os); // Ignore the success of this send. If it failed the remote ends cache // will just continue to be incorrect, but forwarding will cover the error } return send_success; } Message* Forwarder::serverMessageFront(ServerID dest) { Message* next_msg = mOutgoingMessages->front(dest); return next_msg; } Message* Forwarder::serverMessagePull(ServerID dest) { Message* next_msg = mOutgoingMessages->front(dest); if (next_msg == NULL) return NULL; mContext->trace()->serverDatagramQueued(mContext->time, next_msg->dest_server(), next_msg->id(), next_msg->serializedSize()); Message* pop_msg = mOutgoingMessages->pop(dest); assert(pop_msg == next_msg); return pop_msg; } void Forwarder::serverMessageReceived(Message* msg) { assert(msg != NULL); TIMESTAMP_PAYLOAD(msg, Trace::SPACE_TO_SPACE_SMR_DEQUEUED); dispatchMessage(msg); } } //end namespace <|endoftext|>
<commit_before> #include "config.h" // boost #include <boost/filesystem.hpp> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/mpihelper.hh> #include <dune/common/timer.hh> // dune-grid-multiscale #include <dune/grid/multiscale/provider/cube.hh> // dune-stuff #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/logging.hh> // dune-detailed-solvers #include <dune/detailed/solvers/stationary/linear/elliptic/model.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh> /** \brief Creates a parameter file if it does not exist. Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary keys and values. \param[in] filename (Relative) path to the file. **/ void ensureParamFile(std::string filename) { // only write param file if there is none if (!boost::filesystem::exists(filename)) { std::ofstream file; file.open(filename); file << "[grid.multiscale.provider.cube]" << std::endl; file << "level = 4" << std::endl; file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 ? in 3d file << "partitions.0 = 2" << std::endl; file << "partitions.1 = 2" << std::endl; file << "partitions.2 = 2" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl; file << "diffusion.variable = x" << std::endl; file << "diffusion.expression.0 = 1.0" << std::endl; file << "diffusion.expression.1 = 1.0" << std::endl; file << "diffusion.expression.2 = 1.0" << std::endl; file << "force.variable = x" << std::endl; file << "force.expression.0 = 1.0" << std::endl; file << "force.expression.1 = 1.0" << std::endl; file << "force.expression.2 = 1.0" << std::endl; file << "force.order = 0" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl; file << "solve.type = eigen.bicgstab.incompletelut" << std::endl; file << "solve.maxIter = 5000" << std::endl; file << "solve.precision = 1e-12" << std::endl; file << "visualize.name = solution" << std::endl; file.close(); } // only write param file if there is none } // void ensureParamFile() #ifdef POLORDER const int polOrder = POLORDER; #else const int polOrder = 1; #endif int main(int argc, char** argv) { try { // mpi Dune::MPIHelper::instance(argc, argv); // parameter const std::string id = "dune_detailed_discretizations"; const std::string filename = id + ".param"; ensureParamFile(filename); Dune::ParameterTree paramTree = Dune::Stuff::Common::Parameter::Tree::init(argc, argv, filename); // logger Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO | Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); // Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info(); std::ostream& info = std::cout; // Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); std::ostream& debug = std::cout; // timer Dune::Timer timer; // grid info << "setting up grid: " << std::endl; Dune::Stuff::Common::Logger().debug().suspend(); typedef Dune::grid::Multiscale::Provider::Cube< Dune::GridSelector::GridType > GridProviderType; Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, GridProviderType::id, id); const GridProviderType gridProvider(paramTree.sub(GridProviderType::id)); typedef GridProviderType::MsGridType MsGridType; const MsGridType& msGrid = gridProvider.msGrid(); Dune::Stuff::Common::Logger().debug().resume(); info << " took " << timer.elapsed() << " sec (has " << msGrid.globalGridPart()->grid().size(0) << " elements, " << msGrid.size() << " subdomains)" << std::endl; // model info << "setting up model... " << std::flush; timer.reset(); const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim; const unsigned int DUNE_UNUSED(dimRange) = 1; typedef GridProviderType::CoordinateType::value_type DomainFieldType; typedef DomainFieldType RangeFieldType; typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType; Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, ModelType::id, id); const ModelType model(paramTree.sub(ModelType::id)); info << "done (took " << timer.elapsed() << " sec)" << std::endl; // solver info << "initializing solver... " << std::flush; // debug.suspend(); timer.reset(); typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Multiscale::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, polOrder > SolverType; Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, SolverType::id, id); paramTree.sub(SolverType::id)["init.prefix"] = " "; SolverType solver(model, msGrid); solver.init(paramTree.sub(SolverType::id).sub("init")); // debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "solving... "; // debug.suspend(); timer.reset(); typedef SolverType::LocalVectorType LocalDofVectorType; typedef std::vector< Dune::shared_ptr< LocalDofVectorType > > MsDofVectorType; MsDofVectorType solution = solver.createVector(); paramTree.sub(SolverType::id)["solve.prefix"] = " "; solver.solve(solution, paramTree.sub(SolverType::id).sub("solve")); // debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "postprocessing..."; // debug.suspend(); timer.reset(); paramTree.sub(SolverType::id)["visualize.prefix"] = " "; paramTree.sub(SolverType::id)["visualize.filename"] = id + "_solution"; solver.visualize(solution, paramTree.sub(SolverType::id).sub("visualize")); // debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; // if we came that far we can as well be happy about it return 0; } catch(Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch( ... ) { std::cerr << "Unknown exception thrown!" << std::endl; } // try } // main <commit_msg>[examples...multiscale...] added visualization<commit_after> #include "config.h" // boost #include <boost/filesystem.hpp> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/mpihelper.hh> #include <dune/common/timer.hh> // dune-grid-multiscale #include <dune/grid/multiscale/provider/cube.hh> // dune-stuff #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/logging.hh> // dune-detailed-solvers #include <dune/detailed/solvers/stationary/linear/elliptic/model.hh> #include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh> /** \brief Creates a parameter file if it does not exist. Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary keys and values. \param[in] filename (Relative) path to the file. **/ void ensureParamFile(std::string filename) { // only write param file if there is none if (!boost::filesystem::exists(filename)) { std::ofstream file; file.open(filename); file << "[grid.multiscale.provider.cube]" << std::endl; file << "level = 4" << std::endl; file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 ? in 3d file << "partitions.0 = 2" << std::endl; file << "partitions.1 = 2" << std::endl; file << "partitions.2 = 2" << std::endl; file << "filename = msGrid_visualization" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl; file << "diffusion.variable = x" << std::endl; file << "diffusion.expression.0 = 1.0" << std::endl; file << "diffusion.expression.1 = 1.0" << std::endl; file << "diffusion.expression.2 = 1.0" << std::endl; file << "force.variable = x" << std::endl; file << "force.expression.0 = 1.0" << std::endl; file << "force.expression.1 = 1.0" << std::endl; file << "force.expression.2 = 1.0" << std::endl; file << "force.order = 0" << std::endl; file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl; file << "solve.type = eigen.bicgstab.incompletelut" << std::endl; file << "solve.maxIter = 5000" << std::endl; file << "solve.precision = 1e-12" << std::endl; file << "visualize.name = solution" << std::endl; file.close(); } // only write param file if there is none } // void ensureParamFile() #ifdef POLORDER const int polOrder = POLORDER; #else const int polOrder = 1; #endif int main(int argc, char** argv) { try { // mpi Dune::MPIHelper::instance(argc, argv); // parameter const std::string id = "dune_detailed_discretizations"; const std::string filename = id + ".param"; ensureParamFile(filename); Dune::ParameterTree paramTree = Dune::Stuff::Common::Parameter::Tree::init(argc, argv, filename); // logger Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO | Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); // Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info(); std::ostream& info = std::cout; Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); // timer Dune::Timer timer; // grid info << "setting up grid: " << std::endl; debug.suspend(); typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType; Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, GridProviderType::id, id); const GridProviderType gridProvider(paramTree.sub(GridProviderType::id)); typedef GridProviderType::MsGridType MsGridType; const MsGridType& msGrid = gridProvider.msGrid(); info << " took " << timer.elapsed() << " sec (has " << msGrid.globalGridPart()->grid().size(0) << " elements, " << msGrid.size() << " subdomains)" << std::endl; debug.resume(); info << "visualizing grid... " << std::flush; debug.suspend(); timer.reset(); msGrid.visualize(); info << " done (took " << timer.elapsed() << " sek)" << std::endl; debug.resume(); // model info << "setting up model... " << std::flush; timer.reset(); const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim; const unsigned int DUNE_UNUSED(dimRange) = 1; typedef GridProviderType::CoordinateType::value_type DomainFieldType; typedef DomainFieldType RangeFieldType; typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType; Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, ModelType::id, id); const ModelType model(paramTree.sub(ModelType::id)); info << "done (took " << timer.elapsed() << " sec)" << std::endl; // solver info << "initializing solver... " << std::flush; // debug.suspend(); timer.reset(); typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Multiscale::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, polOrder > SolverType; Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, SolverType::id, id); paramTree.sub(SolverType::id)["init.prefix"] = " "; SolverType solver(model, msGrid); solver.init(paramTree.sub(SolverType::id).sub("init")); // debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "solving... "; // debug.suspend(); timer.reset(); typedef SolverType::LocalVectorType LocalDofVectorType; typedef std::vector< Dune::shared_ptr< LocalDofVectorType > > MsDofVectorType; MsDofVectorType solution = solver.createVector(); paramTree.sub(SolverType::id)["solve.prefix"] = " "; solver.solve(solution, paramTree.sub(SolverType::id).sub("solve")); // debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; info << "postprocessing..."; // debug.suspend(); timer.reset(); paramTree.sub(SolverType::id)["visualize.prefix"] = " "; paramTree.sub(SolverType::id)["visualize.filename"] = id + "_solution"; solver.visualize(solution, paramTree.sub(SolverType::id).sub("visualize")); // debug.resume(); info << "done (took " << timer.elapsed() << " sec)" << std::endl; // if we came that far we can as well be happy about it return 0; } catch(Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch( ... ) { std::cerr << "Unknown exception thrown!" << std::endl; } // try } // main <|endoftext|>
<commit_before>#include "boost_defs.hpp" #include "hid_manager.hpp" #include "hid_observer.hpp" #include <boost/optional/optional_io.hpp> namespace { class dump_hid_value final { public: dump_hid_value(const dump_hid_value&) = delete; dump_hid_value(void) { hid_manager_.device_detected.connect([this](auto&& human_interface_device) { human_interface_device.values_arrived.connect([this](auto&& human_interface_device, auto&& event_queue) { values_arrived(human_interface_device, event_queue); }); // Observe auto hid_observer = std::make_shared<krbn::hid_observer>(human_interface_device); hid_observer->device_observed.connect([&](auto&& human_interface_device) { krbn::logger::get_logger().info("{0} is observed.", human_interface_device.get_name_for_log()); }); hid_observer->observe(); hid_observers_[human_interface_device.get_registry_entry_id()] = hid_observer; }); hid_manager_.device_removed.connect([this](auto&& human_interface_device) { hid_observers_.erase(human_interface_device.get_registry_entry_id()); }); hid_manager_.start({ std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_keyboard), std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_mouse), std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_pointer), }); } ~dump_hid_value(void) { hid_manager_.stop(); } private: void values_arrived(krbn::human_interface_device& device, krbn::event_queue& event_queue) { for (const auto& queued_event : event_queue.get_events()) { std::cout << queued_event.get_event_time_stamp().get_time_stamp() << " "; switch (queued_event.get_event().get_type()) { case krbn::event_queue::queued_event::event::type::none: std::cout << "none" << std::endl; break; case krbn::event_queue::queued_event::event::type::key_code: if (auto key_code = queued_event.get_event().get_key_code()) { std::cout << "Key: " << std::dec << static_cast<uint32_t>(*key_code) << " " << queued_event.get_event_type() << std::endl; } break; case krbn::event_queue::queued_event::event::type::consumer_key_code: if (auto consumer_key_code = queued_event.get_event().get_consumer_key_code()) { std::cout << "ConsumerKey: " << std::dec << static_cast<uint32_t>(*consumer_key_code) << " " << queued_event.get_event_type() << std::endl; } break; case krbn::event_queue::queued_event::event::type::pointing_button: if (auto pointing_button = queued_event.get_event().get_pointing_button()) { std::cout << "Button: " << std::dec << static_cast<uint32_t>(*pointing_button) << " " << queued_event.get_event_type() << std::endl; } break; case krbn::event_queue::queued_event::event::type::pointing_motion: if (auto pointing_motion = queued_event.get_event().get_pointing_motion()) { std::cout << "pointing_motion: " << pointing_motion->to_json() << std::endl; } break; case krbn::event_queue::queued_event::event::type::shell_command: std::cout << "shell_command" << std::endl; break; case krbn::event_queue::queued_event::event::type::select_input_source: std::cout << "select_input_source" << std::endl; break; case krbn::event_queue::queued_event::event::type::set_variable: std::cout << "set_variable" << std::endl; break; case krbn::event_queue::queued_event::event::type::mouse_key: std::cout << "mouse_key" << std::endl; break; case krbn::event_queue::queued_event::event::type::stop_keyboard_repeat: std::cout << "stop_keyboard_repeat" << std::endl; break; case krbn::event_queue::queued_event::event::type::device_keys_and_pointing_buttons_are_released: std::cout << "device_keys_and_pointing_buttons_are_released for " << device.get_name_for_log() << " (" << device.get_device_id() << ")" << std::endl; break; case krbn::event_queue::queued_event::event::type::device_ungrabbed: std::cout << "device_ungrabbed for " << device.get_name_for_log() << " (" << device.get_device_id() << ")" << std::endl; break; case krbn::event_queue::queued_event::event::type::caps_lock_state_changed: if (auto integer_value = queued_event.get_event().get_integer_value()) { std::cout << "caps_lock_state_changed " << *integer_value << std::endl; } break; case krbn::event_queue::queued_event::event::type::pointing_device_event_from_event_tap: std::cout << "pointing_device_event_from_event_tap from " << device.get_name_for_log() << " (" << device.get_device_id() << ")" << std::endl; break; case krbn::event_queue::queued_event::event::type::frontmost_application_changed: if (auto frontmost_application = queued_event.get_event().get_frontmost_application()) { std::cout << "frontmost_application_changed " << frontmost_application->get_bundle_identifier() << " " << frontmost_application->get_file_path() << std::endl; } break; case krbn::event_queue::queued_event::event::type::input_source_changed: if (auto input_source_identifiers = queued_event.get_event().get_input_source_identifiers()) { std::cout << "input_source_changed " << input_source_identifiers << std::endl; } break; case krbn::event_queue::queued_event::event::type::keyboard_type_changed: if (auto keyboard_type = queued_event.get_event().get_keyboard_type()) { std::cout << "keyboard_type_changed " << keyboard_type << std::endl; } break; default: std::cout << std::endl; } } event_queue.clear_events(); } krbn::hid_manager hid_manager_; std::unordered_map<krbn::registry_entry_id, std::shared_ptr<krbn::hid_observer>> hid_observers_; }; } // namespace int main(int argc, const char* argv[]) { krbn::thread_utility::register_main_thread(); dump_hid_value d; CFRunLoopRun(); return 0; } <commit_msg>clea hid_observers_ before hid_manager_.stop()<commit_after>#include "boost_defs.hpp" #include "hid_manager.hpp" #include "hid_observer.hpp" #include <boost/optional/optional_io.hpp> namespace { class dump_hid_value final { public: dump_hid_value(const dump_hid_value&) = delete; dump_hid_value(void) { hid_manager_.device_detected.connect([this](auto&& human_interface_device) { human_interface_device.values_arrived.connect([this](auto&& human_interface_device, auto&& event_queue) { values_arrived(human_interface_device, event_queue); }); // Observe auto hid_observer = std::make_shared<krbn::hid_observer>(human_interface_device); hid_observer->device_observed.connect([&](auto&& human_interface_device) { krbn::logger::get_logger().info("{0} is observed.", human_interface_device.get_name_for_log()); }); hid_observer->observe(); hid_observers_[human_interface_device.get_registry_entry_id()] = hid_observer; }); hid_manager_.device_removed.connect([this](auto&& human_interface_device) { hid_observers_.erase(human_interface_device.get_registry_entry_id()); }); hid_manager_.start({ std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_keyboard), std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_mouse), std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_pointer), }); } ~dump_hid_value(void) { hid_observers_.clear(); hid_manager_.stop(); } private: void values_arrived(krbn::human_interface_device& device, krbn::event_queue& event_queue) { for (const auto& queued_event : event_queue.get_events()) { std::cout << queued_event.get_event_time_stamp().get_time_stamp() << " "; switch (queued_event.get_event().get_type()) { case krbn::event_queue::queued_event::event::type::none: std::cout << "none" << std::endl; break; case krbn::event_queue::queued_event::event::type::key_code: if (auto key_code = queued_event.get_event().get_key_code()) { std::cout << "Key: " << std::dec << static_cast<uint32_t>(*key_code) << " " << queued_event.get_event_type() << std::endl; } break; case krbn::event_queue::queued_event::event::type::consumer_key_code: if (auto consumer_key_code = queued_event.get_event().get_consumer_key_code()) { std::cout << "ConsumerKey: " << std::dec << static_cast<uint32_t>(*consumer_key_code) << " " << queued_event.get_event_type() << std::endl; } break; case krbn::event_queue::queued_event::event::type::pointing_button: if (auto pointing_button = queued_event.get_event().get_pointing_button()) { std::cout << "Button: " << std::dec << static_cast<uint32_t>(*pointing_button) << " " << queued_event.get_event_type() << std::endl; } break; case krbn::event_queue::queued_event::event::type::pointing_motion: if (auto pointing_motion = queued_event.get_event().get_pointing_motion()) { std::cout << "pointing_motion: " << pointing_motion->to_json() << std::endl; } break; case krbn::event_queue::queued_event::event::type::shell_command: std::cout << "shell_command" << std::endl; break; case krbn::event_queue::queued_event::event::type::select_input_source: std::cout << "select_input_source" << std::endl; break; case krbn::event_queue::queued_event::event::type::set_variable: std::cout << "set_variable" << std::endl; break; case krbn::event_queue::queued_event::event::type::mouse_key: std::cout << "mouse_key" << std::endl; break; case krbn::event_queue::queued_event::event::type::stop_keyboard_repeat: std::cout << "stop_keyboard_repeat" << std::endl; break; case krbn::event_queue::queued_event::event::type::device_keys_and_pointing_buttons_are_released: std::cout << "device_keys_and_pointing_buttons_are_released for " << device.get_name_for_log() << " (" << device.get_device_id() << ")" << std::endl; break; case krbn::event_queue::queued_event::event::type::device_ungrabbed: std::cout << "device_ungrabbed for " << device.get_name_for_log() << " (" << device.get_device_id() << ")" << std::endl; break; case krbn::event_queue::queued_event::event::type::caps_lock_state_changed: if (auto integer_value = queued_event.get_event().get_integer_value()) { std::cout << "caps_lock_state_changed " << *integer_value << std::endl; } break; case krbn::event_queue::queued_event::event::type::pointing_device_event_from_event_tap: std::cout << "pointing_device_event_from_event_tap from " << device.get_name_for_log() << " (" << device.get_device_id() << ")" << std::endl; break; case krbn::event_queue::queued_event::event::type::frontmost_application_changed: if (auto frontmost_application = queued_event.get_event().get_frontmost_application()) { std::cout << "frontmost_application_changed " << frontmost_application->get_bundle_identifier() << " " << frontmost_application->get_file_path() << std::endl; } break; case krbn::event_queue::queued_event::event::type::input_source_changed: if (auto input_source_identifiers = queued_event.get_event().get_input_source_identifiers()) { std::cout << "input_source_changed " << input_source_identifiers << std::endl; } break; case krbn::event_queue::queued_event::event::type::keyboard_type_changed: if (auto keyboard_type = queued_event.get_event().get_keyboard_type()) { std::cout << "keyboard_type_changed " << keyboard_type << std::endl; } break; default: std::cout << std::endl; } } event_queue.clear_events(); } krbn::hid_manager hid_manager_; std::unordered_map<krbn::registry_entry_id, std::shared_ptr<krbn::hid_observer>> hid_observers_; }; } // namespace int main(int argc, const char* argv[]) { krbn::thread_utility::register_main_thread(); dump_hid_value d; CFRunLoopRun(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <boost/range/iterator_range.hpp> #include "bytes.hh" #include <seastar/core/unaligned.hh> #include "hashing.hh" #include <seastar/core/simple-stream.hh> /** * Utility for writing data into a buffer when its final size is not known up front. * * Internally the data is written into a chain of chunks allocated on-demand. * No resizing of previously written data happens. * */ class bytes_ostream { public: using size_type = bytes::size_type; using value_type = bytes::value_type; static constexpr size_type max_chunk_size() { return 128 * 1024; } private: static_assert(sizeof(value_type) == 1, "value_type is assumed to be one byte long"); struct chunk { // FIXME: group fragment pointers to reduce pointer chasing when packetizing std::unique_ptr<chunk> next; ~chunk() { auto p = std::move(next); while (p) { // Avoid recursion when freeing chunks auto p_next = std::move(p->next); p = std::move(p_next); } } size_type offset; // Also means "size" after chunk is closed size_type size; value_type data[0]; void operator delete(void* ptr) { free(ptr); } }; static constexpr size_type default_chunk_size{512}; private: std::unique_ptr<chunk> _begin; chunk* _current; size_type _size; size_type _initial_chunk_size = default_chunk_size; public: class fragment_iterator : public std::iterator<std::input_iterator_tag, bytes_view> { chunk* _current = nullptr; public: fragment_iterator() = default; fragment_iterator(chunk* current) : _current(current) {} fragment_iterator(const fragment_iterator&) = default; fragment_iterator& operator=(const fragment_iterator&) = default; bytes_view operator*() const { return { _current->data, _current->offset }; } bytes_view operator->() const { return *(*this); } fragment_iterator& operator++() { _current = _current->next.get(); return *this; } fragment_iterator operator++(int) { fragment_iterator tmp(*this); ++(*this); return tmp; } bool operator==(const fragment_iterator& other) const { return _current == other._current; } bool operator!=(const fragment_iterator& other) const { return _current != other._current; } }; private: inline size_type current_space_left() const { if (!_current) { return 0; } return _current->size - _current->offset; } // Figure out next chunk size. // - must be enough for data_size // - must be at least _initial_chunk_size // - try to double each time to prevent too many allocations // - do not exceed max_chunk_size size_type next_alloc_size(size_t data_size) const { auto next_size = _current ? _current->size * 2 : _initial_chunk_size; next_size = std::min(next_size, max_chunk_size()); // FIXME: check for overflow? return std::max<size_type>(next_size, data_size + sizeof(chunk)); } // Makes room for a contiguous region of given size. // The region is accounted for as already written. // size must not be zero. [[gnu::always_inline]] value_type* alloc(size_type size) { if (__builtin_expect(size <= current_space_left(), true)) { auto ret = _current->data + _current->offset; _current->offset += size; _size += size; return ret; } else { return alloc_new(size); } } [[gnu::noinline]] value_type* alloc_new(size_type size) { auto alloc_size = next_alloc_size(size); auto space = malloc(alloc_size); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = size; new_chunk->size = alloc_size - sizeof(chunk); if (_current) { _current->next = std::move(new_chunk); _current = _current->next.get(); } else { _begin = std::move(new_chunk); _current = _begin.get(); } _size += size; return _current->data; } public: explicit bytes_ostream(size_t initial_chunk_size) noexcept : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(initial_chunk_size) { } bytes_ostream() noexcept : bytes_ostream(default_chunk_size) {} bytes_ostream(bytes_ostream&& o) noexcept : _begin(std::move(o._begin)) , _current(o._current) , _size(o._size) , _initial_chunk_size(o._initial_chunk_size) { o._current = nullptr; o._size = 0; } bytes_ostream(const bytes_ostream& o) : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(o._initial_chunk_size) { append(o); } bytes_ostream& operator=(const bytes_ostream& o) { if (this != &o) { auto x = bytes_ostream(o); *this = std::move(x); } return *this; } bytes_ostream& operator=(bytes_ostream&& o) noexcept { if (this != &o) { this->~bytes_ostream(); new (this) bytes_ostream(std::move(o)); } return *this; } template <typename T> struct place_holder { value_type* ptr; // makes the place_holder looks like a stream seastar::simple_output_stream get_stream() { return seastar::simple_output_stream(reinterpret_cast<char*>(ptr), sizeof(T)); } }; // Returns a place holder for a value to be written later. template <typename T> inline std::enable_if_t<std::is_fundamental<T>::value, place_holder<T>> write_place_holder() { return place_holder<T>{alloc(sizeof(T))}; } [[gnu::always_inline]] value_type* write_place_holder(size_type size) { return alloc(size); } // Writes given sequence of bytes [[gnu::always_inline]] inline void write(bytes_view v) { if (v.empty()) { return; } auto this_size = std::min(v.size(), size_t(current_space_left())); if (__builtin_expect(this_size, true)) { memcpy(_current->data + _current->offset, v.begin(), this_size); _current->offset += this_size; _size += this_size; v.remove_prefix(this_size); } while (!v.empty()) { auto this_size = std::min(v.size(), size_t(max_chunk_size())); std::copy_n(v.begin(), this_size, alloc_new(this_size)); v.remove_prefix(this_size); } } [[gnu::always_inline]] void write(const char* ptr, size_t size) { write(bytes_view(reinterpret_cast<const signed char*>(ptr), size)); } bool is_linearized() const { return !_begin || !_begin->next; } // Call only when is_linearized() bytes_view view() const { assert(is_linearized()); if (!_current) { return bytes_view(); } return bytes_view(_current->data, _size); } // Makes the underlying storage contiguous and returns a view to it. // Invalidates all previously created placeholders. bytes_view linearize() { if (is_linearized()) { return view(); } auto space = malloc(_size + sizeof(chunk)); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = _size; new_chunk->size = _size; auto dst = new_chunk->data; auto r = _begin.get(); while (r) { auto next = r->next.get(); dst = std::copy_n(r->data, r->offset, dst); r = next; } _current = new_chunk.get(); _begin = std::move(new_chunk); return bytes_view(_current->data, _size); } // Returns the amount of bytes written so far size_type size() const { return _size; } bool empty() const { return _size == 0; } void reserve(size_t size) { // FIXME: implement } void append(const bytes_ostream& o) { for (auto&& bv : o.fragments()) { write(bv); } } // Removes n bytes from the end of the bytes_ostream. // Beware of O(n) algorithm. void remove_suffix(size_t n) { _size -= n; auto left = _size; auto current = _begin.get(); while (current) { if (current->offset >= left) { current->offset = left; _current = current; current->next.reset(); return; } left -= current->offset; current = current->next.get(); } } // begin() and end() form an input range to bytes_view representing fragments. // Any modification of this instance invalidates iterators. fragment_iterator begin() const { return { _begin.get() }; } fragment_iterator end() const { return { nullptr }; } boost::iterator_range<fragment_iterator> fragments() const { return { begin(), end() }; } struct position { chunk* _chunk; size_type _offset; }; position pos() const { return { _current, _current ? _current->offset : 0 }; } // Returns the amount of bytes written since given position. // "pos" must be valid. size_type written_since(position pos) { chunk* c = pos._chunk; if (!c) { return _size; } size_type total = c->offset - pos._offset; c = c->next.get(); while (c) { total += c->offset; c = c->next.get(); } return total; } // Rollbacks all data written after "pos". // Invalidates all placeholders and positions created after "pos". void retract(position pos) { if (!pos._chunk) { *this = {}; return; } _size -= written_since(pos); _current = pos._chunk; _current->next = nullptr; _current->offset = pos._offset; } void reduce_chunk_count() { // FIXME: This is a simplified version. It linearizes the whole buffer // if its size is below max_chunk_size. We probably could also gain // some read performance by doing "real" reduction, i.e. merging // all chunks until all but the last one is max_chunk_size. if (size() < max_chunk_size()) { linearize(); } } bool operator==(const bytes_ostream& other) const { auto as = fragments().begin(); auto as_end = fragments().end(); auto bs = other.fragments().begin(); auto bs_end = other.fragments().end(); auto a = *as++; auto b = *bs++; while (!a.empty() || !b.empty()) { auto now = std::min(a.size(), b.size()); if (!std::equal(a.begin(), a.begin() + now, b.begin(), b.begin() + now)) { return false; } a.remove_prefix(now); if (a.empty() && as != as_end) { a = *as++; } b.remove_prefix(now); if (b.empty() && bs != bs_end) { b = *bs++; } } return true; } bool operator!=(const bytes_ostream& other) const { return !(*this == other); } // Makes this instance empty. // // The first buffer is not deallocated, so callers may rely on the // fact that if they write less than the initial chunk size between // the clear() calls then writes will not involve any memory allocations, // except for the first write made on this instance. void clear() { if (_begin) { _begin->offset = 0; _size = 0; _current = _begin.get(); _begin->next.reset(); } } }; <commit_msg>bytes_ostream: add output_iterator<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <boost/range/iterator_range.hpp> #include "bytes.hh" #include <seastar/core/unaligned.hh> #include "hashing.hh" #include <seastar/core/simple-stream.hh> /** * Utility for writing data into a buffer when its final size is not known up front. * * Internally the data is written into a chain of chunks allocated on-demand. * No resizing of previously written data happens. * */ class bytes_ostream { public: using size_type = bytes::size_type; using value_type = bytes::value_type; static constexpr size_type max_chunk_size() { return 128 * 1024; } private: static_assert(sizeof(value_type) == 1, "value_type is assumed to be one byte long"); struct chunk { // FIXME: group fragment pointers to reduce pointer chasing when packetizing std::unique_ptr<chunk> next; ~chunk() { auto p = std::move(next); while (p) { // Avoid recursion when freeing chunks auto p_next = std::move(p->next); p = std::move(p_next); } } size_type offset; // Also means "size" after chunk is closed size_type size; value_type data[0]; void operator delete(void* ptr) { free(ptr); } }; static constexpr size_type default_chunk_size{512}; private: std::unique_ptr<chunk> _begin; chunk* _current; size_type _size; size_type _initial_chunk_size = default_chunk_size; public: class fragment_iterator : public std::iterator<std::input_iterator_tag, bytes_view> { chunk* _current = nullptr; public: fragment_iterator() = default; fragment_iterator(chunk* current) : _current(current) {} fragment_iterator(const fragment_iterator&) = default; fragment_iterator& operator=(const fragment_iterator&) = default; bytes_view operator*() const { return { _current->data, _current->offset }; } bytes_view operator->() const { return *(*this); } fragment_iterator& operator++() { _current = _current->next.get(); return *this; } fragment_iterator operator++(int) { fragment_iterator tmp(*this); ++(*this); return tmp; } bool operator==(const fragment_iterator& other) const { return _current == other._current; } bool operator!=(const fragment_iterator& other) const { return _current != other._current; } }; class output_iterator { public: using iterator_category = std::output_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = bytes_ostream::value_type; using pointer = bytes_ostream::value_type*; using reference = bytes_ostream::value_type&; friend class bytes_ostream; private: bytes_ostream* _ostream = nullptr; private: explicit output_iterator(bytes_ostream& os) : _ostream(&os) { } public: reference operator*() const { return *_ostream->write_place_holder(1); } output_iterator& operator++() { return *this; } output_iterator operator++(int) { return *this; } }; private: inline size_type current_space_left() const { if (!_current) { return 0; } return _current->size - _current->offset; } // Figure out next chunk size. // - must be enough for data_size // - must be at least _initial_chunk_size // - try to double each time to prevent too many allocations // - do not exceed max_chunk_size size_type next_alloc_size(size_t data_size) const { auto next_size = _current ? _current->size * 2 : _initial_chunk_size; next_size = std::min(next_size, max_chunk_size()); // FIXME: check for overflow? return std::max<size_type>(next_size, data_size + sizeof(chunk)); } // Makes room for a contiguous region of given size. // The region is accounted for as already written. // size must not be zero. [[gnu::always_inline]] value_type* alloc(size_type size) { if (__builtin_expect(size <= current_space_left(), true)) { auto ret = _current->data + _current->offset; _current->offset += size; _size += size; return ret; } else { return alloc_new(size); } } [[gnu::noinline]] value_type* alloc_new(size_type size) { auto alloc_size = next_alloc_size(size); auto space = malloc(alloc_size); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = size; new_chunk->size = alloc_size - sizeof(chunk); if (_current) { _current->next = std::move(new_chunk); _current = _current->next.get(); } else { _begin = std::move(new_chunk); _current = _begin.get(); } _size += size; return _current->data; } public: explicit bytes_ostream(size_t initial_chunk_size) noexcept : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(initial_chunk_size) { } bytes_ostream() noexcept : bytes_ostream(default_chunk_size) {} bytes_ostream(bytes_ostream&& o) noexcept : _begin(std::move(o._begin)) , _current(o._current) , _size(o._size) , _initial_chunk_size(o._initial_chunk_size) { o._current = nullptr; o._size = 0; } bytes_ostream(const bytes_ostream& o) : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(o._initial_chunk_size) { append(o); } bytes_ostream& operator=(const bytes_ostream& o) { if (this != &o) { auto x = bytes_ostream(o); *this = std::move(x); } return *this; } bytes_ostream& operator=(bytes_ostream&& o) noexcept { if (this != &o) { this->~bytes_ostream(); new (this) bytes_ostream(std::move(o)); } return *this; } template <typename T> struct place_holder { value_type* ptr; // makes the place_holder looks like a stream seastar::simple_output_stream get_stream() { return seastar::simple_output_stream(reinterpret_cast<char*>(ptr), sizeof(T)); } }; // Returns a place holder for a value to be written later. template <typename T> inline std::enable_if_t<std::is_fundamental<T>::value, place_holder<T>> write_place_holder() { return place_holder<T>{alloc(sizeof(T))}; } [[gnu::always_inline]] value_type* write_place_holder(size_type size) { return alloc(size); } // Writes given sequence of bytes [[gnu::always_inline]] inline void write(bytes_view v) { if (v.empty()) { return; } auto this_size = std::min(v.size(), size_t(current_space_left())); if (__builtin_expect(this_size, true)) { memcpy(_current->data + _current->offset, v.begin(), this_size); _current->offset += this_size; _size += this_size; v.remove_prefix(this_size); } while (!v.empty()) { auto this_size = std::min(v.size(), size_t(max_chunk_size())); std::copy_n(v.begin(), this_size, alloc_new(this_size)); v.remove_prefix(this_size); } } [[gnu::always_inline]] void write(const char* ptr, size_t size) { write(bytes_view(reinterpret_cast<const signed char*>(ptr), size)); } bool is_linearized() const { return !_begin || !_begin->next; } // Call only when is_linearized() bytes_view view() const { assert(is_linearized()); if (!_current) { return bytes_view(); } return bytes_view(_current->data, _size); } // Makes the underlying storage contiguous and returns a view to it. // Invalidates all previously created placeholders. bytes_view linearize() { if (is_linearized()) { return view(); } auto space = malloc(_size + sizeof(chunk)); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = _size; new_chunk->size = _size; auto dst = new_chunk->data; auto r = _begin.get(); while (r) { auto next = r->next.get(); dst = std::copy_n(r->data, r->offset, dst); r = next; } _current = new_chunk.get(); _begin = std::move(new_chunk); return bytes_view(_current->data, _size); } // Returns the amount of bytes written so far size_type size() const { return _size; } bool empty() const { return _size == 0; } void reserve(size_t size) { // FIXME: implement } void append(const bytes_ostream& o) { for (auto&& bv : o.fragments()) { write(bv); } } // Removes n bytes from the end of the bytes_ostream. // Beware of O(n) algorithm. void remove_suffix(size_t n) { _size -= n; auto left = _size; auto current = _begin.get(); while (current) { if (current->offset >= left) { current->offset = left; _current = current; current->next.reset(); return; } left -= current->offset; current = current->next.get(); } } // begin() and end() form an input range to bytes_view representing fragments. // Any modification of this instance invalidates iterators. fragment_iterator begin() const { return { _begin.get() }; } fragment_iterator end() const { return { nullptr }; } output_iterator write_begin() { return output_iterator(*this); } boost::iterator_range<fragment_iterator> fragments() const { return { begin(), end() }; } struct position { chunk* _chunk; size_type _offset; }; position pos() const { return { _current, _current ? _current->offset : 0 }; } // Returns the amount of bytes written since given position. // "pos" must be valid. size_type written_since(position pos) { chunk* c = pos._chunk; if (!c) { return _size; } size_type total = c->offset - pos._offset; c = c->next.get(); while (c) { total += c->offset; c = c->next.get(); } return total; } // Rollbacks all data written after "pos". // Invalidates all placeholders and positions created after "pos". void retract(position pos) { if (!pos._chunk) { *this = {}; return; } _size -= written_since(pos); _current = pos._chunk; _current->next = nullptr; _current->offset = pos._offset; } void reduce_chunk_count() { // FIXME: This is a simplified version. It linearizes the whole buffer // if its size is below max_chunk_size. We probably could also gain // some read performance by doing "real" reduction, i.e. merging // all chunks until all but the last one is max_chunk_size. if (size() < max_chunk_size()) { linearize(); } } bool operator==(const bytes_ostream& other) const { auto as = fragments().begin(); auto as_end = fragments().end(); auto bs = other.fragments().begin(); auto bs_end = other.fragments().end(); auto a = *as++; auto b = *bs++; while (!a.empty() || !b.empty()) { auto now = std::min(a.size(), b.size()); if (!std::equal(a.begin(), a.begin() + now, b.begin(), b.begin() + now)) { return false; } a.remove_prefix(now); if (a.empty() && as != as_end) { a = *as++; } b.remove_prefix(now); if (b.empty() && bs != bs_end) { b = *bs++; } } return true; } bool operator!=(const bytes_ostream& other) const { return !(*this == other); } // Makes this instance empty. // // The first buffer is not deallocated, so callers may rely on the // fact that if they write less than the initial chunk size between // the clear() calls then writes will not involve any memory allocations, // except for the first write made on this instance. void clear() { if (_begin) { _begin->offset = 0; _size = 0; _current = _begin.get(); _begin->next.reset(); } } }; <|endoftext|>
<commit_before>// // calcPWP.cpp // // // Created by Evan McCartney-Melstad on 1/10/15. // // #include "calcPWP.h" #include <iostream> #include <vector> #include <fstream> #include <thread> #include <string> int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) { //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE**** std::cout << "Number of threads: " << numThreads << std::endl; std::streampos size; std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate); //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB! file.seekg (0, std::ios::beg); // Go back to the beginning of the file //file.read((char*)readCounts, size); // cast to a char* to give to file.read //unsigned char* readCounts; //readCounts = new unsigned char[size]; std::vector<unsigned char> readCounts(size); file.read((char*) &readCounts[0], size); file.close(); std::cout << "the entire file content is in memory" << std::endl; std::cout << "the total size of the file is " << size << std::endl; std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements // We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci) //int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line) //int totalLoci = size/(272*2); //std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)); //std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)); //long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates //unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)) First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a vector of two-dimensional vectors... */ std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc... std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) ); std::cout << "Initialized the 3d vectors" << std::endl; // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads //unsigned long long int lociPerThread = numLoci / numThreads; unsigned long long int lociPerThread = (numLoci-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci std::cout << "Initialized lociPerThread with " << numLoci << std::endl; std::vector<std::thread> threadsVec; for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) { std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl; unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread; unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0; std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl; threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning]))); } // Wait on threads to finish for (int i = 0; i < numThreads; ++i) { threadsVec[i].join(); } // Now aggregate the results of the threads and print final results std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0)); std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0)); for (int element = 0; element < 272; element++) { for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) { for (int threadVector = 0; threadVector <= numThreads; threadVector++) { weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement]; pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement]; } } } // Now print out the final output to the pairwise pi file: std::ofstream pwpOUT (outFile); int rowCounter = 0; if (!pwpOUT) { std::cerr << "Crap, " << outFile << "didn't open!" << std::endl; } else { for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { rowCounter++; //std::cout << "Made it past the beginning of the last end for loop" << std::endl; //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl; if (weightingsSum[tortoise][comparisonTortoise] > 0) { //std::cout << weightings[tortoise][comparisonTortoise] << std::endl; //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl; pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl; } else { pwpOUT << "NA" << std::endl; } } } } } else std::cout << "Unable to open file"; return 0; } //int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) { int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) { std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl; for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) { //std::cout << "Processing locus # " << locus << std::endl; if (locus % 100000 == 0) { std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl; } int coverages[numIndividuals]; double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) { unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise; unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1; coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus if ( coverages[tortoise] > 0 ) { //std::cout << "Made it to line 222 for locus " << locus << std::endl; majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1 if (coverages[tortoise] > 1) { unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1); threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0)); } for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) { if (coverages[comparisonTortoise] > 0) { double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise]; threadWeightings[tortoise][comparisonTortoise] += locusWeighting; threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise])); } } } } delete[] majorAlleleFreqs; // Needed to avoid memory leaks } return 0; } <commit_msg>Minor changes<commit_after>// // calcPWP.cpp // // // Created by Evan McCartney-Melstad on 1/10/15. // // #include "calcPWP.h" #include <iostream> #include <vector> #include <fstream> #include <thread> #include <string> int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) { //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE**** std::cout << "Number of threads: " << numThreads << std::endl; std::streampos size; std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate); //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB! file.seekg (0, std::ios::beg); // Go back to the beginning of the file //file.read((char*)readCounts, size); // cast to a char* to give to file.read //unsigned char* readCounts; //readCounts = new unsigned char[size]; std::vector<unsigned char> readCounts(size); file.read((char*) &readCounts[0], size); file.close(); std::cout << "the entire file content is in memory" << std::endl; std::cout << "the total size of the file is " << size << std::endl; std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements // We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci) //int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line) //int totalLoci = size/(272*2); //std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)); //std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)); //long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates //unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0)) First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a vector of two-dimensional vectors... */ std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc... std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) ); std::cout << "Initialized the 3d vectors" << std::endl; // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads //unsigned long long int lociPerThread = numLoci / numThreads; unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci std::cout << "Initialized lociPerThread with " << numLoci << std::endl; std::vector<std::thread> threadsVec; for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) { std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl; unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread; unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0; std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl; threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning]))); } std::cout << "All threads completed launching" << std::endl; // Wait on threads to finish for (int i = 0; i < numThreads; ++i) { threadsVec[i].join(); std::cout << "Joined thread " << i << std::endl; } std::cout << "All threads completed running" << std::endl; // Now aggregate the results of the threads and print final results std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0)); std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0)); for (int element = 0; element < 272; element++) { for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) { for (int threadVector = 0; threadVector <= numThreads; threadVector++) { weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement]; pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement]; } } } // Now print out the final output to the pairwise pi file: std::ofstream pwpOUT (outFile); int rowCounter = 0; if (!pwpOUT) { std::cerr << "Crap, " << outFile << "didn't open!" << std::endl; } else { for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) { for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) { rowCounter++; //std::cout << "Made it past the beginning of the last end for loop" << std::endl; //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl; if (weightingsSum[tortoise][comparisonTortoise] > 0) { //std::cout << weightings[tortoise][comparisonTortoise] << std::endl; //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl; pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl; } else { pwpOUT << "NA" << std::endl; } } } } } else std::cout << "Unable to open file"; return 0; } //int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) { int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) { std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl; for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) { //std::cout << "Processing locus # " << locus << std::endl; if (locus % 100000 == 0) { std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl; } int coverages[numIndividuals]; double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) { unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise; unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1; coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus if ( coverages[tortoise] > 0 ) { //std::cout << "Made it to line 222 for locus " << locus << std::endl; majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1 if (coverages[tortoise] > 1) { unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1); threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0)); } for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) { if (coverages[comparisonTortoise] > 0) { double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise]; threadWeightings[tortoise][comparisonTortoise] += locusWeighting; threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise])); } } } } std::cout << "Made it to deleting majorAlleleFreqs" << std::endl; delete[] majorAlleleFreqs; // Needed to avoid memory leaks } std::cout << "Finished thread ending on locus " << endingLocus << std::endl; return 0; } <|endoftext|>
<commit_before>#include "Player.h" #include <Debug.h> #include "Product.h" #include "Playlist.h" using namespace OpenHome; using namespace OpenHome::MediaPlayer; // Track const Track* Track::iZero = new Track(0, Brn(""), Brn("")); Track::Track(TUint aId, const Brx& aUri, const Brx& aMetadata) : iId(aId) { iUri.Replace(aUri); iMetadata.Replace(aMetadata); } TBool Track::IsId(TUint aId) const { return (aId == iId); } TUint Track::Id() const { return iId; } const Brx& Track::Uri() const { return iUri; } const Brx& Track::Metadata() const { return iMetadata; } // Player Player::Player(IRenderer* aRenderer , Net::DvDevice& aDevice , IStandbyHandler& aStandbyHandler , ISourceIndexHandler& aSourceIndexHandler , bool aStandby , const TChar* aAttributes , const TChar* aManufacturerName , const TChar* aManufacturerInfo , const TChar* aManufacturerUrl , const TChar* aManufacturerImageUri , const TChar* aModelName , const TChar* aModelInfo , const TChar* aModelUrl , const TChar* aModelImageUri , const TChar* aProductRoom , const TChar* aProductName , const TChar* aProductInfo , const TChar* aProductUrl , const TChar* aProductImageUri) : iRenderer(aRenderer) , iMutex("PLYR") , iState(eStopped) , iId(0) { aDevice.SetAttribute("Upnp.Domain", "av.openhome.org"); aDevice.SetAttribute("Upnp.Type", "av.openhome.org"); aDevice.SetAttribute("Upnp.Version", "1"); Bwh tmp(strlen(aProductName) + strlen(aProductRoom) + 1); tmp.Append(aProductRoom); tmp.Append(':'); tmp.Append(aProductName); Brhz friendlyName; tmp.TransferTo(friendlyName); aDevice.SetAttribute("Upnp.FriendlyName", friendlyName.CString()); aDevice.SetAttribute("Upnp.Manufacturer", aManufacturerName); aDevice.SetAttribute("Upnp.ManufacturerUrl", aManufacturerUrl); aDevice.SetAttribute("Upnp.ModelDescription", aModelInfo); aDevice.SetAttribute("Upnp.ModelName", aModelName); aDevice.SetAttribute("Upnp.ModelNumber", ""); aDevice.SetAttribute("Upnp.ModelUrl", aModelUrl); aDevice.SetAttribute("Upnp.SerialNumber", ""); aDevice.SetAttribute("Upnp.Upc", ""); iProduct = new ProviderProduct(aDevice, aStandbyHandler, aSourceIndexHandler, aStandby, aAttributes, aManufacturerName, aManufacturerInfo, aManufacturerUrl, aManufacturerImageUri, aModelName, aModelInfo, aModelUrl, aModelImageUri, aProductRoom, aProductName, aProductInfo, aProductUrl, aProductImageUri); iInfo = new ProviderInfo(aDevice); iTime = new ProviderTime(aDevice); iRenderer->SetStatusHandler(*this); } Player::~Player() { delete iRenderer; delete iInfo; } uint32_t Player::AddSource(Source* aSource) { uint32_t handle = iProduct->AddSource(aSource); aSource->SetHandle(handle); return handle; } Source& Player::GetSource(uint32_t aIndex) { return iProduct->GetSource(aIndex); } void Player::Finished(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Finished %d\n", aId); const Track* finished = iPipeline.front(); ASSERT(finished->Id() == aId); const Track* next = GetSource(aHandle).GetTrack(aId, 1); PipelineClear(); if(next->Id() != 0) { PipelineAppend(next); iRenderer->Play(aHandle, next->Id(), next->Uri().Ptr(), next->Uri().Bytes(), 0); } else { next->DecRef(); } iMutex.Signal(); } void Player::Next(uint32_t aHandle, uint32_t aAfterId, uint32_t& aId, uint8_t aUri[], uint32_t& aUriBytes) { iMutex.Wait(); Log::Print("Player::Next\n"); const Track* track = GetSource(aHandle).GetTrack(aAfterId, 1); aId = track->Id(); ASSERT(aUriBytes >= Track::kMaxUriBytes); memcpy(aUri, track->Uri().Ptr(), track->Uri().Bytes()); aUriBytes = track->Uri().Bytes(); PipelineAppend(track); iMutex.Signal(); } void Player::Buffering(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Buffering\n"); GetSource(aHandle).Buffering(aId); iState = eBuffering; iMutex.Signal(); } void Player::Stopped(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Stopped\n"); GetSource(aHandle).Stopped(aId); iState = eStopped; iMutex.Signal(); } void Player::Paused(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Paused\n"); GetSource(aHandle).Paused(aId); iState = ePaused; iMutex.Signal(); } void Player::Started(uint32_t aHandle, uint32_t aId, uint32_t aDuration, uint32_t aBitRate, uint32_t aBitDepth, uint32_t aSampleRate, bool aLossless, const char* aCodecName) { iMutex.Wait(); const Track* track = iPipeline.front(); ASSERT(track->Id() == aId); Log::Print("Player::Started %d, Duration: %d, BitRate: %d, BitDepth: %d\n", aId, aDuration, aBitRate, aBitDepth); iInfo->SetTrack(*track); iInfo->SetDetails(aDuration, aBitRate, aBitDepth, aSampleRate, aLossless, Brn(aCodecName)); iTime->SetDuration(aDuration); iMutex.Signal(); } void Player::Playing(uint32_t aHandle, uint32_t aId, uint32_t aSeconds) { iMutex.Wait(); Log::Print("Player::Playing %d, Second: %d\n", aId, aSeconds); iTime->SetSeconds(aSeconds); //iId is subtly different from iPipeline.front()->Id() //iId is updated when we get a ::Playing back from the renderer //iPipeline.front()->Id() is updated when we call iRenderer->Play() if( (iId != aId) || (iState != ePlaying) ) { iState = ePlaying; iId = aId; GetSource(aHandle).Playing(aId); } iMutex.Signal(); } void Player::Metatext(uint32_t aHandle, uint32_t aId, uint8_t aMetatext[], uint32_t aMetatextBytes) { Log::Print("Player::Metatext %d\n", aId); iInfo->SetMetatext(Brn(aMetatext, aMetatextBytes)); } void Player::Play(uint32_t aHandle, const Track* aTrack, uint32_t aSecond) { iMutex.Wait(); PlayLocked(aHandle, aTrack, aSecond); iMutex.Signal(); } void Player::Play(uint32_t aHandle, int32_t aRelativeIndex) { iMutex.Wait(); Log::Print("Player::Play with RelativeIndex: %d\n", aRelativeIndex); //If we're paused and no skip is requested, then this command is an Unpause if(aRelativeIndex == 0 && iState == ePaused) { iMutex.Signal(); Unpause(); return; } //Else, 2 options: uint32_t id; if(iPipeline.empty()) { //Nothing in pipeline -> interpret aRelativeIndex from id 0 id = 0; } else { //Something in pipeline -> interpret aRelativeIndex from that id id = (iPipeline.front())->Id(); } const Track* track = GetSource(aHandle).GetTrack(id, aRelativeIndex); //If after all that, the track returned from GetTrack is 0 (ie off the end //of the playlist), then we Stop the renderer if(track->Id() == 0) { iMutex.Signal(); track->DecRef(); iRenderer->Stop(); } else { PlayLocked(aHandle, track, 0); iMutex.Signal(); } } void Player::PlaySecondAbsolute(uint32_t aHandle, uint32_t aSecond) { const Track* track; iMutex.Wait(); if(iPipeline.empty()) { track = GetSource(aHandle).GetTrack(0, 0); } else { track = iPipeline.front(); track->IncRef(); } PlayLocked(aHandle, track, aSecond); iMutex.Signal(); } void Player::PlaySecondRelative(uint32_t aHandle, int32_t aSecond) { iMutex.Wait(); if(iPipeline.empty()) { iMutex.Signal(); return; } const Track* track = iPipeline.front(); track->IncRef(); TUint current = iTime->Seconds(); TUint duration = iTime->Duration(); TUint request; if(aSecond < 0) { if( (current + aSecond) > current) { //overflow -> seeked backwards past 0, set to 0 request = 0; } } else { request = current + aSecond; } if(request > duration) { request = duration; } PlayLocked(aHandle, track, request); iMutex.Signal(); } void Player::Pause() { Log::Print("Player::Pause\n"); iRenderer->Pause(); } void Player::Unpause() { Log::Print("Player::Unpause\n"); iRenderer->Unpause(); } void Player::Stop() { Log::Print("Player::Stop\n"); iRenderer->Stop(); } void Player::Deleted(uint32_t aId, const Track* aReplacement) { Log::Print("Player::Deleted: %d\n", aId); aReplacement->DecRef(); } uint32_t Player::NewId() { return iAtomicInt.Inc(); } void Player::PipelineClear() { if(iPipeline.size() > 0) { std::list<const Track*>::iterator i = iPipeline.begin(); for( ; i != iPipeline.end(); ) { (*i)->DecRef(); std::list<const Track*>::iterator j = i; i++; iPipeline.erase(j); } } } void Player::PipelineAppend(const Track* aTrack) { iPipeline.push_back(aTrack); } void Player::PlayLocked(uint32_t aHandle, const Track* aTrack, uint32_t aSecond) { Log::Print("Player::PlayLocked %d, Second: %d\n", aTrack->Id(), aSecond); PipelineClear(); PipelineAppend(aTrack); iRenderer->Play(aHandle, aTrack->Id(), aTrack->Uri().Ptr(), aTrack->Uri().Bytes(), aSecond); } <commit_msg>Clear pipeline on status of Stopped<commit_after>#include "Player.h" #include <Debug.h> #include "Product.h" #include "Playlist.h" using namespace OpenHome; using namespace OpenHome::MediaPlayer; // Track const Track* Track::iZero = new Track(0, Brn(""), Brn("")); Track::Track(TUint aId, const Brx& aUri, const Brx& aMetadata) : iId(aId) { iUri.Replace(aUri); iMetadata.Replace(aMetadata); } TBool Track::IsId(TUint aId) const { return (aId == iId); } TUint Track::Id() const { return iId; } const Brx& Track::Uri() const { return iUri; } const Brx& Track::Metadata() const { return iMetadata; } // Player Player::Player(IRenderer* aRenderer , Net::DvDevice& aDevice , IStandbyHandler& aStandbyHandler , ISourceIndexHandler& aSourceIndexHandler , bool aStandby , const TChar* aAttributes , const TChar* aManufacturerName , const TChar* aManufacturerInfo , const TChar* aManufacturerUrl , const TChar* aManufacturerImageUri , const TChar* aModelName , const TChar* aModelInfo , const TChar* aModelUrl , const TChar* aModelImageUri , const TChar* aProductRoom , const TChar* aProductName , const TChar* aProductInfo , const TChar* aProductUrl , const TChar* aProductImageUri) : iRenderer(aRenderer) , iMutex("PLYR") , iState(eStopped) , iId(0) { aDevice.SetAttribute("Upnp.Domain", "av.openhome.org"); aDevice.SetAttribute("Upnp.Type", "av.openhome.org"); aDevice.SetAttribute("Upnp.Version", "1"); Bwh tmp(strlen(aProductName) + strlen(aProductRoom) + 1); tmp.Append(aProductRoom); tmp.Append(':'); tmp.Append(aProductName); Brhz friendlyName; tmp.TransferTo(friendlyName); aDevice.SetAttribute("Upnp.FriendlyName", friendlyName.CString()); aDevice.SetAttribute("Upnp.Manufacturer", aManufacturerName); aDevice.SetAttribute("Upnp.ManufacturerUrl", aManufacturerUrl); aDevice.SetAttribute("Upnp.ModelDescription", aModelInfo); aDevice.SetAttribute("Upnp.ModelName", aModelName); aDevice.SetAttribute("Upnp.ModelNumber", ""); aDevice.SetAttribute("Upnp.ModelUrl", aModelUrl); aDevice.SetAttribute("Upnp.SerialNumber", ""); aDevice.SetAttribute("Upnp.Upc", ""); iProduct = new ProviderProduct(aDevice, aStandbyHandler, aSourceIndexHandler, aStandby, aAttributes, aManufacturerName, aManufacturerInfo, aManufacturerUrl, aManufacturerImageUri, aModelName, aModelInfo, aModelUrl, aModelImageUri, aProductRoom, aProductName, aProductInfo, aProductUrl, aProductImageUri); iInfo = new ProviderInfo(aDevice); iTime = new ProviderTime(aDevice); iRenderer->SetStatusHandler(*this); } Player::~Player() { delete iRenderer; delete iInfo; } uint32_t Player::AddSource(Source* aSource) { uint32_t handle = iProduct->AddSource(aSource); aSource->SetHandle(handle); return handle; } Source& Player::GetSource(uint32_t aIndex) { return iProduct->GetSource(aIndex); } void Player::Finished(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Finished %d\n", aId); const Track* finished = iPipeline.front(); ASSERT(finished->Id() == aId); const Track* next = GetSource(aHandle).GetTrack(aId, 1); PipelineClear(); if(next->Id() != 0) { PipelineAppend(next); iRenderer->Play(aHandle, next->Id(), next->Uri().Ptr(), next->Uri().Bytes(), 0); } else { next->DecRef(); } iMutex.Signal(); } void Player::Next(uint32_t aHandle, uint32_t aAfterId, uint32_t& aId, uint8_t aUri[], uint32_t& aUriBytes) { iMutex.Wait(); Log::Print("Player::Next\n"); const Track* track = GetSource(aHandle).GetTrack(aAfterId, 1); aId = track->Id(); ASSERT(aUriBytes >= Track::kMaxUriBytes); memcpy(aUri, track->Uri().Ptr(), track->Uri().Bytes()); aUriBytes = track->Uri().Bytes(); PipelineAppend(track); iMutex.Signal(); } void Player::Buffering(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Buffering\n"); GetSource(aHandle).Buffering(aId); iState = eBuffering; iMutex.Signal(); } void Player::Stopped(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Stopped\n"); GetSource(aHandle).Stopped(aId); iState = eStopped; PipelineClear(); iMutex.Signal(); } void Player::Paused(uint32_t aHandle, uint32_t aId) { iMutex.Wait(); Log::Print("Player::Paused\n"); GetSource(aHandle).Paused(aId); iState = ePaused; iMutex.Signal(); } void Player::Started(uint32_t aHandle, uint32_t aId, uint32_t aDuration, uint32_t aBitRate, uint32_t aBitDepth, uint32_t aSampleRate, bool aLossless, const char* aCodecName) { iMutex.Wait(); const Track* track = iPipeline.front(); ASSERT(track->Id() == aId); Log::Print("Player::Started %d, Duration: %d, BitRate: %d, BitDepth: %d\n", aId, aDuration, aBitRate, aBitDepth); iInfo->SetTrack(*track); iInfo->SetDetails(aDuration, aBitRate, aBitDepth, aSampleRate, aLossless, Brn(aCodecName)); iTime->SetDuration(aDuration); iMutex.Signal(); } void Player::Playing(uint32_t aHandle, uint32_t aId, uint32_t aSeconds) { iMutex.Wait(); Log::Print("Player::Playing %d, Second: %d\n", aId, aSeconds); iTime->SetSeconds(aSeconds); //iId is subtly different from iPipeline.front()->Id() //iId is updated when we get a ::Playing back from the renderer //iPipeline.front()->Id() is updated when we call iRenderer->Play() if( (iId != aId) || (iState != ePlaying) ) { iState = ePlaying; iId = aId; GetSource(aHandle).Playing(aId); } iMutex.Signal(); } void Player::Metatext(uint32_t aHandle, uint32_t aId, uint8_t aMetatext[], uint32_t aMetatextBytes) { Log::Print("Player::Metatext %d\n", aId); iInfo->SetMetatext(Brn(aMetatext, aMetatextBytes)); } void Player::Play(uint32_t aHandle, const Track* aTrack, uint32_t aSecond) { iMutex.Wait(); PlayLocked(aHandle, aTrack, aSecond); iMutex.Signal(); } void Player::Play(uint32_t aHandle, int32_t aRelativeIndex) { iMutex.Wait(); Log::Print("Player::Play with RelativeIndex: %d\n", aRelativeIndex); //If we're paused and no skip is requested, then this command is an Unpause if(aRelativeIndex == 0 && iState == ePaused) { iMutex.Signal(); Unpause(); return; } //Else, 2 options: uint32_t id; if(iPipeline.empty()) { //Nothing in pipeline -> interpret aRelativeIndex from id 0 id = 0; } else { //Something in pipeline -> interpret aRelativeIndex from that id id = (iPipeline.front())->Id(); } const Track* track = GetSource(aHandle).GetTrack(id, aRelativeIndex); //If after all that, the track returned from GetTrack is 0 (ie off the end //of the playlist), then we Stop the renderer if(track->Id() == 0) { iMutex.Signal(); track->DecRef(); iRenderer->Stop(); } else { PlayLocked(aHandle, track, 0); iMutex.Signal(); } } void Player::PlaySecondAbsolute(uint32_t aHandle, uint32_t aSecond) { const Track* track; iMutex.Wait(); if(iPipeline.empty()) { track = GetSource(aHandle).GetTrack(0, 0); } else { track = iPipeline.front(); track->IncRef(); } PlayLocked(aHandle, track, aSecond); iMutex.Signal(); } void Player::PlaySecondRelative(uint32_t aHandle, int32_t aSecond) { iMutex.Wait(); if(iPipeline.empty()) { iMutex.Signal(); return; } const Track* track = iPipeline.front(); track->IncRef(); TUint current = iTime->Seconds(); TUint duration = iTime->Duration(); TUint request; if(aSecond < 0) { if( (current + aSecond) > current) { //overflow -> seeked backwards past 0, set to 0 request = 0; } } else { request = current + aSecond; } if(request > duration) { request = duration; } PlayLocked(aHandle, track, request); iMutex.Signal(); } void Player::Pause() { Log::Print("Player::Pause\n"); iRenderer->Pause(); } void Player::Unpause() { Log::Print("Player::Unpause\n"); iRenderer->Unpause(); } void Player::Stop() { Log::Print("Player::Stop\n"); iRenderer->Stop(); } void Player::Deleted(uint32_t aId, const Track* aReplacement) { Log::Print("Player::Deleted: %d\n", aId); aReplacement->DecRef(); } uint32_t Player::NewId() { return iAtomicInt.Inc(); } void Player::PipelineClear() { if(iPipeline.size() > 0) { std::list<const Track*>::iterator i = iPipeline.begin(); for( ; i != iPipeline.end(); ) { (*i)->DecRef(); std::list<const Track*>::iterator j = i; i++; iPipeline.erase(j); } } } void Player::PipelineAppend(const Track* aTrack) { iPipeline.push_back(aTrack); } void Player::PlayLocked(uint32_t aHandle, const Track* aTrack, uint32_t aSecond) { Log::Print("Player::PlayLocked %d, Second: %d\n", aTrack->Id(), aSecond); PipelineClear(); PipelineAppend(aTrack); iRenderer->Play(aHandle, aTrack->Id(), aTrack->Uri().Ptr(), aTrack->Uri().Bytes(), aSecond); } <|endoftext|>
<commit_before>#include <Vertica.h> using Vertica::ScalarFunction; using Vertica::ScalarFunctionFactory; extern "C" { #include <json/selector.h> #include <json/slice.h> } class JsonQuery : public ScalarFunction { public: virtual void processBlock(Vertica::ServerInterface &, Vertica::BlockReader &argReader, Vertica::BlockWriter &resWriter) { do { const Vertica::VString &jsonSrc = argReader.getStringRef(0); const Vertica::VString &querySrc = argReader.getStringRef(1); Vertica::VString &resSrc = resWriter.getStringRef(); json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length()); json_slice_t jsonOut; if (json_slice_query(&jsonIn, querySrc.data(), querySrc.length(), &jsonOut)) { resSrc.copy(jsonOut.src, jsonOut.len); } else { resSrc.setNull(); } resWriter.next(); } while (argReader.next()); } }; class JsonQueryString : public ScalarFunction { public: virtual void processBlock(Vertica::ServerInterface &, Vertica::BlockReader &argReader, Vertica::BlockWriter &resWriter) { do { const Vertica::VString &jsonSrc = argReader.getStringRef(0); const Vertica::VString &querySrc = argReader.getStringRef(1); Vertica::VString &resSrc = resWriter.getStringRef(); json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length()); json_slice_t jsonOut; bool status = json_slice_query(&jsonIn, querySrc.data(), querySrc.length(), &jsonOut); if (status && jsonOut.len >= 2 && jsonOut.src[0] == '"' && jsonOut.src[jsonOut.len - 1] == '"') { resSrc.copy(jsonOut.src + 1, jsonOut.len - 2); } else { resSrc.setNull(); } resWriter.next(); } while (argReader.next()); } }; class JsonQueryUnquoted : public ScalarFunction { public: virtual void processBlock(Vertica::ServerInterface &, Vertica::BlockReader &argReader, Vertica::BlockWriter &resWriter) { do { const Vertica::VString &jsonSrc = argReader.getStringRef(0); const Vertica::VString &querySrc = argReader.getStringRef(1); Vertica::VString &resSrc = resWriter.getStringRef(); json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length()); json_slice_t jsonOut; bool status = json_slice_query(&jsonIn, querySrc.data(), querySrc.length(), &jsonOut); if (status) { if (jsonOut.len >= 2 && jsonOut.src[0] == '"' && jsonOut.src[jsonOut.len - 1] == '"') { resSrc.copy(jsonOut.src + 1, jsonOut.len - 2); } else { resSrc.copy(jsonOut.src, jsonOut.len); } } else { resSrc.setNull(); } resWriter.next(); } while (argReader.next()); } }; class AbstractJsonQueryFactory : public ScalarFunctionFactory { public: explicit AbstractJsonQueryFactory() { vol = Vertica::IMMUTABLE; strict = Vertica::STRICT; } virtual void getPrototype(Vertica::ServerInterface &, Vertica::ColumnTypes &argTypes, Vertica::ColumnTypes &resTypes) { argTypes.addVarchar(); argTypes.addVarchar(); resTypes.addVarchar(); } virtual void getReturnType(Vertica::ServerInterface &, const Vertica::SizedColumnTypes &argTypes, Vertica::SizedColumnTypes &resTypes) { const Vertica::VerticaType &jsonSrcType = argTypes.getColumnType(0); resTypes.addVarchar(jsonSrcType.getStringLength()); } }; class JsonQueryFactory : public AbstractJsonQueryFactory { public: virtual ScalarFunction *createScalarFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, JsonQuery); } }; class JsonQueryStringFactory : public AbstractJsonQueryFactory { public: virtual ScalarFunction *createScalarFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, JsonQueryString); } }; class JsonQueryUnquotedFactory : public AbstractJsonQueryFactory { public: virtual ScalarFunction *createScalarFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, JsonQueryUnquoted); } }; RegisterFactory(JsonQueryFactory); RegisterFactory(JsonQueryStringFactory); RegisterFactory(JsonQueryUnquotedFactory); <commit_msg>Refactor code duplication in the extension implementation.<commit_after>#include <Vertica.h> using Vertica::ScalarFunction; using Vertica::ScalarFunctionFactory; extern "C" { #include <json/selector.h> #include <json/slice.h> } template<class Q> class AbstractJsonQuery : public ScalarFunction { public: virtual void processBlock(Vertica::ServerInterface &, Vertica::BlockReader &argReader, Vertica::BlockWriter &resWriter) { do { const Vertica::VString &jsonSrc = argReader.getStringRef(0); const Vertica::VString &querySrc = argReader.getStringRef(1); Vertica::VString &resSrc = resWriter.getStringRef(); json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length()); json_slice_t jsonOut; if (json_slice_query(&jsonIn, querySrc.data(), querySrc.length(), &jsonOut)) { Q::copyResult(jsonOut, resSrc); } else { resSrc.setNull(); } resWriter.next(); } while (argReader.next()); } }; class JsonQuery : public AbstractJsonQuery<JsonQuery> { public: static void copyResult(const json_slice_t &json, Vertica::VString &result) { result.copy(json.src, json.len); } }; class JsonQueryString : public AbstractJsonQuery<JsonQueryString> { public: static void copyResult(const json_slice_t &json, Vertica::VString &result) { if (json.len >= 2 && json.src[0] == '"' && json.src[json.len - 1] == '"') { result.copy(json.src + 1, json.len - 2); } else { result.setNull(); } } }; class JsonQueryUnquoted : public AbstractJsonQuery<JsonQueryUnquoted> { public: static void copyResult(const json_slice_t &json, Vertica::VString &result) { if (json.len >= 2 && json.src[0] == '"' && json.src[json.len - 1] == '"') { result.copy(json.src + 1, json.len - 2); } else { result.copy(json.src, json.len); } } }; class AbstractJsonQueryFactory : public ScalarFunctionFactory { public: explicit AbstractJsonQueryFactory() { vol = Vertica::IMMUTABLE; strict = Vertica::STRICT; } virtual void getPrototype(Vertica::ServerInterface &, Vertica::ColumnTypes &argTypes, Vertica::ColumnTypes &resTypes) { argTypes.addVarchar(); argTypes.addVarchar(); resTypes.addVarchar(); } virtual void getReturnType(Vertica::ServerInterface &, const Vertica::SizedColumnTypes &argTypes, Vertica::SizedColumnTypes &resTypes) { const Vertica::VerticaType &jsonSrcType = argTypes.getColumnType(0); resTypes.addVarchar(jsonSrcType.getStringLength()); } }; class JsonQueryFactory : public AbstractJsonQueryFactory { public: virtual ScalarFunction *createScalarFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, JsonQuery); } }; class JsonQueryStringFactory : public AbstractJsonQueryFactory { public: virtual ScalarFunction *createScalarFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, JsonQueryString); } }; class JsonQueryUnquotedFactory : public AbstractJsonQueryFactory { public: virtual ScalarFunction *createScalarFunction(Vertica::ServerInterface &iface) { return vt_createFuncObj(iface.allocator, JsonQueryUnquoted); } }; RegisterFactory(JsonQueryFactory); RegisterFactory(JsonQueryStringFactory); RegisterFactory(JsonQueryUnquotedFactory); <|endoftext|>
<commit_before> #include <string> #include <iostream> #include <algorithm> #include <mutex> #include "boost/lockfree/queue.hpp" #include "LogServer.hpp" struct LogServer::LogServerImpl { LogServerImpl() : m_messageQueue(1024) {} public: typedef LogMessage queue_element_type; typedef boost::lockfree::queue<queue_element_type*> queue_type; queue_type m_messageQueue; std::mutex m_stdoutMutex; void enqueue(queue_element_type* msg) { while (!m_messageQueue.push(msg)) ; } void listen() { queue_element_type* msg(nullptr); while (true) { if (m_messageQueue.pop(msg)) { msg->write(); delete msg; } } // while } }; // end struct LogServerImpl // Definitions of LogServer public interface // constructors LogServer::LogServer(bool debug) : m_pimpl(std::make_unique<LogServerImpl>()), m_debug(debug) {} LogServer::~LogServer() {} LogServer::LogServer(LogServer&& other) : m_pimpl{std::move(other.m_pimpl)} {} void LogServer::network(const std::string& msg) { m_pimpl->enqueue(new Log::NetworkMessage(msg)); } void LogServer::start() { m_pimpl->listen(); } void LogServer::forwardEnqueue(LogMessage* msg) { m_pimpl->enqueue(msg); } <commit_msg>Fixed server hogging 100% CPU for no reason due to logserver being in non-sleeping spinlock.<commit_after> #include <string> #include <iostream> #include <algorithm> #include <mutex> #include <thread> #include <chrono> #include "boost/lockfree/queue.hpp" #include "LogServer.hpp" struct LogServer::LogServerImpl { LogServerImpl() : m_messageQueue(1024) {} public: typedef LogMessage queue_element_type; typedef boost::lockfree::queue<queue_element_type*> queue_type; queue_type m_messageQueue; std::mutex m_stdoutMutex; void enqueue(queue_element_type* msg) { while (!m_messageQueue.push(msg)) ; } void listen() { queue_element_type* msg(nullptr); while (true) { if (m_messageQueue.pop(msg)) { msg->write(); delete msg; } else { using namespace std::literals; std::this_thread::sleep_for(3s); } } // while } }; // end struct LogServerImpl // Definitions of LogServer public interface // constructors LogServer::LogServer(bool debug) : m_pimpl(std::make_unique<LogServerImpl>()), m_debug(debug) {} LogServer::~LogServer() {} LogServer::LogServer(LogServer&& other) : m_pimpl{std::move(other.m_pimpl)} {} void LogServer::network(const std::string& msg) { m_pimpl->enqueue(new Log::NetworkMessage(msg)); } void LogServer::start() { m_pimpl->listen(); } void LogServer::forwardEnqueue(LogMessage* msg) { m_pimpl->enqueue(msg); } <|endoftext|>
<commit_before>#pragma once #include <eosio/blockvault_client_plugin/blockvault.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> namespace eosio { namespace blockvault { template <typename BP> struct blockvault_sync_strategy : public sync_callback { blockvault_sync_strategy(block_vault_interface* blockvault, BP& blockchain_provider, std::function<void()> shutdown, std::function<bool()> check_shutdown) : _blockvault(blockvault) , _blockchain_provider(blockchain_provider) , _shutdown(shutdown) , _check_shutdown(check_shutdown) , _startup_run(false) , _received_snapshot(false) { EOS_ASSERT(nullptr != blockvault, plugin_exception, "block_vault_interface cannot be null"); } ~blockvault_sync_strategy() { if (_num_unlinkable_blocks) wlog("${num} out of ${total} blocks received are unlinkable", ("num", _num_unlinkable_blocks)("total", _num_blocks_received)); } void run_startup() { _blockchain_provider.do_non_snapshot_startup(_shutdown, _check_shutdown); _startup_run = true; } void do_sync() { auto head_block = _blockchain_provider.chain->last_irreversible_block(); if (nullptr != head_block) { block_id_type bid = head_block->calculate_id(); ilog("Requesting blockvault sync from block id ${id}, block_num ${num}", ("id", (const string)bid)("num", head_block->block_num())); _blockvault->sync(&bid, *this); } else { ilog("Requesting complete blockvault sync."); _blockvault->sync(nullptr, *this); } if (!_startup_run) { ilog("Received no data from blockvault."); run_startup(); } ilog("Sync from blockvault completed. ${snap}. ${blks} blocks received. ${ulnk} blocks unlinkable", ("snap", _received_snapshot ? "Got snapshot" : "No snapshot") ("blks", _num_blocks_received)("ulnk", _num_unlinkable_blocks)); } void on_snapshot(const char* snapshot_filename) override final { ilog("Received snapshot from blockvault ${fn}", ("fn", snapshot_filename)); EOS_ASSERT(!_received_snapshot, plugin_exception, "Received multiple snapshots from blockvault." ); _received_snapshot = true; if (_check_shutdown()) { _shutdown(); } auto infile = std::ifstream(snapshot_filename, (std::ios::in | std::ios::binary)); auto reader = std::make_shared<chain::istream_snapshot_reader>(infile); _blockchain_provider.chain->startup(_shutdown, _check_shutdown, reader); _startup_run = true; infile.close(); _snapshot_height = _blockchain_provider.chain->head_block_num(); } void on_block(eosio::chain::signed_block_ptr block) override final { if (0 == (_num_blocks_received % 100)) { dlog("Received block number ${bn}", ("bn", block->block_num())); } if (_check_shutdown()) { _shutdown(); } if (!_startup_run) { run_startup(); } try { ++_num_blocks_received; auto rc = _blockchain_provider.incoming_blockvault_sync_method(block, (!_received_snapshot || (block->block_num() != _snapshot_height +1))); EOS_ASSERT(rc, plugin_exception, "Unable to sync block from blockvault, block num=${bnum}, block id=${bid}", ("bnum", block->block_num())("bid", block->calculate_id())); } catch (unlinkable_block_exception& e) { if (block->block_num() == 2) { elog("Received unlinkable block 2. Please double check if --genesis-json and --genesis-timestamp are " "correctly specified"); throw e; } ++_num_unlinkable_blocks; } } private: block_vault_interface* _blockvault; BP& _blockchain_provider; std::function<void()> _shutdown; std::function<bool()> _check_shutdown; bool _startup_run; bool _received_snapshot; uint32_t _num_unlinkable_blocks = 0; uint32_t _num_blocks_received = 0; uint32_t _snapshot_height = 0; }; } // namespace blockvault } // namespace eosio <commit_msg>cleaned up logical expression<commit_after>#pragma once #include <eosio/blockvault_client_plugin/blockvault.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> namespace eosio { namespace blockvault { template <typename BP> struct blockvault_sync_strategy : public sync_callback { blockvault_sync_strategy(block_vault_interface* blockvault, BP& blockchain_provider, std::function<void()> shutdown, std::function<bool()> check_shutdown) : _blockvault(blockvault) , _blockchain_provider(blockchain_provider) , _shutdown(shutdown) , _check_shutdown(check_shutdown) , _startup_run(false) , _received_snapshot(false) { EOS_ASSERT(nullptr != blockvault, plugin_exception, "block_vault_interface cannot be null"); } ~blockvault_sync_strategy() { if (_num_unlinkable_blocks) wlog("${num} out of ${total} blocks received are unlinkable", ("num", _num_unlinkable_blocks)("total", _num_blocks_received)); } void run_startup() { _blockchain_provider.do_non_snapshot_startup(_shutdown, _check_shutdown); _startup_run = true; } void do_sync() { auto head_block = _blockchain_provider.chain->last_irreversible_block(); if (nullptr != head_block) { block_id_type bid = head_block->calculate_id(); ilog("Requesting blockvault sync from block id ${id}, block_num ${num}", ("id", (const string)bid)("num", head_block->block_num())); _blockvault->sync(&bid, *this); } else { ilog("Requesting complete blockvault sync."); _blockvault->sync(nullptr, *this); } if (!_startup_run) { ilog("Received no data from blockvault."); run_startup(); } ilog("Sync from blockvault completed. ${snap}. ${blks} blocks received. ${ulnk} blocks unlinkable", ("snap", _received_snapshot ? "Got snapshot" : "No snapshot") ("blks", _num_blocks_received)("ulnk", _num_unlinkable_blocks)); } void on_snapshot(const char* snapshot_filename) override final { ilog("Received snapshot from blockvault ${fn}", ("fn", snapshot_filename)); EOS_ASSERT(!_received_snapshot, plugin_exception, "Received multiple snapshots from blockvault." ); _received_snapshot = true; if (_check_shutdown()) { _shutdown(); } auto infile = std::ifstream(snapshot_filename, (std::ios::in | std::ios::binary)); auto reader = std::make_shared<chain::istream_snapshot_reader>(infile); _blockchain_provider.chain->startup(_shutdown, _check_shutdown, reader); _startup_run = true; infile.close(); _snapshot_height = _blockchain_provider.chain->head_block_num(); } void on_block(eosio::chain::signed_block_ptr block) override final { if (0 == (_num_blocks_received % 100)) { dlog("Received block number ${bn}", ("bn", block->block_num())); } if (_check_shutdown()) { _shutdown(); } if (!_startup_run) { run_startup(); } try { ++_num_blocks_received; auto rc = _blockchain_provider.incoming_blockvault_sync_method(block, !(_received_snapshot && block->block_num() == _snapshot_height +1)); EOS_ASSERT(rc, plugin_exception, "Unable to sync block from blockvault, block num=${bnum}, block id=${bid}", ("bnum", block->block_num())("bid", block->calculate_id())); } catch (unlinkable_block_exception& e) { if (block->block_num() == 2) { elog("Received unlinkable block 2. Please double check if --genesis-json and --genesis-timestamp are " "correctly specified"); throw e; } ++_num_unlinkable_blocks; } } private: block_vault_interface* _blockvault; BP& _blockchain_provider; std::function<void()> _shutdown; std::function<bool()> _check_shutdown; bool _startup_run; bool _received_snapshot; uint32_t _num_unlinkable_blocks = 0; uint32_t _num_blocks_received = 0; uint32_t _snapshot_height = 0; }; } // namespace blockvault } // namespace eosio <|endoftext|>
<commit_before>#include "MenuScene.hpp" #include "MenuBehaviors.hpp" MenuScene::MenuScene(SceneId id, Game* game) : Scene(id, game) { _screenAct = nullptr; } MenuScene::~MenuScene() { delScreenAct(); } void MenuScene::init() { _clk.reset(); screen(MENU_SCR_TITLE); _state = SCENE_LOADED; } void MenuScene::destroy() { delScreenAct(); } void MenuScene::delScreenAct() { if (_screenAct != nullptr) { _game->destroy(_screenAct); _screenAct = nullptr; } } void MenuScene::screen(MenuScreen scr) { _screen = scr; // fry previous actor and add new one delScreenAct(); _screenAct = _game->makeActor(); switch (_screen) { case MENU_SCR_TITLE: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Red); _screenAct->addBehavior<MenuTitleBehavior>(this); break; case MENU_SCR_CONTROLS: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Green); //_screenAct->addBehavior<MenuControlsBehavior>(this); break; case MENU_SCR_CREDITS: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Blue); //_screenAct->addBehavior<MenuCreditsBehavior>(this); break; case MENU_SCR_HI_SCORE: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Yellow); //_screenAct->addBehavior<MenuHiScoreBehavior>(this); break; default: // remove actor if we failed to set a behavior delScreenAct(); } } void MenuScene::startGame() { _state = SCENE_DONE; } <commit_msg>navigation start<commit_after>#include "MenuScene.hpp" #include "MenuBehaviors.hpp" MenuScene::MenuScene(SceneId id, Game* game) : Scene(id, game) { _screenAct = nullptr; } MenuScene::~MenuScene() { //delScreenAct(); // Al cerrar la app: Intentando eliminar un actor inexistente } void MenuScene::init() { _clk.reset(); screen(MENU_SCR_TITLE); _state = SCENE_LOADED; } void MenuScene::destroy() { //delScreenAct(); // Al cerrar la app: Intentando eliminar un actor inexistente } void MenuScene::delScreenAct() { if (_screenAct != nullptr) { _game->destroy(_screenAct); _screenAct = nullptr; } } void MenuScene::screen(MenuScreen scr) { _screen = scr; // fry previous actor and add new one delScreenAct(); _screenAct = _game->makeActor(); switch (_screen) { case MENU_SCR_TITLE: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Red); _screenAct->addBehavior<MenuTitleBehavior>(this); break; case MENU_SCR_CONTROLS: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Green); //_screenAct->addBehavior<MenuControlsBehavior>(this); break; case MENU_SCR_CREDITS: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Blue); //_screenAct->addBehavior<MenuCreditsBehavior>(this); break; case MENU_SCR_HI_SCORE: _screenAct->addBehavior<Rectangle>(5, 5, sf::Color::Yellow); //_screenAct->addBehavior<MenuHiScoreBehavior>(this); break; default: // remove actor if we failed to set a behavior delScreenAct(); } } void MenuScene::startGame() { _state = SCENE_DONE; } <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #include <boost/random/mersenne_twister.hpp> #include <gtest/gtest.h> #include <math_util/random.h> #include <ros/ros.h> TEST(RandomTests, GetUniformRandomSample) { boost::random::mt19937 gen; std::vector<int32_t> sample; math_util::GetUniformRandomSample<boost::random::mt19937>(gen, 0, 100, 10, sample); EXPECT_EQ(10, sample.size()); math_util::GetUniformRandomSample<boost::random::mt19937>(gen, 0, 100, 90, sample); EXPECT_EQ(90, sample.size()); } TEST(RandomTests, RandomGenerator) { math_util::RandomGenerator gen; std::vector<int32_t> sample; gen.GetUniformRandomSample(0, 100, 10, sample); EXPECT_EQ(10, sample.size()); gen.GetUniformRandomSample(0, 100, 90, sample); EXPECT_EQ(90, sample.size()); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>fix tests for random<commit_after>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #include <boost/random/mersenne_twister.hpp> #include <gtest/gtest.h> #include <math_util/random.h> #include <ros/ros.h> #ifdef BOOST_1_46 namespace boost_random = boost; #else namespace boost_random = boost::random; #endif TEST(RandomTests, GetUniformRandomSample) { boost_random::mt19937 gen; std::vector<int32_t> sample; math_util::GetUniformRandomSample<boost_random::mt19937>(gen, 0, 100, 10, sample); EXPECT_EQ(10, sample.size()); math_util::GetUniformRandomSample<boost_random::mt19937>(gen, 0, 100, 90, sample); EXPECT_EQ(90, sample.size()); } TEST(RandomTests, RandomGenerator) { math_util::RandomGenerator gen; std::vector<int32_t> sample; gen.GetUniformRandomSample(0, 100, 10, sample); EXPECT_EQ(10, sample.size()); gen.GetUniformRandomSample(0, 100, 90, sample); EXPECT_EQ(90, sample.size()); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/algorithm/heap_algorithm.hpp> #include <boost/range/algorithm/reverse.hpp> #include <boost/move/iterator.hpp> #include "mutation_reader.hh" #include "core/future-util.hh" #include "utils/move.hh" #include "stdx.hh" template<typename T> T move_and_clear(T& obj) { T x = std::move(obj); obj = T(); return x; } future<> combined_mutation_reader::prepare_next() { return parallel_for_each(_next, [this] (mutation_reader* mr) { return (*mr)().then([this, mr] (streamed_mutation_opt next) { if (next) { _ptables.emplace_back(mutation_and_reader { std::move(*next), mr }); boost::range::push_heap(_ptables, &heap_compare); } }); }).then([this] { _next.clear(); }); } future<streamed_mutation_opt> combined_mutation_reader::next() { if (_current.empty() && !_next.empty()) { return prepare_next().then([this] { return next(); }); } if (_ptables.empty()) { return make_ready_future<streamed_mutation_opt>(); }; while (!_ptables.empty()) { boost::range::pop_heap(_ptables, &heap_compare); auto& candidate = _ptables.back(); streamed_mutation& m = candidate.m; if (!_current.empty() && !_current.back().decorated_key().equal(*m.schema(), m.decorated_key())) { // key has changed, so emit accumulated mutation boost::range::push_heap(_ptables, &heap_compare); return make_ready_future<streamed_mutation_opt>(merge_mutations(move_and_clear(_current))); } _current.emplace_back(std::move(m)); _next.emplace_back(candidate.read); _ptables.pop_back(); } return make_ready_future<streamed_mutation_opt>(merge_mutations(move_and_clear(_current))); } void combined_mutation_reader::init_mutation_reader_set(std::vector<mutation_reader*> readers) { _all_readers = std::move(readers); _next.assign(_all_readers.begin(), _all_readers.end()); _ptables.reserve(_all_readers.size()); } future<> combined_mutation_reader::fast_forward_to(std::vector<mutation_reader*> to_add, std::vector<mutation_reader*> to_remove, const dht::partition_range& pr) { _ptables.clear(); std::vector<mutation_reader*> new_readers; boost::range::sort(_all_readers); boost::range::sort(to_remove); boost::range::set_difference(_all_readers, to_remove, std::back_inserter(new_readers)); _all_readers = std::move(new_readers); return parallel_for_each(_all_readers, [this, &pr] (mutation_reader* mr) { return mr->fast_forward_to(pr); }).then([this, to_add = std::move(to_add)] { _all_readers.insert(_all_readers.end(), to_add.begin(), to_add.end()); _next.assign(_all_readers.begin(), _all_readers.end()); }); } combined_mutation_reader::combined_mutation_reader(std::vector<mutation_reader> readers) : _readers(std::move(readers)) { _next.reserve(_readers.size()); _current.reserve(_readers.size()); _ptables.reserve(_readers.size()); for (auto&& r : _readers) { _next.emplace_back(&r); } _all_readers.assign(_next.begin(), _next.end()); } future<> combined_mutation_reader::fast_forward_to(const dht::partition_range& pr) { _ptables.clear(); _next.assign(_all_readers.begin(), _all_readers.end()); return parallel_for_each(_next, [this, &pr] (mutation_reader* mr) { return mr->fast_forward_to(pr); }); } future<streamed_mutation_opt> combined_mutation_reader::operator()() { return next(); } mutation_reader make_combined_reader(std::vector<mutation_reader> readers) { return make_mutation_reader<combined_mutation_reader>(std::move(readers)); } mutation_reader make_combined_reader(mutation_reader&& a, mutation_reader&& b) { std::vector<mutation_reader> v; v.reserve(2); v.push_back(std::move(a)); v.push_back(std::move(b)); return make_combined_reader(std::move(v)); } class reader_returning final : public mutation_reader::impl { streamed_mutation _m; bool _done = false; public: reader_returning(streamed_mutation m) : _m(std::move(m)) { } virtual future<streamed_mutation_opt> operator()() override { if (_done) { return make_ready_future<streamed_mutation_opt>(); } else { _done = true; return make_ready_future<streamed_mutation_opt>(std::move(_m)); } } }; mutation_reader make_reader_returning(mutation m, streamed_mutation::forwarding fwd) { return make_mutation_reader<reader_returning>(streamed_mutation_from_mutation(std::move(m), std::move(fwd))); } mutation_reader make_reader_returning(streamed_mutation m) { return make_mutation_reader<reader_returning>(std::move(m)); } class reader_returning_many final : public mutation_reader::impl { std::vector<streamed_mutation> _m; dht::partition_range _pr; public: reader_returning_many(std::vector<streamed_mutation> m, const dht::partition_range& pr) : _m(std::move(m)), _pr(pr) { boost::range::reverse(_m); } virtual future<streamed_mutation_opt> operator()() override { while (!_m.empty()) { auto& sm = _m.back(); dht::ring_position_comparator cmp(*sm.schema()); if (_pr.before(sm.decorated_key(), cmp)) { _m.pop_back(); } else if (_pr.after(sm.decorated_key(), cmp)) { break; } else { auto m = std::move(sm); _m.pop_back(); return make_ready_future<streamed_mutation_opt>(std::move(m)); } } return make_ready_future<streamed_mutation_opt>(); } virtual future<> fast_forward_to(const dht::partition_range& pr) override { _pr = pr; return make_ready_future<>(); } }; mutation_reader make_reader_returning_many(std::vector<mutation> mutations, const query::partition_slice& slice, streamed_mutation::forwarding fwd) { std::vector<streamed_mutation> streamed_mutations; streamed_mutations.reserve(mutations.size()); for (auto& m : mutations) { auto ck_ranges = query::clustering_key_filter_ranges::get_ranges(*m.schema(), slice, m.key()); auto mp = mutation_partition(std::move(m.partition()), *m.schema(), std::move(ck_ranges)); auto sm = streamed_mutation_from_mutation(mutation(m.schema(), m.decorated_key(), std::move(mp)), fwd); streamed_mutations.emplace_back(std::move(sm)); } return make_mutation_reader<reader_returning_many>(std::move(streamed_mutations), query::full_partition_range); } mutation_reader make_reader_returning_many(std::vector<mutation> mutations, const dht::partition_range& pr) { std::vector<streamed_mutation> streamed_mutations; boost::range::transform(mutations, std::back_inserter(streamed_mutations), [] (auto& m) { return streamed_mutation_from_mutation(std::move(m)); }); return make_mutation_reader<reader_returning_many>(std::move(streamed_mutations), pr); } mutation_reader make_reader_returning_many(std::vector<streamed_mutation> mutations) { return make_mutation_reader<reader_returning_many>(std::move(mutations), query::full_partition_range); } class empty_reader final : public mutation_reader::impl { public: virtual future<streamed_mutation_opt> operator()() override { return make_ready_future<streamed_mutation_opt>(); } virtual future<> fast_forward_to(const dht::partition_range&) override { return make_ready_future<>(); } }; mutation_reader make_empty_reader() { return make_mutation_reader<empty_reader>(); } class restricting_mutation_reader : public mutation_reader::impl { const restricted_mutation_reader_config& _config; unsigned _weight = 0; bool _waited = false; mutation_reader _base; public: restricting_mutation_reader(const restricted_mutation_reader_config& config, unsigned weight, mutation_reader&& base) : _config(config), _weight(weight), _base(std::move(base)) { if (_config.sem->waiters() >= _config.max_queue_length) { _config.raise_queue_overloaded_exception(); } } ~restricting_mutation_reader() { if (_waited) { _config.sem->signal(_weight); } } future<streamed_mutation_opt> operator()() override { // FIXME: we should defer freeing until the mutation is freed, perhaps, // rather than just returned if (_waited) { return _base(); } auto waited = _config.timeout.count() != 0 ? _config.sem->wait(_config.timeout, _weight) : _config.sem->wait(_weight); return waited.then([this] { _waited = true; return _base(); }); } virtual future<> fast_forward_to(const dht::partition_range& pr) override { return _base.fast_forward_to(pr); } }; mutation_reader make_restricted_reader(const restricted_mutation_reader_config& config, unsigned weight, mutation_reader&& base) { return make_mutation_reader<restricting_mutation_reader>(config, weight, std::move(base)); } class multi_range_mutation_reader : public mutation_reader::impl { public: using ranges_vector = dht::partition_range_vector; private: const ranges_vector& _ranges; ranges_vector::const_iterator _current_range; mutation_reader _reader; public: multi_range_mutation_reader(schema_ptr s, mutation_source source, const ranges_vector& ranges, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, streamed_mutation::forwarding fwd, mutation_reader::forwarding fwd_mr) : _ranges(ranges) , _current_range(_ranges.begin()) , _reader(source(s, *_current_range, slice, pc, trace_state, fwd, _ranges.size() > 1 ? mutation_reader::forwarding::yes : fwd_mr)) { } virtual future<streamed_mutation_opt> operator()() override { return repeat_until_value([this] { return _reader().then([this] (streamed_mutation_opt smopt) { if (smopt) { return make_ready_future<stdx::optional<streamed_mutation_opt>>(std::move(smopt)); } ++_current_range; if (_current_range == _ranges.end()) { return make_ready_future<stdx::optional<streamed_mutation_opt>>(streamed_mutation_opt()); } return _reader.fast_forward_to(*_current_range).then([] { return make_ready_future<stdx::optional<streamed_mutation_opt>>(); }); }); }); } virtual future<> fast_forward_to(const dht::partition_range& pr) override { // When end of pr is reached, this reader will increment _current_range // and notice that it now points to _ranges.end(). _current_range = std::prev(_ranges.end()); return _reader.fast_forward_to(pr); } }; mutation_reader make_multi_range_reader(schema_ptr s, mutation_source source, const dht::partition_range_vector& ranges, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, streamed_mutation::forwarding fwd, mutation_reader::forwarding fwd_mr) { return make_mutation_reader<multi_range_mutation_reader>(std::move(s), std::move(source), ranges, slice, pc, std::move(trace_state), fwd, fwd_mr); } snapshot_source make_empty_snapshot_source() { return snapshot_source([] { return make_empty_mutation_source(); }); } mutation_source make_empty_mutation_source() { return mutation_source([](schema_ptr s, const dht::partition_range& pr, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr tr, streamed_mutation::forwarding fwd) { return make_empty_reader(); }); } mutation_source make_combined_mutation_source(std::vector<mutation_source> addends) { return mutation_source([addends = std::move(addends)] (schema_ptr s, const dht::partition_range& pr, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr tr, streamed_mutation::forwarding fwd) { std::vector<mutation_reader> rd; rd.reserve(addends.size()); for (auto&& ms : addends) { rd.emplace_back(ms(s, pr, slice, pc, tr, fwd)); } return make_combined_reader(std::move(rd)); }); } <commit_msg>combined_mutation_reader: do not pop mutation with different key<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/algorithm/heap_algorithm.hpp> #include <boost/range/algorithm/reverse.hpp> #include <boost/move/iterator.hpp> #include "mutation_reader.hh" #include "core/future-util.hh" #include "utils/move.hh" #include "stdx.hh" template<typename T> T move_and_clear(T& obj) { T x = std::move(obj); obj = T(); return x; } future<> combined_mutation_reader::prepare_next() { return parallel_for_each(_next, [this] (mutation_reader* mr) { return (*mr)().then([this, mr] (streamed_mutation_opt next) { if (next) { _ptables.emplace_back(mutation_and_reader { std::move(*next), mr }); boost::range::push_heap(_ptables, &heap_compare); } }); }).then([this] { _next.clear(); }); } future<streamed_mutation_opt> combined_mutation_reader::next() { if (_current.empty() && !_next.empty()) { return prepare_next().then([this] { return next(); }); } if (_ptables.empty()) { return make_ready_future<streamed_mutation_opt>(); }; while (!_ptables.empty()) { boost::range::pop_heap(_ptables, &heap_compare); auto& candidate = _ptables.back(); streamed_mutation& m = candidate.m; _current.emplace_back(std::move(m)); _next.emplace_back(candidate.read); _ptables.pop_back(); if (_ptables.empty() || !_current.back().decorated_key().equal(*_current.back().schema(), _ptables.front().m.decorated_key())) { // key has changed, so emit accumulated mutation break; } } return make_ready_future<streamed_mutation_opt>(merge_mutations(move_and_clear(_current))); } void combined_mutation_reader::init_mutation_reader_set(std::vector<mutation_reader*> readers) { _all_readers = std::move(readers); _next.assign(_all_readers.begin(), _all_readers.end()); _ptables.reserve(_all_readers.size()); } future<> combined_mutation_reader::fast_forward_to(std::vector<mutation_reader*> to_add, std::vector<mutation_reader*> to_remove, const dht::partition_range& pr) { _ptables.clear(); std::vector<mutation_reader*> new_readers; boost::range::sort(_all_readers); boost::range::sort(to_remove); boost::range::set_difference(_all_readers, to_remove, std::back_inserter(new_readers)); _all_readers = std::move(new_readers); return parallel_for_each(_all_readers, [this, &pr] (mutation_reader* mr) { return mr->fast_forward_to(pr); }).then([this, to_add = std::move(to_add)] { _all_readers.insert(_all_readers.end(), to_add.begin(), to_add.end()); _next.assign(_all_readers.begin(), _all_readers.end()); }); } combined_mutation_reader::combined_mutation_reader(std::vector<mutation_reader> readers) : _readers(std::move(readers)) { _next.reserve(_readers.size()); _current.reserve(_readers.size()); _ptables.reserve(_readers.size()); for (auto&& r : _readers) { _next.emplace_back(&r); } _all_readers.assign(_next.begin(), _next.end()); } future<> combined_mutation_reader::fast_forward_to(const dht::partition_range& pr) { _ptables.clear(); _next.assign(_all_readers.begin(), _all_readers.end()); return parallel_for_each(_next, [this, &pr] (mutation_reader* mr) { return mr->fast_forward_to(pr); }); } future<streamed_mutation_opt> combined_mutation_reader::operator()() { return next(); } mutation_reader make_combined_reader(std::vector<mutation_reader> readers) { return make_mutation_reader<combined_mutation_reader>(std::move(readers)); } mutation_reader make_combined_reader(mutation_reader&& a, mutation_reader&& b) { std::vector<mutation_reader> v; v.reserve(2); v.push_back(std::move(a)); v.push_back(std::move(b)); return make_combined_reader(std::move(v)); } class reader_returning final : public mutation_reader::impl { streamed_mutation _m; bool _done = false; public: reader_returning(streamed_mutation m) : _m(std::move(m)) { } virtual future<streamed_mutation_opt> operator()() override { if (_done) { return make_ready_future<streamed_mutation_opt>(); } else { _done = true; return make_ready_future<streamed_mutation_opt>(std::move(_m)); } } }; mutation_reader make_reader_returning(mutation m, streamed_mutation::forwarding fwd) { return make_mutation_reader<reader_returning>(streamed_mutation_from_mutation(std::move(m), std::move(fwd))); } mutation_reader make_reader_returning(streamed_mutation m) { return make_mutation_reader<reader_returning>(std::move(m)); } class reader_returning_many final : public mutation_reader::impl { std::vector<streamed_mutation> _m; dht::partition_range _pr; public: reader_returning_many(std::vector<streamed_mutation> m, const dht::partition_range& pr) : _m(std::move(m)), _pr(pr) { boost::range::reverse(_m); } virtual future<streamed_mutation_opt> operator()() override { while (!_m.empty()) { auto& sm = _m.back(); dht::ring_position_comparator cmp(*sm.schema()); if (_pr.before(sm.decorated_key(), cmp)) { _m.pop_back(); } else if (_pr.after(sm.decorated_key(), cmp)) { break; } else { auto m = std::move(sm); _m.pop_back(); return make_ready_future<streamed_mutation_opt>(std::move(m)); } } return make_ready_future<streamed_mutation_opt>(); } virtual future<> fast_forward_to(const dht::partition_range& pr) override { _pr = pr; return make_ready_future<>(); } }; mutation_reader make_reader_returning_many(std::vector<mutation> mutations, const query::partition_slice& slice, streamed_mutation::forwarding fwd) { std::vector<streamed_mutation> streamed_mutations; streamed_mutations.reserve(mutations.size()); for (auto& m : mutations) { auto ck_ranges = query::clustering_key_filter_ranges::get_ranges(*m.schema(), slice, m.key()); auto mp = mutation_partition(std::move(m.partition()), *m.schema(), std::move(ck_ranges)); auto sm = streamed_mutation_from_mutation(mutation(m.schema(), m.decorated_key(), std::move(mp)), fwd); streamed_mutations.emplace_back(std::move(sm)); } return make_mutation_reader<reader_returning_many>(std::move(streamed_mutations), query::full_partition_range); } mutation_reader make_reader_returning_many(std::vector<mutation> mutations, const dht::partition_range& pr) { std::vector<streamed_mutation> streamed_mutations; boost::range::transform(mutations, std::back_inserter(streamed_mutations), [] (auto& m) { return streamed_mutation_from_mutation(std::move(m)); }); return make_mutation_reader<reader_returning_many>(std::move(streamed_mutations), pr); } mutation_reader make_reader_returning_many(std::vector<streamed_mutation> mutations) { return make_mutation_reader<reader_returning_many>(std::move(mutations), query::full_partition_range); } class empty_reader final : public mutation_reader::impl { public: virtual future<streamed_mutation_opt> operator()() override { return make_ready_future<streamed_mutation_opt>(); } virtual future<> fast_forward_to(const dht::partition_range&) override { return make_ready_future<>(); } }; mutation_reader make_empty_reader() { return make_mutation_reader<empty_reader>(); } class restricting_mutation_reader : public mutation_reader::impl { const restricted_mutation_reader_config& _config; unsigned _weight = 0; bool _waited = false; mutation_reader _base; public: restricting_mutation_reader(const restricted_mutation_reader_config& config, unsigned weight, mutation_reader&& base) : _config(config), _weight(weight), _base(std::move(base)) { if (_config.sem->waiters() >= _config.max_queue_length) { _config.raise_queue_overloaded_exception(); } } ~restricting_mutation_reader() { if (_waited) { _config.sem->signal(_weight); } } future<streamed_mutation_opt> operator()() override { // FIXME: we should defer freeing until the mutation is freed, perhaps, // rather than just returned if (_waited) { return _base(); } auto waited = _config.timeout.count() != 0 ? _config.sem->wait(_config.timeout, _weight) : _config.sem->wait(_weight); return waited.then([this] { _waited = true; return _base(); }); } virtual future<> fast_forward_to(const dht::partition_range& pr) override { return _base.fast_forward_to(pr); } }; mutation_reader make_restricted_reader(const restricted_mutation_reader_config& config, unsigned weight, mutation_reader&& base) { return make_mutation_reader<restricting_mutation_reader>(config, weight, std::move(base)); } class multi_range_mutation_reader : public mutation_reader::impl { public: using ranges_vector = dht::partition_range_vector; private: const ranges_vector& _ranges; ranges_vector::const_iterator _current_range; mutation_reader _reader; public: multi_range_mutation_reader(schema_ptr s, mutation_source source, const ranges_vector& ranges, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, streamed_mutation::forwarding fwd, mutation_reader::forwarding fwd_mr) : _ranges(ranges) , _current_range(_ranges.begin()) , _reader(source(s, *_current_range, slice, pc, trace_state, fwd, _ranges.size() > 1 ? mutation_reader::forwarding::yes : fwd_mr)) { } virtual future<streamed_mutation_opt> operator()() override { return repeat_until_value([this] { return _reader().then([this] (streamed_mutation_opt smopt) { if (smopt) { return make_ready_future<stdx::optional<streamed_mutation_opt>>(std::move(smopt)); } ++_current_range; if (_current_range == _ranges.end()) { return make_ready_future<stdx::optional<streamed_mutation_opt>>(streamed_mutation_opt()); } return _reader.fast_forward_to(*_current_range).then([] { return make_ready_future<stdx::optional<streamed_mutation_opt>>(); }); }); }); } virtual future<> fast_forward_to(const dht::partition_range& pr) override { // When end of pr is reached, this reader will increment _current_range // and notice that it now points to _ranges.end(). _current_range = std::prev(_ranges.end()); return _reader.fast_forward_to(pr); } }; mutation_reader make_multi_range_reader(schema_ptr s, mutation_source source, const dht::partition_range_vector& ranges, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, streamed_mutation::forwarding fwd, mutation_reader::forwarding fwd_mr) { return make_mutation_reader<multi_range_mutation_reader>(std::move(s), std::move(source), ranges, slice, pc, std::move(trace_state), fwd, fwd_mr); } snapshot_source make_empty_snapshot_source() { return snapshot_source([] { return make_empty_mutation_source(); }); } mutation_source make_empty_mutation_source() { return mutation_source([](schema_ptr s, const dht::partition_range& pr, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr tr, streamed_mutation::forwarding fwd) { return make_empty_reader(); }); } mutation_source make_combined_mutation_source(std::vector<mutation_source> addends) { return mutation_source([addends = std::move(addends)] (schema_ptr s, const dht::partition_range& pr, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr tr, streamed_mutation::forwarding fwd) { std::vector<mutation_reader> rd; rd.reserve(addends.size()); for (auto&& ms : addends) { rd.emplace_back(ms(s, pr, slice, pc, tr, fwd)); } return make_combined_reader(std::move(rd)); }); } <|endoftext|>
<commit_before>// Copyright Hugh Perkins 2016, 2017 // 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 <iostream> #include <fstream> #include <stdexcept> #include "llvm/IR/LLVMContext.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SourceMgr.h" #include "llvm/IRReader/IRReader.h" #include "llvm/IR/Module.h" void readSpirVText() { llvm::LLVMContext context; llvm::SMDiagnostic smDiagnostic; // std::string llFilename = "cl_kernel1.ll"; // std::unique_ptr<llvm::Module> M = parseIRFile(llFilename, smDiagnostic, context); std::string llFilename = "cl_kernel1.spt"; std::unique_ptr<llvm::Module> M = parseIRFile(llFilename, smDiagnostic, context); if(!M) { smDiagnostic.print("irtoopencl", llvm::errs()); throw std::runtime_error("failed to parse IR"); } } int main(int argc, char *argv[]) { readSpirVText(); return 0; } <commit_msg>got reading llmv from spirv working ok<commit_after>#include <iostream> #include <fstream> #include <stdexcept> #ifndef _SPIRV_SUPPORT_TEXT_FMT #define _SPIRV_SUPPORT_TEXT_FMT #endif #include "llvm/Support/SPIRV.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SourceMgr.h" #include "llvm/IRReader/IRReader.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" void readSpirVText() { // llvm::LLVMContext context; // llvm::SMDiagnostic smDiagnostic; // // std::string llFilename = "cl_kernel1.ll"; // // std::unique_ptr<llvm::Module> M = parseIRFile(llFilename, smDiagnostic, context); // std::string llFilename = "cl_kernel1.spt"; // std::unique_ptr<llvm::Module> M = parseIRFile(llFilename, smDiagnostic, context); // if(!M) { // smDiagnostic.print("irtoopencl", llvm::errs()); // throw std::runtime_error("failed to parse IR"); // } // from https://github.com/KhronosGroup/SPIRV-LLVM/blob/khronos/spirv-3.6.1/tools/llvm-spirv/llvm-spirv.cpp std::string spvFilename = "cl_kernel1.spv"; llvm::LLVMContext Context; std::ifstream IFS(spvFilename, std::ios::binary); llvm::Module *M; std::string Err; if (!llvm::ReadSPIRV(Context, IFS, M, Err)) { llvm::errs() << "Fails to load SPIRV as LLVM Module: " << Err << '\n'; return; } // DEBUG(dbgs() << "Converted LLVM module:\n" << *M); llvm::raw_string_ostream ErrorOS(Err); if (llvm::verifyModule(*M, &ErrorOS)){ llvm::errs() << "Fails to verify module: " << ErrorOS.str(); return; } for(auto it=M->begin(); it != M->end(); it++) { llvm::Function *fn = &*it; std::cout << fn->getName().str() << std::endl; for(auto it2=fn->begin(); it2 != fn->end(); it2++) { llvm::BasicBlock *block = &*it2; std::cout << "block " << block->getName().str() << std::endl; for(auto it3=block->begin(); it3 != block->end(); it3++) { llvm::Instruction *inst = &*it3; std::cout << "instruction " << inst->getOpcodeName() << std::endl; } } } } int main(int argc, char *argv[]) { readSpirVText(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2011, British Broadcasting Corporation * All Rights Reserved. * * Author: Philip de Nier * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the British Broadcasting Corporation 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define __STDC_FORMAT_MACROS #include <cstdio> #include <cstring> #include <cerrno> #include "AppUtils.h" #include <bmx/Utils.h> #include <bmx/BMXException.h> #include <bmx/Logging.h> using namespace std; using namespace bmx; typedef struct { const char *color_str; Color color; } ColorMap; typedef struct { const char *format_str; AVCIHeaderFormat format; } AVCIHeaderFormatInfo; static const ColorMap COLOR_MAP[] = { {"white", COLOR_WHITE}, {"red", COLOR_RED}, {"yellow", COLOR_YELLOW}, {"green", COLOR_GREEN}, {"cyan", COLOR_CYAN}, {"blue", COLOR_BLUE}, {"magenta", COLOR_MAGENTA}, {"black", COLOR_BLACK}, }; static const AVCIHeaderFormatInfo AVCI_HEADER_FORMAT_INFO[] = { {"AVC-Intra 100 1080i50", {AVCI100_1080I, {25, 1}}}, {"AVC-Intra 100 1080i59.94", {AVCI100_1080I, {30000, 1001}}}, {"AVC-Intra 100 1080p25", {AVCI100_1080P, {25, 1}}}, {"AVC-Intra 100 1080p29.97", {AVCI100_1080P, {30000, 1001}}}, {"AVC-Intra 100 720p25", {AVCI100_720P, {25, 1}}}, {"AVC-Intra 100 720p50", {AVCI100_720P, {50, 1}}}, {"AVC-Intra 100 720p29.97", {AVCI100_720P, {30000, 1001}}}, {"AVC-Intra 100 720p59.94", {AVCI100_720P, {60000, 1001}}}, {"AVC-Intra 50 1080p50", {AVCI50_1080I, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080I, {30000, 1001}}}, {"AVC-Intra 50 1080p25", {AVCI50_1080P, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080P, {30000, 1001}}}, {"AVC-Intra 50 720p25", {AVCI50_720P, {25, 1}}}, {"AVC-Intra 50 720p50", {AVCI50_720P, {50, 1}}}, {"AVC-Intra 50 720p29.97", {AVCI50_720P, {30000, 1001}}}, {"AVC-Intra 50 720p59.94", {AVCI50_720P, {60000, 1001}}}, }; size_t bmx::get_num_avci_header_formats() { return ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); } const char* bmx::get_avci_header_format_string(size_t index) { BMX_ASSERT(index < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)); return AVCI_HEADER_FORMAT_INFO[index].format_str; } bool bmx::parse_timecode(const char *tc_str, Rational frame_rate, Timecode *timecode) { int hour, min, sec, frame; char c; if (sscanf(tc_str, "%d:%d:%d%c%d", &hour, &min, &sec, &c, &frame) != 5) return false; timecode->Init(frame_rate, (c != ':'), hour, min, sec, frame); return true; } bool bmx::parse_position(const char *position_str, Timecode start_timecode, Rational frame_rate, int64_t *position) { if (position_str[0] == 'o') { // ignore drop frame indictor for offset Rational nondrop_rate; if (frame_rate.denominator == 1001) { nondrop_rate.numerator = get_rounded_tc_base(frame_rate); nondrop_rate.denominator = 1; } else { nondrop_rate = frame_rate; } Timecode timecode; if (!parse_timecode(position_str + 1, nondrop_rate, &timecode)) return false; *position = timecode.GetOffset(); return true; } Timecode timecode; if (!parse_timecode(position_str, frame_rate, &timecode)) return false; *position = timecode.GetOffset() - start_timecode.GetOffset(); return true; } bool bmx::parse_partition_interval(const char *partition_interval_str, Rational frame_rate, int64_t *partition_interval) { bool in_seconds = (strchr(partition_interval_str, 's') != 0); if (sscanf(partition_interval_str, "%"PRId64, partition_interval) != 1) return false; if (in_seconds) *partition_interval = (*partition_interval) * frame_rate.numerator / frame_rate.denominator; return true; } bool bmx::parse_bool(const char *bool_str, bool *value) { if (strcmp(bool_str, "true") == 0) *value = true; else if (strcmp(bool_str, "false") == 0) *value = false; else return false; return true; } bool bmx::parse_color(const char *color_str, Color *color) { size_t i; for (i = 0; i < ARRAY_SIZE(COLOR_MAP); i++) { if (strcmp(COLOR_MAP[i].color_str, color_str) == 0) { *color = COLOR_MAP[i].color; return true; } } return false; } bool bmx::parse_avci_header(const char *format_str, const char *filename, const char *offset_str, vector<AVCIHeaderInput> *avci_header_inputs) { AVCIHeaderInput input; if (strcmp(format_str, "all") == 0) { size_t i; for (i = 0; i < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); i++) input.formats.push_back(AVCI_HEADER_FORMAT_INFO[i].format); } else { size_t index; const char *format_str_ptr = format_str; while (format_str_ptr) { if (sscanf(format_str_ptr, "%"PRIszt, &index) != 1 || index > ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)) return false; input.formats.push_back(AVCI_HEADER_FORMAT_INFO[index].format); format_str_ptr = strchr(format_str_ptr, ','); if (format_str_ptr) format_str_ptr++; } } input.filename = filename; if (sscanf(offset_str, "%"PRId64, &input.offset) != 1) return false; avci_header_inputs->push_back(input); return true; } string bmx::create_mxf_track_filename(const char *prefix, uint32_t track_number, bool is_picture) { char buffer[16]; sprintf(buffer, "_%s%u.mxf", (is_picture ? "v" : "a"), track_number); string filename = prefix; return filename.append(buffer); } bool bmx::have_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs) { size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } return i < avci_header_inputs.size(); } bool bmx::read_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs, unsigned char *buffer, size_t buffer_size) { BMX_ASSERT(buffer_size >= 512); size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } if (i >= avci_header_inputs.size()) return false; FILE *file = fopen(avci_header_inputs[i].filename, "rb"); if (!file) { log_error("Failed to open AVC-Intra header data input file '%s': %s\n", avci_header_inputs[i].filename, strerror(errno)); return false; } int64_t offset = avci_header_inputs[i].offset + j * 512; if (fseek(file, offset, SEEK_SET) != 0) { log_error("Failed to seek to offset %"PRId64" in AVC-Intra header data input file '%s': %s\n", offset, avci_header_inputs[i].filename, strerror(errno)); fclose(file); return false; } if (fread(buffer, 512, 1, file) != 1) { log_error("Failed to read 512 bytes from AVC-Intra header data input file '%s' at offset %"PRId64": %s\n", avci_header_inputs[i].filename, offset, ferror(file) ? "read error" : "end of file"); fclose(file); return false; } fclose(file); return true; } void bmx::init_progress(float *next_update) { *next_update = -1.0; } void bmx::print_progress(int64_t count, int64_t duration, float *next_update) { if (duration == 0) return; if (count == 0 && (!next_update || *next_update <= 0.0)) { printf(" 0.0%%\r"); fflush(stdout); *next_update = 1.0; } else { float progress = count / (float)duration * 100; if (!next_update || progress >= *next_update) { printf(" %.1f%%\r", progress); fflush(stdout); if (next_update) { *next_update += 0.1; if (*next_update < progress) *next_update = progress + 0.1; } } } } <commit_msg>apps: set first progress update to 0.1%, not 1%<commit_after>/* * Copyright (C) 2011, British Broadcasting Corporation * All Rights Reserved. * * Author: Philip de Nier * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the British Broadcasting Corporation 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define __STDC_FORMAT_MACROS #include <cstdio> #include <cstring> #include <cerrno> #include "AppUtils.h" #include <bmx/Utils.h> #include <bmx/BMXException.h> #include <bmx/Logging.h> using namespace std; using namespace bmx; typedef struct { const char *color_str; Color color; } ColorMap; typedef struct { const char *format_str; AVCIHeaderFormat format; } AVCIHeaderFormatInfo; static const ColorMap COLOR_MAP[] = { {"white", COLOR_WHITE}, {"red", COLOR_RED}, {"yellow", COLOR_YELLOW}, {"green", COLOR_GREEN}, {"cyan", COLOR_CYAN}, {"blue", COLOR_BLUE}, {"magenta", COLOR_MAGENTA}, {"black", COLOR_BLACK}, }; static const AVCIHeaderFormatInfo AVCI_HEADER_FORMAT_INFO[] = { {"AVC-Intra 100 1080i50", {AVCI100_1080I, {25, 1}}}, {"AVC-Intra 100 1080i59.94", {AVCI100_1080I, {30000, 1001}}}, {"AVC-Intra 100 1080p25", {AVCI100_1080P, {25, 1}}}, {"AVC-Intra 100 1080p29.97", {AVCI100_1080P, {30000, 1001}}}, {"AVC-Intra 100 720p25", {AVCI100_720P, {25, 1}}}, {"AVC-Intra 100 720p50", {AVCI100_720P, {50, 1}}}, {"AVC-Intra 100 720p29.97", {AVCI100_720P, {30000, 1001}}}, {"AVC-Intra 100 720p59.94", {AVCI100_720P, {60000, 1001}}}, {"AVC-Intra 50 1080p50", {AVCI50_1080I, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080I, {30000, 1001}}}, {"AVC-Intra 50 1080p25", {AVCI50_1080P, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080P, {30000, 1001}}}, {"AVC-Intra 50 720p25", {AVCI50_720P, {25, 1}}}, {"AVC-Intra 50 720p50", {AVCI50_720P, {50, 1}}}, {"AVC-Intra 50 720p29.97", {AVCI50_720P, {30000, 1001}}}, {"AVC-Intra 50 720p59.94", {AVCI50_720P, {60000, 1001}}}, }; size_t bmx::get_num_avci_header_formats() { return ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); } const char* bmx::get_avci_header_format_string(size_t index) { BMX_ASSERT(index < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)); return AVCI_HEADER_FORMAT_INFO[index].format_str; } bool bmx::parse_timecode(const char *tc_str, Rational frame_rate, Timecode *timecode) { int hour, min, sec, frame; char c; if (sscanf(tc_str, "%d:%d:%d%c%d", &hour, &min, &sec, &c, &frame) != 5) return false; timecode->Init(frame_rate, (c != ':'), hour, min, sec, frame); return true; } bool bmx::parse_position(const char *position_str, Timecode start_timecode, Rational frame_rate, int64_t *position) { if (position_str[0] == 'o') { // ignore drop frame indictor for offset Rational nondrop_rate; if (frame_rate.denominator == 1001) { nondrop_rate.numerator = get_rounded_tc_base(frame_rate); nondrop_rate.denominator = 1; } else { nondrop_rate = frame_rate; } Timecode timecode; if (!parse_timecode(position_str + 1, nondrop_rate, &timecode)) return false; *position = timecode.GetOffset(); return true; } Timecode timecode; if (!parse_timecode(position_str, frame_rate, &timecode)) return false; *position = timecode.GetOffset() - start_timecode.GetOffset(); return true; } bool bmx::parse_partition_interval(const char *partition_interval_str, Rational frame_rate, int64_t *partition_interval) { bool in_seconds = (strchr(partition_interval_str, 's') != 0); if (sscanf(partition_interval_str, "%"PRId64, partition_interval) != 1) return false; if (in_seconds) *partition_interval = (*partition_interval) * frame_rate.numerator / frame_rate.denominator; return true; } bool bmx::parse_bool(const char *bool_str, bool *value) { if (strcmp(bool_str, "true") == 0) *value = true; else if (strcmp(bool_str, "false") == 0) *value = false; else return false; return true; } bool bmx::parse_color(const char *color_str, Color *color) { size_t i; for (i = 0; i < ARRAY_SIZE(COLOR_MAP); i++) { if (strcmp(COLOR_MAP[i].color_str, color_str) == 0) { *color = COLOR_MAP[i].color; return true; } } return false; } bool bmx::parse_avci_header(const char *format_str, const char *filename, const char *offset_str, vector<AVCIHeaderInput> *avci_header_inputs) { AVCIHeaderInput input; if (strcmp(format_str, "all") == 0) { size_t i; for (i = 0; i < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); i++) input.formats.push_back(AVCI_HEADER_FORMAT_INFO[i].format); } else { size_t index; const char *format_str_ptr = format_str; while (format_str_ptr) { if (sscanf(format_str_ptr, "%"PRIszt, &index) != 1 || index > ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)) return false; input.formats.push_back(AVCI_HEADER_FORMAT_INFO[index].format); format_str_ptr = strchr(format_str_ptr, ','); if (format_str_ptr) format_str_ptr++; } } input.filename = filename; if (sscanf(offset_str, "%"PRId64, &input.offset) != 1) return false; avci_header_inputs->push_back(input); return true; } string bmx::create_mxf_track_filename(const char *prefix, uint32_t track_number, bool is_picture) { char buffer[16]; sprintf(buffer, "_%s%u.mxf", (is_picture ? "v" : "a"), track_number); string filename = prefix; return filename.append(buffer); } bool bmx::have_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs) { size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } return i < avci_header_inputs.size(); } bool bmx::read_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs, unsigned char *buffer, size_t buffer_size) { BMX_ASSERT(buffer_size >= 512); size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } if (i >= avci_header_inputs.size()) return false; FILE *file = fopen(avci_header_inputs[i].filename, "rb"); if (!file) { log_error("Failed to open AVC-Intra header data input file '%s': %s\n", avci_header_inputs[i].filename, strerror(errno)); return false; } int64_t offset = avci_header_inputs[i].offset + j * 512; if (fseek(file, offset, SEEK_SET) != 0) { log_error("Failed to seek to offset %"PRId64" in AVC-Intra header data input file '%s': %s\n", offset, avci_header_inputs[i].filename, strerror(errno)); fclose(file); return false; } if (fread(buffer, 512, 1, file) != 1) { log_error("Failed to read 512 bytes from AVC-Intra header data input file '%s' at offset %"PRId64": %s\n", avci_header_inputs[i].filename, offset, ferror(file) ? "read error" : "end of file"); fclose(file); return false; } fclose(file); return true; } void bmx::init_progress(float *next_update) { *next_update = -1.0; } void bmx::print_progress(int64_t count, int64_t duration, float *next_update) { if (duration == 0) return; if (count == 0 && (!next_update || *next_update <= 0.0)) { printf(" 0.0%%\r"); fflush(stdout); *next_update = 0.1; } else { float progress = count / (float)duration * 100; if (!next_update || progress >= *next_update) { printf(" %.1f%%\r", progress); fflush(stdout); if (next_update) { *next_update += 0.1; if (*next_update < progress) *next_update = progress + 0.1; } } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2011, British Broadcasting Corporation * All Rights Reserved. * * Author: Philip de Nier * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the British Broadcasting Corporation 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define __STDC_FORMAT_MACROS #include <cstdio> #include <cstring> #include <cerrno> #include "AppUtils.h" #include <bmx/Utils.h> #include <bmx/BMXException.h> #include <bmx/Logging.h> using namespace std; using namespace bmx; typedef struct { const char *color_str; Color color; } ColorMap; typedef struct { const char *format_str; AVCIHeaderFormat format; } AVCIHeaderFormatInfo; static const ColorMap COLOR_MAP[] = { {"white", COLOR_WHITE}, {"red", COLOR_RED}, {"yellow", COLOR_YELLOW}, {"green", COLOR_GREEN}, {"cyan", COLOR_CYAN}, {"blue", COLOR_BLUE}, {"magenta", COLOR_MAGENTA}, {"black", COLOR_BLACK}, }; static const AVCIHeaderFormatInfo AVCI_HEADER_FORMAT_INFO[] = { {"AVC-Intra 100 1080i50", {AVCI100_1080I, {25, 1}}}, {"AVC-Intra 100 1080i59.94", {AVCI100_1080I, {30000, 1001}}}, {"AVC-Intra 100 1080p25", {AVCI100_1080P, {25, 1}}}, {"AVC-Intra 100 1080p29.97", {AVCI100_1080P, {30000, 1001}}}, {"AVC-Intra 100 720p25", {AVCI100_720P, {25, 1}}}, {"AVC-Intra 100 720p50", {AVCI100_720P, {50, 1}}}, {"AVC-Intra 100 720p29.97", {AVCI100_720P, {30000, 1001}}}, {"AVC-Intra 100 720p59.94", {AVCI100_720P, {60000, 1001}}}, {"AVC-Intra 50 1080p50", {AVCI50_1080I, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080I, {30000, 1001}}}, {"AVC-Intra 50 1080p25", {AVCI50_1080P, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080P, {30000, 1001}}}, {"AVC-Intra 50 720p25", {AVCI50_720P, {25, 1}}}, {"AVC-Intra 50 720p50", {AVCI50_720P, {50, 1}}}, {"AVC-Intra 50 720p29.97", {AVCI50_720P, {30000, 1001}}}, {"AVC-Intra 50 720p59.94", {AVCI50_720P, {60000, 1001}}}, }; size_t bmx::get_num_avci_header_formats() { return ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); } const char* bmx::get_avci_header_format_string(size_t index) { BMX_ASSERT(index < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)); return AVCI_HEADER_FORMAT_INFO[index].format_str; } bool bmx::parse_timecode(const char *tc_str, Rational frame_rate, Timecode *timecode) { int hour, min, sec, frame; char c; if (sscanf(tc_str, "%d:%d:%d%c%d", &hour, &min, &sec, &c, &frame) != 5) return false; timecode->Init(frame_rate, (c != ':'), hour, min, sec, frame); return true; } bool bmx::parse_position(const char *position_str, Timecode start_timecode, Rational frame_rate, int64_t *position) { if (position_str[0] == 'o') { // ignore drop frame indictor for offset Rational nondrop_rate; if (frame_rate.denominator == 1001) { nondrop_rate.numerator = get_rounded_tc_base(frame_rate); nondrop_rate.denominator = 1; } else { nondrop_rate = frame_rate; } Timecode timecode; if (!parse_timecode(position_str + 1, nondrop_rate, &timecode)) return false; *position = timecode.GetOffset(); return true; } Timecode timecode; if (!parse_timecode(position_str, frame_rate, &timecode)) return false; *position = timecode.GetOffset() - start_timecode.GetOffset(); return true; } bool bmx::parse_partition_interval(const char *partition_interval_str, Rational frame_rate, int64_t *partition_interval) { bool in_seconds = (strchr(partition_interval_str, 's') != 0); if (sscanf(partition_interval_str, "%"PRId64, partition_interval) != 1) return false; if (in_seconds) *partition_interval = (*partition_interval) * frame_rate.numerator / frame_rate.denominator; return true; } bool bmx::parse_bool(const char *bool_str, bool *value) { if (strcmp(bool_str, "true") == 0) *value = true; else if (strcmp(bool_str, "false") == 0) *value = false; else return false; return true; } bool bmx::parse_color(const char *color_str, Color *color) { size_t i; for (i = 0; i < ARRAY_SIZE(COLOR_MAP); i++) { if (strcmp(COLOR_MAP[i].color_str, color_str) == 0) { *color = COLOR_MAP[i].color; return true; } } return false; } bool bmx::parse_avci_header(const char *format_str, const char *filename, const char *offset_str, vector<AVCIHeaderInput> *avci_header_inputs) { AVCIHeaderInput input; if (strcmp(format_str, "all") == 0) { size_t i; for (i = 0; i < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); i++) input.formats.push_back(AVCI_HEADER_FORMAT_INFO[i].format); } else { size_t index; const char *format_str_ptr = format_str; while (format_str_ptr) { if (sscanf(format_str_ptr, "%"PRIszt, &index) != 1 || index > ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)) return false; input.formats.push_back(AVCI_HEADER_FORMAT_INFO[index].format); format_str_ptr = strchr(format_str_ptr, ','); if (format_str_ptr) format_str_ptr++; } } input.filename = filename; if (sscanf(offset_str, "%"PRId64, &input.offset) != 1) return false; avci_header_inputs->push_back(input); return true; } string bmx::create_mxf_track_filename(const char *prefix, uint32_t track_number, bool is_picture) { char buffer[16]; sprintf(buffer, "_%s%u.mxf", (is_picture ? "v" : "a"), track_number); string filename = prefix; return filename.append(buffer); } bool bmx::have_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs) { size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } return i < avci_header_inputs.size(); } bool bmx::read_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs, unsigned char *buffer, size_t buffer_size) { BMX_ASSERT(buffer_size >= 512); size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } if (i >= avci_header_inputs.size()) return false; FILE *file = fopen(avci_header_inputs[i].filename, "rb"); if (!file) { log_error("Failed to open AVC-Intra header data input file '%s': %s\n", avci_header_inputs[i].filename, strerror(errno)); return false; } int64_t offset = avci_header_inputs[i].offset + j * 512; if (fseek(file, offset, SEEK_SET) != 0) { log_error("Failed to seek to offset %"PRId64" in AVC-Intra header data input file '%s': %s\n", offset, avci_header_inputs[i].filename, strerror(errno)); fclose(file); return false; } if (fread(buffer, 512, 1, file) != 1) { log_error("Failed to read 512 bytes from AVC-Intra header data input file '%s' at offset %"PRId64": %s\n", avci_header_inputs[i].filename, offset, ferror(file) ? "read error" : "end of file"); fclose(file); return false; } fclose(file); return true; } void bmx::init_progress(float *next_update) { *next_update = -1.0; } void bmx::print_progress(int64_t count, int64_t duration, float *next_update) { if (duration == 0) return; if (count == 0 && (!next_update || *next_update <= 0.0)) { printf(" 0.0%%\r"); fflush(stdout); if (next_update) *next_update = 0.1f; } else { float progress = count / (float)duration * 100; if (!next_update || progress >= *next_update) { printf(" %.1f%%\r", progress); fflush(stdout); if (next_update) { *next_update += 0.1f; if (*next_update < progress) *next_update = progress + 0.1f; } } } } <commit_msg>app utils: use 64-bit fseek when reading avic header<commit_after>/* * Copyright (C) 2011, British Broadcasting Corporation * All Rights Reserved. * * Author: Philip de Nier * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the British Broadcasting Corporation 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define __STDC_FORMAT_MACROS #include <cstdio> #include <cstring> #include <cerrno> #include "AppUtils.h" #include <bmx/Utils.h> #include <bmx/BMXException.h> #include <bmx/Logging.h> using namespace std; using namespace bmx; typedef struct { const char *color_str; Color color; } ColorMap; typedef struct { const char *format_str; AVCIHeaderFormat format; } AVCIHeaderFormatInfo; static const ColorMap COLOR_MAP[] = { {"white", COLOR_WHITE}, {"red", COLOR_RED}, {"yellow", COLOR_YELLOW}, {"green", COLOR_GREEN}, {"cyan", COLOR_CYAN}, {"blue", COLOR_BLUE}, {"magenta", COLOR_MAGENTA}, {"black", COLOR_BLACK}, }; static const AVCIHeaderFormatInfo AVCI_HEADER_FORMAT_INFO[] = { {"AVC-Intra 100 1080i50", {AVCI100_1080I, {25, 1}}}, {"AVC-Intra 100 1080i59.94", {AVCI100_1080I, {30000, 1001}}}, {"AVC-Intra 100 1080p25", {AVCI100_1080P, {25, 1}}}, {"AVC-Intra 100 1080p29.97", {AVCI100_1080P, {30000, 1001}}}, {"AVC-Intra 100 720p25", {AVCI100_720P, {25, 1}}}, {"AVC-Intra 100 720p50", {AVCI100_720P, {50, 1}}}, {"AVC-Intra 100 720p29.97", {AVCI100_720P, {30000, 1001}}}, {"AVC-Intra 100 720p59.94", {AVCI100_720P, {60000, 1001}}}, {"AVC-Intra 50 1080p50", {AVCI50_1080I, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080I, {30000, 1001}}}, {"AVC-Intra 50 1080p25", {AVCI50_1080P, {25, 1}}}, {"AVC-Intra 50 1080p29.97", {AVCI50_1080P, {30000, 1001}}}, {"AVC-Intra 50 720p25", {AVCI50_720P, {25, 1}}}, {"AVC-Intra 50 720p50", {AVCI50_720P, {50, 1}}}, {"AVC-Intra 50 720p29.97", {AVCI50_720P, {30000, 1001}}}, {"AVC-Intra 50 720p59.94", {AVCI50_720P, {60000, 1001}}}, }; size_t bmx::get_num_avci_header_formats() { return ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); } const char* bmx::get_avci_header_format_string(size_t index) { BMX_ASSERT(index < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)); return AVCI_HEADER_FORMAT_INFO[index].format_str; } bool bmx::parse_timecode(const char *tc_str, Rational frame_rate, Timecode *timecode) { int hour, min, sec, frame; char c; if (sscanf(tc_str, "%d:%d:%d%c%d", &hour, &min, &sec, &c, &frame) != 5) return false; timecode->Init(frame_rate, (c != ':'), hour, min, sec, frame); return true; } bool bmx::parse_position(const char *position_str, Timecode start_timecode, Rational frame_rate, int64_t *position) { if (position_str[0] == 'o') { // ignore drop frame indictor for offset Rational nondrop_rate; if (frame_rate.denominator == 1001) { nondrop_rate.numerator = get_rounded_tc_base(frame_rate); nondrop_rate.denominator = 1; } else { nondrop_rate = frame_rate; } Timecode timecode; if (!parse_timecode(position_str + 1, nondrop_rate, &timecode)) return false; *position = timecode.GetOffset(); return true; } Timecode timecode; if (!parse_timecode(position_str, frame_rate, &timecode)) return false; *position = timecode.GetOffset() - start_timecode.GetOffset(); return true; } bool bmx::parse_partition_interval(const char *partition_interval_str, Rational frame_rate, int64_t *partition_interval) { bool in_seconds = (strchr(partition_interval_str, 's') != 0); if (sscanf(partition_interval_str, "%"PRId64, partition_interval) != 1) return false; if (in_seconds) *partition_interval = (*partition_interval) * frame_rate.numerator / frame_rate.denominator; return true; } bool bmx::parse_bool(const char *bool_str, bool *value) { if (strcmp(bool_str, "true") == 0) *value = true; else if (strcmp(bool_str, "false") == 0) *value = false; else return false; return true; } bool bmx::parse_color(const char *color_str, Color *color) { size_t i; for (i = 0; i < ARRAY_SIZE(COLOR_MAP); i++) { if (strcmp(COLOR_MAP[i].color_str, color_str) == 0) { *color = COLOR_MAP[i].color; return true; } } return false; } bool bmx::parse_avci_header(const char *format_str, const char *filename, const char *offset_str, vector<AVCIHeaderInput> *avci_header_inputs) { AVCIHeaderInput input; if (strcmp(format_str, "all") == 0) { size_t i; for (i = 0; i < ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO); i++) input.formats.push_back(AVCI_HEADER_FORMAT_INFO[i].format); } else { size_t index; const char *format_str_ptr = format_str; while (format_str_ptr) { if (sscanf(format_str_ptr, "%"PRIszt, &index) != 1 || index > ARRAY_SIZE(AVCI_HEADER_FORMAT_INFO)) return false; input.formats.push_back(AVCI_HEADER_FORMAT_INFO[index].format); format_str_ptr = strchr(format_str_ptr, ','); if (format_str_ptr) format_str_ptr++; } } input.filename = filename; if (sscanf(offset_str, "%"PRId64, &input.offset) != 1) return false; avci_header_inputs->push_back(input); return true; } string bmx::create_mxf_track_filename(const char *prefix, uint32_t track_number, bool is_picture) { char buffer[16]; sprintf(buffer, "_%s%u.mxf", (is_picture ? "v" : "a"), track_number); string filename = prefix; return filename.append(buffer); } bool bmx::have_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs) { size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } return i < avci_header_inputs.size(); } bool bmx::read_avci_header_data(EssenceType essence_type, Rational sample_rate, vector<AVCIHeaderInput> &avci_header_inputs, unsigned char *buffer, size_t buffer_size) { BMX_ASSERT(buffer_size >= 512); size_t i; size_t j; for (i = 0; i < avci_header_inputs.size(); i++) { for (j = 0; j < avci_header_inputs[i].formats.size(); j++) { if (avci_header_inputs[i].formats[j].essence_type == essence_type && avci_header_inputs[i].formats[j].sample_rate == sample_rate) { break; } } if (j < avci_header_inputs[i].formats.size()) break; } if (i >= avci_header_inputs.size()) return false; FILE *file = fopen(avci_header_inputs[i].filename, "rb"); if (!file) { log_error("Failed to open AVC-Intra header data input file '%s': %s\n", avci_header_inputs[i].filename, strerror(errno)); return false; } int64_t offset = avci_header_inputs[i].offset + j * 512; #if defined(_MSC_VER) if (_fseeki64(file, offset, SEEK_SET) != 0) { #else if (fseeko(file, offset, SEEK_SET) != 0) { #endif log_error("Failed to seek to offset %"PRId64" in AVC-Intra header data input file '%s': %s\n", offset, avci_header_inputs[i].filename, strerror(errno)); fclose(file); return false; } if (fread(buffer, 512, 1, file) != 1) { log_error("Failed to read 512 bytes from AVC-Intra header data input file '%s' at offset %"PRId64": %s\n", avci_header_inputs[i].filename, offset, ferror(file) ? "read error" : "end of file"); fclose(file); return false; } fclose(file); return true; } void bmx::init_progress(float *next_update) { *next_update = -1.0; } void bmx::print_progress(int64_t count, int64_t duration, float *next_update) { if (duration == 0) return; if (count == 0 && (!next_update || *next_update <= 0.0)) { printf(" 0.0%%\r"); fflush(stdout); if (next_update) *next_update = 0.1f; } else { float progress = count / (float)duration * 100; if (!next_update || progress >= *next_update) { printf(" %.1f%%\r", progress); fflush(stdout); if (next_update) { *next_update += 0.1f; if (*next_update < progress) *next_update = progress + 0.1f; } } } } <|endoftext|>
<commit_before>#include "nanocv/string.h" #include "nanocv/measure.hpp" #include "nanocv/math/gauss.hpp" #include "nanocv/vision/image.h" #include "nanocv/math/random.hpp" #include "nanocv/math/numeric.hpp" #include "nanocv/tensor/random.hpp" #include "nanocv/vision/gradient.hpp" #include "nanocv/vision/convolve.hpp" #include "nanocv/tensor/transform.hpp" #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace { using namespace ncv; /// \todo move these to library (once the warping algorithm works OK) enum class field_type { translation, rotation, random, }; struct field_params { explicit field_params( field_type ftype = field_type::random, scalar_t noise = 0.1, scalar_t sigma = 0.1) : m_ftype(ftype), m_noise(noise), m_sigma(sigma) { } field_type m_ftype; scalar_t m_noise; scalar_t m_sigma; }; image_t image_field(const matrix_t& fieldx, const matrix_t& fieldy) { assert(fieldx.rows() == fieldy.rows()); assert(fieldx.cols() == fieldy.cols()); rgba_matrix_t rgba(fieldx.rows(), fieldx.cols()); tensor::transform(fieldx, fieldy, rgba, [] (const scalar_t fx, const scalar_t fy) { const auto red = math::clamp(255.0 * 0.5 * (fx + 1.0), 0.0, 255.0); const auto blue = math::clamp(255.0 * 0.5 * (fy + 1.0), 0.0, 255.0); return color::make_rgba( math::cast<rgba_t>(red), 0, math::cast<rgba_t>(blue)); }); image_t image; image.load_rgba(rgba); return image; } void smooth_field(matrix_t& field, const scalar_t sigma) { const gauss_kernel_t<scalar_t> gauss(sigma); ncv::convolve(gauss, field); } std::tuple<matrix_t, matrix_t> make_random_fields( const size_t rows, const size_t cols, const scalar_t noise, const scalar_t sigma) { matrix_t fieldx(rows, cols), fieldy(rows, cols); tensor::set_random(fieldx, random_t<scalar_t>(-noise, +noise)); tensor::set_random(fieldy, random_t<scalar_t>(-noise, +noise)); smooth_field(fieldx, sigma); smooth_field(fieldy, sigma); return std::make_tuple(fieldx, fieldy); } std::tuple<matrix_t, matrix_t> make_translation_fields( const size_t rows, const size_t cols, const scalar_t delta, const scalar_t noise, const scalar_t sigma) { matrix_t fieldx(rows, cols), fieldy(rows, cols); tensor::set_random(fieldx, random_t<scalar_t>(delta - noise, delta + noise)); tensor::set_random(fieldy, random_t<scalar_t>(delta - noise, delta + noise)); smooth_field(fieldx, sigma); smooth_field(fieldy, sigma); return std::make_tuple(fieldx, fieldy); } std::tuple<matrix_t, matrix_t> make_rotation_fields( const size_t rows, const size_t cols, const scalar_t theta, const scalar_t noise, const scalar_t sigma) { matrix_t fieldx(rows, cols), fieldy(rows, cols); const scalar_t cx = 0.5 * cols; const scalar_t cy = 0.5 * rows; const scalar_t id = 1.0 / (math::square(cx) + math::square(cy)); random_t<scalar_t> rng(-noise, +noise); for (size_t r = 0; r < rows; r ++) { for (size_t c = 0; c < cols; c ++) { const auto dist = math::square(scalar_t(r) - cy) + math::square(scalar_t(c) - cx); fieldx(r, c) = id * dist * std::cos(theta) + rng(); fieldy(r, c) = id * dist * std::sin(theta) + rng(); } } smooth_field(fieldx, sigma); smooth_field(fieldy, sigma); return std::make_tuple(fieldx, fieldy); } template < typename tmatrixio, typename tmatrixf, typename tmatrixt > void warp_by_field(tmatrixio&& x, const scalar_t alphax, const tmatrixf& fieldx, const tmatrixt& gradx, const scalar_t alphay, const tmatrixf& fieldy, const tmatrixt& grady, const scalar_t beta) { x.array() += alphax * fieldx.array() * gradx.array() + alphay * fieldy.array() * grady.array() + beta * (gradx.array().square() + grady.array().square()).sqrt(); } image_t warp(const image_t& iimage, const field_params& fparams, image_t* fimage = nullptr) { tensor_t patch = ncv::color::to_rgba_tensor(iimage.rgba()); // x gradient (directional gradient) tensor_t patchgx(4, patch.rows(), patch.cols()); ncv::gradientx(patch.matrix(0), patchgx.matrix(0)); ncv::gradientx(patch.matrix(1), patchgx.matrix(1)); ncv::gradientx(patch.matrix(2), patchgx.matrix(2)); ncv::gradientx(patch.matrix(3), patchgx.matrix(3)); // y gradient (directional gradient) tensor_t patchgy(4, patch.rows(), patch.cols()); ncv::gradienty(patch.matrix(0), patchgy.matrix(0)); ncv::gradienty(patch.matrix(1), patchgy.matrix(1)); ncv::gradienty(patch.matrix(2), patchgy.matrix(2)); ncv::gradienty(patch.matrix(3), patchgy.matrix(3)); // generate random fields const scalar_t pi = std::atan2(0.0, -0.0); random_t<scalar_t> rng_theta(-pi / 8.0, +pi / 8.0); random_t<scalar_t> rng_delta(-1.0, +1.0); matrix_t fieldx, fieldy; switch (fparams.m_ftype) { case field_type::translation: std::tie(fieldx, fieldy) = make_translation_fields(patch.rows(), patch.cols(), rng_delta(), fparams.m_noise, fparams.m_sigma); break; case field_type::rotation: std::tie(fieldx, fieldy) = make_rotation_fields(patch.rows(), patch.cols(), rng_theta(), fparams.m_noise, fparams.m_sigma); break; case field_type::random: default: std::tie(fieldx, fieldy) = make_random_fields(patch.rows(), patch.cols(), fparams.m_noise, fparams.m_sigma); break; } // visualize the fields (if requested) if (fimage) { *fimage = image_field(fieldx, fieldy); } // warp random_t<scalar_t> rng_alphax(-1.0, +1.0); random_t<scalar_t> rng_alphay(-1.0, +1.0); random_t<scalar_t> rng_beta (-1.0, +1.0); const scalar_t alphax = rng_alphax(); const scalar_t alphay = rng_alphay(); const scalar_t beta = rng_beta(); log_info() << "patch(0) = [" << patch.matrix(0).minCoeff() << ", " << patch.matrix(0).maxCoeff() << "]"; log_info() << "patch(1) = [" << patch.matrix(1).minCoeff() << ", " << patch.matrix(1).maxCoeff() << "]"; log_info() << "patch(2) = [" << patch.matrix(2).minCoeff() << ", " << patch.matrix(2).maxCoeff() << "]"; log_info() << "patch(3) = [" << patch.matrix(3).minCoeff() << ", " << patch.matrix(3).maxCoeff() << "]"; warp_by_field(patch.matrix(0), alphax, fieldx, patchgx.matrix(0), alphay, fieldy, patchgy.matrix(0), beta); warp_by_field(patch.matrix(1), alphax, fieldx, patchgx.matrix(1), alphay, fieldy, patchgy.matrix(1), beta); warp_by_field(patch.matrix(2), alphax, fieldx, patchgx.matrix(2), alphay, fieldy, patchgy.matrix(2), beta); warp_by_field(patch.matrix(3), alphax, fieldx, patchgx.matrix(3), alphay, fieldy, patchgy.matrix(3), beta); log_info() << "*patch(0) = [" << patch.matrix(0).minCoeff() << ", " << patch.matrix(0).maxCoeff() << "]"; log_info() << "*patch(1) = [" << patch.matrix(1).minCoeff() << ", " << patch.matrix(1).maxCoeff() << "]"; log_info() << "*patch(2) = [" << patch.matrix(2).minCoeff() << ", " << patch.matrix(2).maxCoeff() << "]"; log_info() << "*patch(3) = [" << patch.matrix(3).minCoeff() << ", " << patch.matrix(3).maxCoeff() << "]"; // OK image_t oimage; oimage.load_rgba(color::from_rgba_tensor(patch)); return oimage; } } int main(int argc, char *argv[]) { using namespace ncv; // parse the command line boost::program_options::options_description po_desc("", 160); po_desc.add_options()("help,h", "randomly warp the input image"); po_desc.add_options()("input,i", boost::program_options::value<ncv::string_t>(), "input image path"); po_desc.add_options()("count,c", boost::program_options::value<ncv::size_t>()->default_value(32), "number of random warpings to generate"); po_desc.add_options()("translation", "use translation fields"); po_desc.add_options()("rotation", "use rotation fields"); po_desc.add_options()("random", "use random fields"); po_desc.add_options()("output,o", boost::program_options::value<ncv::string_t>(), "output (warped) image path"); boost::program_options::variables_map po_vm; boost::program_options::store( boost::program_options::command_line_parser(argc, argv).options(po_desc).run(), po_vm); boost::program_options::notify(po_vm); // check arguments and options if ( po_vm.empty() || !po_vm.count("input") || !po_vm.count("output") || po_vm.count("help")) { std::cout << po_desc; return EXIT_FAILURE; } const string_t cmd_input = po_vm["input"].as<string_t>(); const string_t cmd_output = po_vm["output"].as<string_t>(); const size_t cmd_count = po_vm["count"].as<size_t>(); const bool cmd_ftype_trs = po_vm.count("translation"); const bool cmd_ftype_rot = po_vm.count("rotation"); const bool cmd_ftype_rnd = po_vm.count("random"); field_type ftype = field_type::random; if (cmd_ftype_trs) { ftype = field_type::translation; } else if (cmd_ftype_rot) { ftype = field_type::rotation; } else if (cmd_ftype_rnd) { ftype = field_type::random; } const field_params fparams(ftype); // load input image image_t iimage; ncv::measure_critical_and_log( [&] () { return iimage.load_rgba(cmd_input); }, "loaded image from <" + cmd_input + ">", "failed to load image from <" + cmd_input + ">"); log_info () << "image: " << iimage.cols() << "x" << iimage.rows() << " pixels, " << (iimage.is_luma() ? "[luma]" : "[rgba]") << "."; // randomly warp the input image for (size_t c = 0; c < cmd_count; c ++) { image_t oimage, fimage; ncv::measure_and_log( [&] () { oimage = warp(iimage, fparams, &fimage); }, "warped image"); // save warped image const string_t opath = (boost::filesystem::path(cmd_output).parent_path() / boost::filesystem::path(cmd_output).stem()).string() + text::to_string(c + 1) + boost::filesystem::path(cmd_output).extension().string(); ncv::measure_critical_and_log( [&] () { return oimage.save(opath); }, "saved image to <" + opath + ">", "failed to save to <" + opath + ">"); // save field image const string_t fpath = (boost::filesystem::path(cmd_output).parent_path() / boost::filesystem::path(cmd_output).stem()).string() + text::to_string(c + 1) + "_field" + boost::filesystem::path(cmd_output).extension().string(); ncv::measure_critical_and_log( [&] () { return fimage.save(fpath); }, "saved field image to <" + fpath + ">", "failed to save to <" + fpath + ">"); } // OK log_info() << ncv::done; return EXIT_SUCCESS; } <commit_msg>cleanup<commit_after>#include "nanocv/string.h" #include "nanocv/measure.hpp" #include "nanocv/math/gauss.hpp" #include "nanocv/vision/image.h" #include "nanocv/math/random.hpp" #include "nanocv/math/numeric.hpp" #include "nanocv/tensor/random.hpp" #include "nanocv/vision/gradient.hpp" #include "nanocv/vision/convolve.hpp" #include "nanocv/tensor/transform.hpp" #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace { using namespace ncv; /// \todo move these to library (once the warping algorithm works OK) enum class field_type { translation, rotation, random, }; struct field_params { explicit field_params( field_type ftype = field_type::random, scalar_t noise = 0.1, scalar_t sigma = 0.1) : m_ftype(ftype), m_noise(noise), m_sigma(sigma) { } field_type m_ftype; scalar_t m_noise; scalar_t m_sigma; }; image_t image_field(const matrix_t& fieldx, const matrix_t& fieldy) { assert(fieldx.rows() == fieldy.rows()); assert(fieldx.cols() == fieldy.cols()); rgba_matrix_t rgba(fieldx.rows(), fieldx.cols()); tensor::transform(fieldx, fieldy, rgba, [] (const scalar_t fx, const scalar_t fy) { const auto red = math::clamp(255.0 * 0.5 * (fx + 1.0), 0.0, 255.0); const auto blue = math::clamp(255.0 * 0.5 * (fy + 1.0), 0.0, 255.0); return color::make_rgba( math::cast<rgba_t>(red), 0, math::cast<rgba_t>(blue)); }); image_t image; image.load_rgba(rgba); return image; } void smooth_field(matrix_t& field, const scalar_t sigma) { const gauss_kernel_t<scalar_t> gauss(sigma); ncv::convolve(gauss, field); } std::tuple<matrix_t, matrix_t> make_random_fields( const size_t rows, const size_t cols, const scalar_t noise, const scalar_t sigma) { matrix_t fieldx(rows, cols), fieldy(rows, cols); tensor::set_random(fieldx, random_t<scalar_t>(-noise, +noise)); tensor::set_random(fieldy, random_t<scalar_t>(-noise, +noise)); smooth_field(fieldx, sigma); smooth_field(fieldy, sigma); return std::make_tuple(fieldx, fieldy); } std::tuple<matrix_t, matrix_t> make_translation_fields( const size_t rows, const size_t cols, const scalar_t delta, const scalar_t noise, const scalar_t sigma) { matrix_t fieldx(rows, cols), fieldy(rows, cols); tensor::set_random(fieldx, random_t<scalar_t>(delta - noise, delta + noise)); tensor::set_random(fieldy, random_t<scalar_t>(delta - noise, delta + noise)); smooth_field(fieldx, sigma); smooth_field(fieldy, sigma); return std::make_tuple(fieldx, fieldy); } std::tuple<matrix_t, matrix_t> make_rotation_fields( const size_t rows, const size_t cols, const scalar_t theta, const scalar_t noise, const scalar_t sigma) { matrix_t fieldx(rows, cols), fieldy(rows, cols); const scalar_t cx = 0.5 * cols; const scalar_t cy = 0.5 * rows; const scalar_t id = 1.0 / (math::square(cx) + math::square(cy)); random_t<scalar_t> rng(-noise, +noise); for (size_t r = 0; r < rows; r ++) { for (size_t c = 0; c < cols; c ++) { const auto dist = math::square(scalar_t(r) - cy) + math::square(scalar_t(c) - cx); fieldx(r, c) = id * dist * std::cos(theta) + rng(); fieldy(r, c) = id * dist * std::sin(theta) + rng(); } } smooth_field(fieldx, sigma); smooth_field(fieldy, sigma); return std::make_tuple(fieldx, fieldy); } template < typename tmatrixio, typename tmatrixf, typename tmatrixt > void warp_by_field(tmatrixio&& x, const scalar_t alphax, const tmatrixf& fieldx, const tmatrixt& gradx, const scalar_t alphay, const tmatrixf& fieldy, const tmatrixt& grady, const scalar_t beta) { x.array() += alphax * fieldx.array() * gradx.array() + alphay * fieldy.array() * grady.array() + beta * (gradx.array().square() + grady.array().square()).sqrt(); } image_t warp(const image_t& iimage, const field_params& fparams, image_t* fimage = nullptr) { assert(iimage.is_rgba()); tensor_t patch = ncv::color::to_rgba_tensor(iimage.rgba()); // x gradient (directional gradient) tensor_t gradx(4, patch.rows(), patch.cols()); ncv::gradientx(patch.matrix(0), gradx.matrix(0)); ncv::gradientx(patch.matrix(1), gradx.matrix(1)); ncv::gradientx(patch.matrix(2), gradx.matrix(2)); ncv::gradientx(patch.matrix(3), gradx.matrix(3)); // y gradient (directional gradient) tensor_t grady(4, patch.rows(), patch.cols()); ncv::gradienty(patch.matrix(0), grady.matrix(0)); ncv::gradienty(patch.matrix(1), grady.matrix(1)); ncv::gradienty(patch.matrix(2), grady.matrix(2)); ncv::gradienty(patch.matrix(3), grady.matrix(3)); // generate random fields const scalar_t pi = std::atan2(0.0, -0.0); random_t<scalar_t> rng_theta(-pi / 8.0, +pi / 8.0); random_t<scalar_t> rng_delta(-1.0, +1.0); matrix_t fieldx, fieldy; switch (fparams.m_ftype) { case field_type::translation: std::tie(fieldx, fieldy) = make_translation_fields(patch.rows(), patch.cols(), rng_delta(), fparams.m_noise, fparams.m_sigma); break; case field_type::rotation: std::tie(fieldx, fieldy) = make_rotation_fields(patch.rows(), patch.cols(), rng_theta(), fparams.m_noise, fparams.m_sigma); break; case field_type::random: default: std::tie(fieldx, fieldy) = make_random_fields(patch.rows(), patch.cols(), fparams.m_noise, fparams.m_sigma); break; } // visualize the fields (if requested) if (fimage) { *fimage = image_field(fieldx, fieldy); } // warp random_t<scalar_t> rng_alphax(-1.0, +1.0); random_t<scalar_t> rng_alphay(-1.0, +1.0); random_t<scalar_t> rng_beta (-1.0, +1.0); const scalar_t alphax = rng_alphax(); const scalar_t alphay = rng_alphay(); const scalar_t beta = rng_beta(); warp_by_field(patch.matrix(0), alphax, fieldx, gradx.matrix(0), alphay, fieldy, grady.matrix(0), beta); warp_by_field(patch.matrix(1), alphax, fieldx, gradx.matrix(1), alphay, fieldy, grady.matrix(1), beta); warp_by_field(patch.matrix(2), alphax, fieldx, gradx.matrix(2), alphay, fieldy, grady.matrix(2), beta); warp_by_field(patch.matrix(3), alphax, fieldx, gradx.matrix(3), alphay, fieldy, grady.matrix(3), beta); // OK image_t oimage; oimage.load_rgba(color::from_rgba_tensor(patch)); return oimage; } } int main(int argc, char *argv[]) { using namespace ncv; // parse the command line boost::program_options::options_description po_desc("", 160); po_desc.add_options()("help,h", "randomly warp the input image"); po_desc.add_options()("input,i", boost::program_options::value<ncv::string_t>(), "input image path"); po_desc.add_options()("count,c", boost::program_options::value<ncv::size_t>()->default_value(32), "number of random warpings to generate"); po_desc.add_options()("translation", "use translation fields"); po_desc.add_options()("rotation", "use rotation fields"); po_desc.add_options()("random", "use random fields"); po_desc.add_options()("output,o", boost::program_options::value<ncv::string_t>(), "output (warped) image path"); boost::program_options::variables_map po_vm; boost::program_options::store( boost::program_options::command_line_parser(argc, argv).options(po_desc).run(), po_vm); boost::program_options::notify(po_vm); // check arguments and options if ( po_vm.empty() || !po_vm.count("input") || !po_vm.count("output") || po_vm.count("help")) { std::cout << po_desc; return EXIT_FAILURE; } const string_t cmd_input = po_vm["input"].as<string_t>(); const string_t cmd_output = po_vm["output"].as<string_t>(); const size_t cmd_count = po_vm["count"].as<size_t>(); const bool cmd_ftype_trs = po_vm.count("translation"); const bool cmd_ftype_rot = po_vm.count("rotation"); const bool cmd_ftype_rnd = po_vm.count("random"); field_type ftype = field_type::random; if (cmd_ftype_trs) { ftype = field_type::translation; } else if (cmd_ftype_rot) { ftype = field_type::rotation; } else if (cmd_ftype_rnd) { ftype = field_type::random; } const field_params fparams(ftype); // load input image image_t iimage; ncv::measure_critical_and_log( [&] () { return iimage.load_rgba(cmd_input); }, "loaded image from <" + cmd_input + ">", "failed to load image from <" + cmd_input + ">"); log_info () << "image: " << iimage.cols() << "x" << iimage.rows() << " pixels, " << (iimage.is_luma() ? "[luma]" : "[rgba]") << "."; // randomly warp the input image for (size_t c = 0; c < cmd_count; c ++) { image_t oimage, fimage; ncv::measure_and_log( [&] () { oimage = warp(iimage, fparams, &fimage); }, "warped image"); // save warped image const string_t opath = (boost::filesystem::path(cmd_output).parent_path() / boost::filesystem::path(cmd_output).stem()).string() + text::to_string(c + 1) + boost::filesystem::path(cmd_output).extension().string(); ncv::measure_critical_and_log( [&] () { return oimage.save(opath); }, "saved image to <" + opath + ">", "failed to save to <" + opath + ">"); // save field image const string_t fpath = (boost::filesystem::path(cmd_output).parent_path() / boost::filesystem::path(cmd_output).stem()).string() + text::to_string(c + 1) + "_field" + boost::filesystem::path(cmd_output).extension().string(); ncv::measure_critical_and_log( [&] () { return fimage.save(fpath); }, "saved field image to <" + fpath + ">", "failed to save to <" + fpath + ">"); } // OK log_info() << ncv::done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Fix regression on FAT files (from 64-bit support).<commit_after><|endoftext|>
<commit_before>#include <FAST/Streamers/KinectStreamer.hpp> #include "KinectTracking.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Data/Mesh.hpp" namespace fast { KinectTracking::KinectTracking() { createInputPort<Image>(0); createInputPort<Mesh>(1); createOutputPort<Image>(0, OUTPUT_DEPENDS_ON_INPUT, 0); createOutputPort<Image>(1, OUTPUT_STATIC); // Annotation image //createOutputPort<Mesh>(2, OUTPUT_STATIC); // Target cloud // Create annotation image mAnnotationImage = Image::New(); mAnnotationImage->create(512, 424, TYPE_UINT8, 1); mAnnotationImage->fill(0); } void KinectTracking::execute() { Image::pointer input = getStaticInputData<Image>(); Mesh::pointer meshInput = getStaticInputData<Mesh>(1); setStaticOutputData<Image>(0, input); setStaticOutputData<Image>(1, mAnnotationImage); mCurrentCloud = meshInput; } Mesh::pointer KinectTracking::getTargetCloud(KinectStreamer::pointer streamer) { std::cout << "Creating target cloud..." << std::endl; ImageAccess::pointer access = mAnnotationImage->getImageAccess(ACCESS_READ); MeshAccess::pointer meshAccess = mCurrentCloud->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> vertices = meshAccess->getVertices(); std::vector<MeshVertex> outputVertices; for(int y = 0; y < mAnnotationImage->getHeight(); ++y) { for(int x = 0; x < mAnnotationImage->getWidth(); ++x) { try { if(access->getScalar(Vector2i(x, y)) == 1) { std::cout << "hmf" << std::endl; MeshVertex vertex = streamer->getPoint(x, y); outputVertices.push_back(vertex); } } catch (Exception &e) { } } } Mesh::pointer output = Mesh::New(); output->create(outputVertices); std::cout << "Created target cloud." << std::endl; return output; } void KinectTracking::addLine(Vector2i start, Vector2i end) { std::cout << "Drawing from: " << start.transpose() << " to " << end.transpose() << std::endl; // Draw line in some auxillary image ImageAccess::pointer access = mAnnotationImage->getImageAccess(ACCESS_READ_WRITE); Vector2f direction = end.cast<float>() - start.cast<float>(); int length = (end-start).norm(); int brushSize = 6; for(int i = 0; i < length; ++i) { float distance = (float)i/length; for(int a = -brushSize; a <= brushSize; a++) { for(int b = -brushSize; b <= brushSize; b++) { Vector2f offset(a, b); if(offset.norm() > brushSize) continue; Vector2f position = start.cast<float>() + direction*distance + offset; try { access->setScalar(position.cast<int>(), 1); } catch(Exception &e) { } } } } } }<commit_msg>Nan detection in getTargetCloud<commit_after>#include <FAST/Streamers/KinectStreamer.hpp> #include "KinectTracking.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Data/Mesh.hpp" namespace fast { KinectTracking::KinectTracking() { createInputPort<Image>(0); createInputPort<Mesh>(1); createOutputPort<Image>(0, OUTPUT_DEPENDS_ON_INPUT, 0); createOutputPort<Image>(1, OUTPUT_STATIC); // Annotation image //createOutputPort<Mesh>(2, OUTPUT_STATIC); // Target cloud // Create annotation image mAnnotationImage = Image::New(); mAnnotationImage->create(512, 424, TYPE_UINT8, 1); mAnnotationImage->fill(0); } void KinectTracking::execute() { Image::pointer input = getStaticInputData<Image>(); Mesh::pointer meshInput = getStaticInputData<Mesh>(1); setStaticOutputData<Image>(0, input); setStaticOutputData<Image>(1, mAnnotationImage); mCurrentCloud = meshInput; } Mesh::pointer KinectTracking::getTargetCloud(KinectStreamer::pointer streamer) { std::cout << "Creating target cloud..." << std::endl; ImageAccess::pointer access = mAnnotationImage->getImageAccess(ACCESS_READ); MeshAccess::pointer meshAccess = mCurrentCloud->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> vertices = meshAccess->getVertices(); std::vector<MeshVertex> outputVertices; for(int y = 0; y < mAnnotationImage->getHeight(); ++y) { for(int x = 0; x < mAnnotationImage->getWidth(); ++x) { try { if(access->getScalar(Vector2i(x, y)) == 1) { MeshVertex vertex = streamer->getPoint(x, y); if(!std::isnan(vertex.getPosition().x())) { outputVertices.push_back(vertex); } } } catch (Exception &e) { } } } Mesh::pointer output = Mesh::New(); output->create(outputVertices); std::cout << "Created target cloud." << std::endl; return output; } void KinectTracking::addLine(Vector2i start, Vector2i end) { std::cout << "Drawing from: " << start.transpose() << " to " << end.transpose() << std::endl; // Draw line in some auxillary image ImageAccess::pointer access = mAnnotationImage->getImageAccess(ACCESS_READ_WRITE); Vector2f direction = end.cast<float>() - start.cast<float>(); int length = (end-start).norm(); int brushSize = 6; for(int i = 0; i < length; ++i) { float distance = (float)i/length; for(int a = -brushSize; a <= brushSize; a++) { for(int b = -brushSize; b <= brushSize; b++) { Vector2f offset(a, b); if(offset.norm() > brushSize) continue; Vector2f position = start.cast<float>() + direction*distance + offset; try { access->setScalar(position.cast<int>(), 1); } catch(Exception &e) { } } } } } }<|endoftext|>
<commit_before>//===-- ProcessLauncherWindows.cpp ------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Host/windows/ProcessLauncherWindows.h" #include "lldb/Host/HostProcess.h" #include "lldb/Host/ProcessLaunchInfo.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Program.h" #include <string> #include <vector> using namespace lldb; using namespace lldb_private; namespace { void CreateEnvironmentBuffer(const Environment &env, std::vector<char> &buffer) { if (env.size() == 0) return; // Environment buffer is a null terminated list of null terminated strings for (const auto &KV : env) { std::wstring warg; if (llvm::ConvertUTF8toWide(Environment::compose(KV), warg)) { buffer.insert(buffer.end(), (char *)warg.c_str(), (char *)(warg.c_str() + warg.size() + 1)); } } // One null wchar_t (to end the block) is two null bytes buffer.push_back(0); buffer.push_back(0); } bool GetFlattenedWindowsCommandString(Args args, std::string &command) { if (args.empty()) return false; std::vector<llvm::StringRef> args_ref; for (auto &entry : args.entries()) args_ref.push_back(entry.ref); command = llvm::sys::flattenWindowsCommandLine(args_ref); return true; } } // namespace HostProcess ProcessLauncherWindows::LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) { error.Clear(); std::string executable; std::string commandLine; std::vector<char> environment; STARTUPINFO startupinfo = {}; PROCESS_INFORMATION pi = {}; HANDLE stdin_handle = GetStdioHandle(launch_info, STDIN_FILENO); HANDLE stdout_handle = GetStdioHandle(launch_info, STDOUT_FILENO); HANDLE stderr_handle = GetStdioHandle(launch_info, STDERR_FILENO); startupinfo.cb = sizeof(startupinfo); startupinfo.dwFlags |= STARTF_USESTDHANDLES; startupinfo.hStdError = stderr_handle ? stderr_handle : ::GetStdHandle(STD_ERROR_HANDLE); startupinfo.hStdInput = stdin_handle ? stdin_handle : ::GetStdHandle(STD_INPUT_HANDLE); startupinfo.hStdOutput = stdout_handle ? stdout_handle : ::GetStdHandle(STD_OUTPUT_HANDLE); const char *hide_console_var = getenv("LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE"); if (hide_console_var && llvm::StringRef(hide_console_var).equals_lower("true")) { startupinfo.dwFlags |= STARTF_USESHOWWINDOW; startupinfo.wShowWindow = SW_HIDE; } DWORD flags = CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT; if (launch_info.GetFlags().Test(eLaunchFlagDebug)) flags |= DEBUG_ONLY_THIS_PROCESS; if (launch_info.GetFlags().Test(eLaunchFlagDisableSTDIO)) flags &= ~CREATE_NEW_CONSOLE; LPVOID env_block = nullptr; ::CreateEnvironmentBuffer(launch_info.GetEnvironment(), environment); if (!environment.empty()) env_block = environment.data(); executable = launch_info.GetExecutableFile().GetPath(); GetFlattenedWindowsCommandString(launch_info.GetArguments(), commandLine); std::wstring wexecutable, wcommandLine, wworkingDirectory; llvm::ConvertUTF8toWide(executable, wexecutable); llvm::ConvertUTF8toWide(commandLine, wcommandLine); llvm::ConvertUTF8toWide(launch_info.GetWorkingDirectory().GetCString(), wworkingDirectory); wcommandLine.resize(PATH_MAX); // Needs to be over-allocated because // CreateProcessW can modify it BOOL result = ::CreateProcessW( wexecutable.c_str(), &wcommandLine[0], NULL, NULL, TRUE, flags, env_block, wworkingDirectory.size() == 0 ? NULL : wworkingDirectory.c_str(), &startupinfo, &pi); if (!result) { // Call GetLastError before we make any other system calls. error.SetError(::GetLastError(), eErrorTypeWin32); } if (result) { // Do not call CloseHandle on pi.hProcess, since we want to pass that back // through the HostProcess. ::CloseHandle(pi.hThread); } if (stdin_handle) ::CloseHandle(stdin_handle); if (stdout_handle) ::CloseHandle(stdout_handle); if (stderr_handle) ::CloseHandle(stderr_handle); if (!result) return HostProcess(); return HostProcess(pi.hProcess); } HANDLE ProcessLauncherWindows::GetStdioHandle(const ProcessLaunchInfo &launch_info, int fd) { const FileAction *action = launch_info.GetFileActionForFD(fd); if (action == nullptr) return NULL; SECURITY_ATTRIBUTES secattr = {}; secattr.nLength = sizeof(SECURITY_ATTRIBUTES); secattr.bInheritHandle = TRUE; llvm::StringRef path = action->GetPath(); DWORD access = 0; DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; DWORD create = 0; DWORD flags = 0; if (fd == STDIN_FILENO) { access = GENERIC_READ; create = OPEN_EXISTING; flags = FILE_ATTRIBUTE_READONLY; } if (fd == STDOUT_FILENO || fd == STDERR_FILENO) { access = GENERIC_WRITE; create = CREATE_ALWAYS; if (fd == STDERR_FILENO) flags = FILE_FLAG_WRITE_THROUGH; } std::wstring wpath; llvm::ConvertUTF8toWide(path, wpath); HANDLE result = ::CreateFileW(wpath.c_str(), access, share, &secattr, create, flags, NULL); return (result == INVALID_HANDLE_VALUE) ? NULL : result; } <commit_msg>Improve process launch comments for Windows<commit_after>//===-- ProcessLauncherWindows.cpp ------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Host/windows/ProcessLauncherWindows.h" #include "lldb/Host/HostProcess.h" #include "lldb/Host/ProcessLaunchInfo.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Program.h" #include <string> #include <vector> using namespace lldb; using namespace lldb_private; namespace { void CreateEnvironmentBuffer(const Environment &env, std::vector<char> &buffer) { if (env.size() == 0) return; // Environment buffer is a null terminated list of null terminated strings for (const auto &KV : env) { std::wstring warg; if (llvm::ConvertUTF8toWide(Environment::compose(KV), warg)) { buffer.insert(buffer.end(), (char *)warg.c_str(), (char *)(warg.c_str() + warg.size() + 1)); } } // One null wchar_t (to end the block) is two null bytes buffer.push_back(0); buffer.push_back(0); } bool GetFlattenedWindowsCommandString(Args args, std::string &command) { if (args.empty()) return false; std::vector<llvm::StringRef> args_ref; for (auto &entry : args.entries()) args_ref.push_back(entry.ref); command = llvm::sys::flattenWindowsCommandLine(args_ref); return true; } } // namespace HostProcess ProcessLauncherWindows::LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) { error.Clear(); std::string executable; std::string commandLine; std::vector<char> environment; STARTUPINFO startupinfo = {}; PROCESS_INFORMATION pi = {}; HANDLE stdin_handle = GetStdioHandle(launch_info, STDIN_FILENO); HANDLE stdout_handle = GetStdioHandle(launch_info, STDOUT_FILENO); HANDLE stderr_handle = GetStdioHandle(launch_info, STDERR_FILENO); startupinfo.cb = sizeof(startupinfo); startupinfo.dwFlags |= STARTF_USESTDHANDLES; startupinfo.hStdError = stderr_handle ? stderr_handle : ::GetStdHandle(STD_ERROR_HANDLE); startupinfo.hStdInput = stdin_handle ? stdin_handle : ::GetStdHandle(STD_INPUT_HANDLE); startupinfo.hStdOutput = stdout_handle ? stdout_handle : ::GetStdHandle(STD_OUTPUT_HANDLE); const char *hide_console_var = getenv("LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE"); if (hide_console_var && llvm::StringRef(hide_console_var).equals_lower("true")) { startupinfo.dwFlags |= STARTF_USESHOWWINDOW; startupinfo.wShowWindow = SW_HIDE; } DWORD flags = CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT; if (launch_info.GetFlags().Test(eLaunchFlagDebug)) flags |= DEBUG_ONLY_THIS_PROCESS; if (launch_info.GetFlags().Test(eLaunchFlagDisableSTDIO)) flags &= ~CREATE_NEW_CONSOLE; LPVOID env_block = nullptr; ::CreateEnvironmentBuffer(launch_info.GetEnvironment(), environment); if (!environment.empty()) env_block = environment.data(); executable = launch_info.GetExecutableFile().GetPath(); GetFlattenedWindowsCommandString(launch_info.GetArguments(), commandLine); std::wstring wexecutable, wcommandLine, wworkingDirectory; llvm::ConvertUTF8toWide(executable, wexecutable); llvm::ConvertUTF8toWide(commandLine, wcommandLine); llvm::ConvertUTF8toWide(launch_info.GetWorkingDirectory().GetCString(), wworkingDirectory); // If the command line is empty, it's best to pass a null pointer to tell // CreateProcessW to use the executable name as the command line. If the // command line is not empty, its contents may be modified by CreateProcessW. WCHAR *pwcommandLine = wcommandLine.empty() ? nullptr : &wcommandLine[0]; BOOL result = ::CreateProcessW( wexecutable.c_str(), pwcommandLine, NULL, NULL, TRUE, flags, env_block, wworkingDirectory.size() == 0 ? NULL : wworkingDirectory.c_str(), &startupinfo, &pi); if (!result) { // Call GetLastError before we make any other system calls. error.SetError(::GetLastError(), eErrorTypeWin32); // Note that error 50 ("The request is not supported") will occur if you // try debug a 64-bit inferior from a 32-bit LLDB. } if (result) { // Do not call CloseHandle on pi.hProcess, since we want to pass that back // through the HostProcess. ::CloseHandle(pi.hThread); } if (stdin_handle) ::CloseHandle(stdin_handle); if (stdout_handle) ::CloseHandle(stdout_handle); if (stderr_handle) ::CloseHandle(stderr_handle); if (!result) return HostProcess(); return HostProcess(pi.hProcess); } HANDLE ProcessLauncherWindows::GetStdioHandle(const ProcessLaunchInfo &launch_info, int fd) { const FileAction *action = launch_info.GetFileActionForFD(fd); if (action == nullptr) return NULL; SECURITY_ATTRIBUTES secattr = {}; secattr.nLength = sizeof(SECURITY_ATTRIBUTES); secattr.bInheritHandle = TRUE; llvm::StringRef path = action->GetPath(); DWORD access = 0; DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; DWORD create = 0; DWORD flags = 0; if (fd == STDIN_FILENO) { access = GENERIC_READ; create = OPEN_EXISTING; flags = FILE_ATTRIBUTE_READONLY; } if (fd == STDOUT_FILENO || fd == STDERR_FILENO) { access = GENERIC_WRITE; create = CREATE_ALWAYS; if (fd == STDERR_FILENO) flags = FILE_FLAG_WRITE_THROUGH; } std::wstring wpath; llvm::ConvertUTF8toWide(path, wpath); HANDLE result = ::CreateFileW(wpath.c_str(), access, share, &secattr, create, flags, NULL); return (result == INVALID_HANDLE_VALUE) ? NULL : result; } <|endoftext|>
<commit_before>#ifndef GUARD_persistent_object_hpp #define GUARD_persistent_object_hpp #include "database_connection.hpp" #include <jewel/decimal.hpp> #include <boost/optional.hpp> #include <boost/shared_ptr.hpp> #include <stdexcept> #include <string> namespace sqloxx { /** * Class template for creating objects persisted to a database. * * @todo Provide for atomicity of loading and saving (not just of * SQL execution, but of the actual alteration of the in-memory objects). * * @todo Unit testing. * * @todo Document protected function APIs. */ template <typename Id> class PersistentObject { public: /** * Create a PersistentObject that corresponds (or purports to correspond) * to one that already exists in the database. * * Note that even if there is no corresponding object in the database for * the given value p_id, this constructor will still proceed without * complaint. The constructor does not actually perform any checks on the * validity either of p_database_connection or of p_id. * * Exception safety: <em>nothrow guarantee</em> (though derived classes' * constructors might, of course, throw). */ PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection, Id p_id ); /** * Create a PersistentObject that does not correspond to * one that already exists in the database. * * Exception safety: <em>nothrow guarantee</em> (though derived classes' * constructors might, of course, throw). */ explicit PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection ); /** * Exception safety: <em>nothrow guarantee</em> (though this destructor * cannot, of course, offer any guarantees about the exception safety * of derived classes' destructors). */ virtual ~PersistentObject(); /** * Calls the derived class's implementation * of do_load_all, if the object is not already * fully loaded. If the object does not have an id, * then this function does nothing. * * Note the implementation is wrapped as a transaction * by calls to begin_transaction and end_transaction * methods of the DatabaseConnection. */ void load(); /** * Saves the state of the in-memory object to the * database, overwriting the data in the database in the * event of any conflict with the existing persisted data * for this id. This is done by calling * do_save_existing_partial (in the event the object is not * fully loaded) or do_save_existing_all (in the event the object * is fully loaded). The do_save_... functions should be defined in * the derived class. * * Note the implementation is wrapped as a transaction * by calls to begin_transaction and end_transaction * methods of the DatabaseConnection. */ void save_existing(); /** * Saves the state of the in-memory object to the database, * as an additional item, rather than overwriting existing * data. This is done by calling the pure virtual function * do_save_new_all, which must be defined in the derived * class. Note the do_get_table_name function must also * be defined in the derived class in order for this function * to find an automatically generated id to assign to the object * when saved. By default it is assumed that the id is an auto- * incrementing integer primary key generated by SQLite. However this * behaviour can be overridden by redefining the * do_calculate_prospective_key function in the derived class. * * Note the implementation is wrapped as a transaction by call to * begin_transaction and end_transaction methods of * DatabaseConnection. */ void save_new(); /** * Returns the id of the object. If the object doesn't have an id, * this will CRASH via an assertion failure - rather than throw. */ Id id() const; protected: /** * @returns a boost::shared_ptr to the database connection with which * this instance of PersistentObject is associated. This is where the * object will be loaded from or saved to, as the case may be. * * Exception safety: <em>nothrow guarantee</em> */ boost::shared_ptr<DatabaseConnection> database_connection() const; /** * Note an object that is created anew, that does not already exist * in the database, should not have an id. By having an id, an object * is saying "I exist in the database". */ void set_id(Id p_id); /** * @returns the id that would be assigned to the this instance of * PersistentObject when saved to the database. * * This function calls /e do_calculate_prospective_key, which has a * default implementation but may be redefined. * * @throws std::logic_error in the event this instance already has * an id. (This occurs regardless of how/whether * \e do_calculate_prospective_key is redefined.) * * Apart from \e std::logic_error as just described, the exception * throwing behaviour and exception safety of this function depend on * those of the function PersistentObject::do_calculate_prospective_key. */ Id prospective_key() const; /** * @returns \e true if this instance of PersistentObject has * an valid id; otherwise returns \e false. * * Exception safety: <em>nothrow guarantee</em>. */ bool has_id() const; /** * <em>The documentation for this function refers only to the * default definition provided by PersistentObject.</em> * * Provides an implementation for the public function prospective_key. * Should not be called by any functions are than prospective_key. * * @throws sqloxx::TableSizeException if the greatest primary key value * already in the table (i.e. the table into which this instance of * PersistentObject would be persisted) is the maximum value for the * type \e Id, so that another row could not be inserted without overflow. * * @throws sqloxx::DatabaseException, or a derivative therefrom, may * be thrown if there is some other * error finding the next primary key value. This should not occur except * in the case of a corrupt database, or a memory allocation error * (extremely unlikely), or the database connection being invalid * (including because not yet connected to a database file). * @throws sqloxx::InvalidConnection if the database connection * associated with this instance of PersistentObject is invalid. * * Exception safety: <em>strong guarantee</em>. */ virtual Id do_calculate_prospective_key() const; /** * See documentation for public \e load function. * * Exception safety: <em>depends on function definition * provided by derived class</em> */ virtual void do_load_all() = 0; /** * See documentation for public <em>save_existing</em> function. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual void do_save_existing_all() = 0; /** * See documentation for public <em>save_existing</em> function. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual void do_save_existing_partial() = 0; /** * See documentation for public <em>save_new</em> function. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual void do_save_new_all() = 0; /** * This function should be defined in the derived class to return the * name of the table in which instances of the derived class are stored * in the database. This function is in turn called by the default * implementation of \e do_calculate_prospective_key, which is in turn * called by \e save_new. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual std::string do_get_table_name() const = 0; private: enum LoadingStatus { ghost = 0, loading, loaded }; // Data members boost::shared_ptr<DatabaseConnection> m_database_connection; boost::optional<Id> m_id; LoadingStatus m_loading_status; }; template <typename Id> inline PersistentObject<Id>::PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection, Id p_id ): m_database_connection(p_database_connection), m_id(p_id), m_loading_status(ghost) { } template <typename Id> inline PersistentObject<Id>::PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection ): m_database_connection(p_database_connection), m_loading_status(ghost) { } template <typename Id> inline PersistentObject<Id>::~PersistentObject() { } template <typename Id> inline void PersistentObject<Id>::load() { if (m_loading_status == ghost && has_id()) { m_loading_status = loading; m_database_connection->begin_transaction(); do_load_all(); m_database_connection->end_transaction(); m_loading_status = loaded; } return; } template <typename Id> inline void PersistentObject<Id>::save_existing() { start: switch (m_loading_status) { case loaded: m_database_connection->begin_transaction(); do_save_existing_all(); m_database_connection->end_transaction(); break; case ghost: m_database_connection->begin_transaction(); do_save_existing_partial(); m_database_connection->end_transaction(); break; case loading: goto start; break; default: throw std::logic_error("Loading status not recognized."); } return; } template <typename Id> inline Id PersistentObject<Id>::prospective_key() const { if (has_id()) { throw std::logic_error ( "Object already has id so prospective_key does not apply." ); } return do_calculate_prospective_key(); } template <typename Id> inline Id PersistentObject<Id>::do_calculate_prospective_key() const { return database_connection()->template next_auto_key<Id> ( do_get_table_name() ); } template <typename Id> inline void PersistentObject<Id>::save_new() { m_database_connection->begin_transaction(); Id const key = prospective_key(); do_save_new_all(); m_database_connection->end_transaction(); set_id(key); return; } template <typename Id> inline boost::shared_ptr<DatabaseConnection> PersistentObject<Id>::database_connection() const { return m_database_connection; } template <typename Id> inline Id PersistentObject<Id>::id() const { return *m_id; } template <typename Id> inline void PersistentObject<Id>::set_id(Id p_id) { m_id = p_id; return; } template <typename Id> inline bool PersistentObject<Id>::has_id() const { // Relies on the fact that m_id is a boost::optional<Id>, and // will convert to true if and only if it has been initialized. return m_id; } } // namespace sqloxx #endif // GUARD_persistent_object <commit_msg>Continued documenting API of PersistentObject.<commit_after>#ifndef GUARD_persistent_object_hpp #define GUARD_persistent_object_hpp #include "database_connection.hpp" #include <jewel/decimal.hpp> #include <boost/optional.hpp> #include <boost/shared_ptr.hpp> #include <stdexcept> #include <string> namespace sqloxx { /** * Class template for creating objects persisted to a database. * * @todo Provide for atomicity of loading and saving (not just of * SQL execution, but of the actual alteration of the in-memory objects). * * @todo Unit testing. */ template <typename Id> class PersistentObject { public: /** * Create a PersistentObject that corresponds (or purports to correspond) * to one that already exists in the database. * * @param p_database_connection database connection with * which the PersistentObject is associated. * * @param p_id the id of the object as it exists in the database. This * presumably will be, or correspond directly to, the primary key. * * Note that even if there is no corresponding object in the database for * the given value p_id, this constructor will still proceed without * complaint. The constructor does not actually perform any checks on the * validity either of p_database_connection or of p_id. * * Exception safety: <em>nothrow guarantee</em> (though derived classes' * constructors might, of course, throw). */ PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection, Id p_id ); /** * Create a PersistentObject that does \e not correspond to * one that already exists in the database. * * @param p_database_connection database connection with which the * PersistentObject is to be associated. * * Exception safety: <em>nothrow guarantee</em> (though derived classes' * constructors might, of course, throw). */ explicit PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection ); /** * Exception safety: <em>nothrow guarantee</em> (though this destructor * cannot, of course, offer any guarantees about the exception safety * of derived classes' destructors). */ virtual ~PersistentObject(); /** * Calls the derived class's implementation * of do_load_all, if the object is not already * fully loaded. If the object does not have an id, * then this function does nothing. * * Note the implementation is wrapped as a transaction * by calls to begin_transaction and end_transaction * methods of the DatabaseConnection. * * @todo Document exception safety. */ void load(); /** * Saves the state of the in-memory object to the * database, overwriting the data in the database in the * event of any conflict with the existing persisted data * for this id. This is done by calling * do_save_existing_partial (in the event the object is not * fully loaded) or do_save_existing_all (in the event the object * is fully loaded). The do_save_... functions should be defined in * the derived class. * * Note the implementation is wrapped as a transaction * by calls to begin_transaction and end_transaction * methods of the DatabaseConnection. * * @todo Document exception safety. */ void save_existing(); /** * Saves the state of the in-memory object to the database, * as an additional item, rather than overwriting existing * data. This is done by calling the pure virtual function * do_save_new_all, which must be defined in the derived * class. Note the do_get_table_name function must also * be defined in the derived class in order for this function * to find an automatically generated id to assign to the object * when saved. By default it is assumed that the id is an auto- * incrementing integer primary key generated by SQLite. However this * behaviour can be overridden by redefining the * do_calculate_prospective_key function in the derived class. * * Note the implementation is wrapped as a transaction by call to * begin_transaction and end_transaction methods of * DatabaseConnection. * * @todo Document exception safety. */ void save_new(); /** * @returns the id of the object. If the object doesn't have an id, * this will CRASH via an assertion failure - rather than throw. * * @todo Change this so that if the object doesn't have an id, it * will throw an exception rather than crash. To do this, I should * create a value-retrieving function to wrap around the * boost::optional "dereferencing" operation. * * @todo Document exception safety. */ Id id() const; protected: /** * @returns a boost::shared_ptr to the database connection with which * this instance of PersistentObject is associated. This is where the * object will be loaded from or saved to, as the case may be. * * Exception safety: <em>nothrow guarantee</em> */ boost::shared_ptr<DatabaseConnection> database_connection() const; /** * Sets the id of this instance of PersistentObject to p_id. * * @param p_id the value to which you want to set the id of this object. * * Note an object that is created anew, that does not already exist * in the database, should not have an id. By having an id, an object * is saying "I exist in the database". * * Exception safety: <em>nothrow guarantee</em>. */ void set_id(Id p_id); /** * @returns the id that would be assigned to the this instance of * PersistentObject when saved to the database. * * This function calls /e do_calculate_prospective_key, which has a * default implementation but may be redefined. * * @throws std::logic_error in the event this instance already has * an id. (This occurs regardless of how/whether * \e do_calculate_prospective_key is redefined.) * * Apart from \e std::logic_error as just described, the exception * throwing behaviour and exception safety of this function depend on * those of the function PersistentObject::do_calculate_prospective_key. */ Id prospective_key() const; /** * @returns \e true if this instance of PersistentObject has * an valid id; otherwise returns \e false. * * Exception safety: <em>nothrow guarantee</em>. */ bool has_id() const; /** * <em>The documentation for this function refers only to the * default definition provided by PersistentObject.</em> * * Provides an implementation for the public function prospective_key. * Should not be called by any functions are than prospective_key. * * @throws sqloxx::TableSizeException if the greatest primary key value * already in the table (i.e. the table into which this instance of * PersistentObject would be persisted) is the maximum value for the * type \e Id, so that another row could not be inserted without overflow. * * @throws sqloxx::DatabaseException, or a derivative therefrom, may * be thrown if there is some other * error finding the next primary key value. This should not occur except * in the case of a corrupt database, or a memory allocation error * (extremely unlikely), or the database connection being invalid * (including because not yet connected to a database file). * @throws sqloxx::InvalidConnection if the database connection * associated with this instance of PersistentObject is invalid. * * Exception safety: <em>strong guarantee</em>. */ virtual Id do_calculate_prospective_key() const; /** * See documentation for public \e load function. * * Exception safety: <em>depends on function definition * provided by derived class</em> */ virtual void do_load_all() = 0; /** * See documentation for public <em>save_existing</em> function. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual void do_save_existing_all() = 0; /** * See documentation for public <em>save_existing</em> function. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual void do_save_existing_partial() = 0; /** * See documentation for public <em>save_new</em> function. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual void do_save_new_all() = 0; /** * This function should be defined in the derived class to return the * name of the table in which instances of the derived class are stored * in the database. This function is in turn called by the default * implementation of \e do_calculate_prospective_key, which is in turn * called by \e save_new. * * Exception safety: <em>depends on function definition provided by * derived class</em>. */ virtual std::string do_get_table_name() const = 0; private: enum LoadingStatus { ghost = 0, loading, loaded }; // Data members boost::shared_ptr<DatabaseConnection> m_database_connection; boost::optional<Id> m_id; LoadingStatus m_loading_status; }; template <typename Id> inline PersistentObject<Id>::PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection, Id p_id ): m_database_connection(p_database_connection), m_id(p_id), m_loading_status(ghost) { } template <typename Id> inline PersistentObject<Id>::PersistentObject ( boost::shared_ptr<DatabaseConnection> p_database_connection ): m_database_connection(p_database_connection), m_loading_status(ghost) { } template <typename Id> inline PersistentObject<Id>::~PersistentObject() { } template <typename Id> inline void PersistentObject<Id>::load() { if (m_loading_status == ghost && has_id()) { m_loading_status = loading; m_database_connection->begin_transaction(); do_load_all(); m_database_connection->end_transaction(); m_loading_status = loaded; } return; } template <typename Id> inline void PersistentObject<Id>::save_existing() { start: switch (m_loading_status) { case loaded: m_database_connection->begin_transaction(); do_save_existing_all(); m_database_connection->end_transaction(); break; case ghost: m_database_connection->begin_transaction(); do_save_existing_partial(); m_database_connection->end_transaction(); break; case loading: goto start; break; default: throw std::logic_error("Loading status not recognized."); } return; } template <typename Id> inline Id PersistentObject<Id>::prospective_key() const { if (has_id()) { throw std::logic_error ( "Object already has id so prospective_key does not apply." ); } return do_calculate_prospective_key(); } template <typename Id> inline Id PersistentObject<Id>::do_calculate_prospective_key() const { return database_connection()->template next_auto_key<Id> ( do_get_table_name() ); } template <typename Id> inline void PersistentObject<Id>::save_new() { m_database_connection->begin_transaction(); Id const key = prospective_key(); do_save_new_all(); m_database_connection->end_transaction(); set_id(key); return; } template <typename Id> inline boost::shared_ptr<DatabaseConnection> PersistentObject<Id>::database_connection() const { return m_database_connection; } template <typename Id> inline Id PersistentObject<Id>::id() const { return *m_id; } template <typename Id> inline void PersistentObject<Id>::set_id(Id p_id) { m_id = p_id; return; } template <typename Id> inline bool PersistentObject<Id>::has_id() const { // Relies on the fact that m_id is a boost::optional<Id>, and // will convert to true if and only if it has been initialized. return m_id; } } // namespace sqloxx #endif // GUARD_persistent_object <|endoftext|>
<commit_before>#include <blackhole/sink/stream.hpp> #include "global.hpp" using namespace blackhole; TEST(stream_t, Class) { sink::stream_t sink1(sink::stream_t::output_t::stdout); sink::stream_t sink2(sink::stream_t::output_t::stderr); UNUSED(sink1); UNUSED(sink2); } TEST(stream_t, IsThreadUnsafe) { static_assert( sink::thread_safety< sink::stream_t >::type::value == sink::thread::safety_t::unsafe, "stream_t sink must be thread unsafe" ); } TEST(stream_t, StringConstructor) { sink::stream_t sink1("stdout"); sink::stream_t sink2("stderr"); UNUSED(sink1); UNUSED(sink2); } TEST(stream_t, StreamConstructor) { std::ostringstream stream; sink::stream_t sink(stream); sink.consume("test message"); EXPECT_EQ("test message\n", stream.str()); } TEST(stream_t, CanConsumeLogMessage) { sink::stream_t sink(sink::stream_t::output_t::stdout); sink.consume("test message for stream sink"); } <commit_msg>[Code Style] Style.<commit_after>#include <blackhole/sink/stream.hpp> #include "global.hpp" using namespace blackhole; TEST(stream_t, Class) { sink::stream_t sink1(sink::stream_t::output_t::stdout); sink::stream_t sink2(sink::stream_t::output_t::stderr); UNUSED(sink1); UNUSED(sink2); } TEST(stream_t, IsThreadUnsafe) { static_assert( sink::thread_safety< sink::stream_t >::type::value == sink::thread::safety_t::unsafe, "`stream_t` sink must be thread unsafe" ); } TEST(stream_t, StringConstructor) { sink::stream_t sink1("stdout"); sink::stream_t sink2("stderr"); UNUSED(sink1); UNUSED(sink2); } TEST(stream_t, StreamConstructor) { std::ostringstream stream; sink::stream_t sink(stream); sink.consume("test message"); EXPECT_EQ("test message\n", stream.str()); } TEST(stream_t, CanConsumeLogMessage) { sink::stream_t sink(sink::stream_t::output_t::stdout); sink.consume("test message for stream sink"); } <|endoftext|>
<commit_before>#include "volume_renderer.h" TLANG_NAMESPACE_BEGIN bool use_gui = false; auto volume_renderer = [](std::vector<std::string> cli_param) { auto param = parse_param(cli_param); bool gpu = param.get("gpu", true); TC_P(gpu); CoreState::set_trigger_gdb_when_crash(true); Program prog(gpu ? Arch::gpu : Arch::x86_64); prog.config.print_ir = true; TRenderer renderer((Dict())); layout([&] { renderer.place_data(); }); renderer.declare_kernels(); std::unique_ptr<GUI> gui = nullptr; int n = renderer.output_res.y; int grid_resolution = renderer.grid_resolution; auto f = fopen("snow_density_256.bin", "rb"); TC_ASSERT_INFO(f, "./snow_density_256.bin not found"); std::vector<float32> density_field(pow<3>(grid_resolution)); if (std::fread(density_field.data(), sizeof(float32), density_field.size(), f)) {} std::fclose(f); float32 target_max_density = 724.0; auto max_density = 0.0f; for (int i = 0; i < pow<3>(grid_resolution); i++) { max_density = std::max(max_density, density_field[i]); } TC_P(max_density); for (int i = 0; i < pow<3>(grid_resolution); i++) { density_field[i] /= max_density; // normalize to 1 first density_field[i] *= target_max_density * 1; // then scale density_field[i] = std::min(density_field[i], target_max_density); } for (int i = 0; i < grid_resolution; i++) { for (int j = 0; j < grid_resolution; j++) { for (int k = 0; k < grid_resolution; k++) { auto d = density_field[i * grid_resolution * grid_resolution + j * grid_resolution + k]; if (d != 0) { // populate non-empty voxels only renderer.density.val<float32>(i, j, k) = d; } } } } renderer.preprocess_volume(); if (use_gui) { gui = std::make_unique<GUI>("Volume Renderer", Vector2i(n * 2, n)); } Vector2i render_size(n * 2, n); Array2D<Vector4> render_buffer; auto tone_map = [](real x) { return std::sqrt(x); }; constexpr int N = 10; for (int frame = 0; frame < 100; frame++) { for (int i = 0; i < N; i++) { renderer.sample(); } prog.profiler_print(); real scale = 1.0f / ((frame + 1) * N); render_buffer.initialize(render_size); std::unique_ptr<Canvas> canvas; canvas = std::make_unique<Canvas>(render_buffer); for (int i = 0; i < n * n * 2; i++) { render_buffer[i / n][i % n] = Vector4(tone_map(scale * renderer.buffer(0).val<float32>(i)), tone_map(scale * renderer.buffer(1).val<float32>(i)), tone_map(scale * renderer.buffer(2).val<float32>(i)), 1); } for (int i = 0; i < renderer.sky_map_size[0]; i++) { for (int j = 0; j < renderer.sky_map_size[1]; j++) { for (int d = 0; d < 3; d++) { // canvas->img[i][j][d] = sky_map(d).val<float32>(i, j) * 500; } } } if (use_gui) { gui->canvas->img = canvas->img; gui->update(); } else { canvas->img.write_as_image(fmt::format("{:05d}-{:05d}-{:05d}.png", frame, N, renderer.parameters.depth_limit)); } } }; TC_REGISTER_TASK(volume_renderer); auto volume_renderer_gui = [](std::vector<std::string> cli_param) { use_gui = true; volume_renderer(cli_param); }; TC_REGISTER_TASK(volume_renderer_gui); TLANG_NAMESPACE_END <commit_msg>depth limit slider<commit_after>#include "volume_renderer.h" TLANG_NAMESPACE_BEGIN bool use_gui = false; auto volume_renderer = [](std::vector<std::string> cli_param) { auto param = parse_param(cli_param); bool gpu = param.get("gpu", true); TC_P(gpu); CoreState::set_trigger_gdb_when_crash(true); Program prog(gpu ? Arch::gpu : Arch::x86_64); prog.config.print_ir = true; TRenderer renderer((Dict())); layout([&] { renderer.place_data(); }); renderer.declare_kernels(); std::unique_ptr<GUI> gui = nullptr; int n = renderer.output_res.y; int grid_resolution = renderer.grid_resolution; auto f = fopen("snow_density_256.bin", "rb"); TC_ASSERT_INFO(f, "./snow_density_256.bin not found"); std::vector<float32> density_field(pow<3>(grid_resolution)); if (std::fread(density_field.data(), sizeof(float32), density_field.size(), f)) {} std::fclose(f); float32 target_max_density = 724.0; auto max_density = 0.0f; for (int i = 0; i < pow<3>(grid_resolution); i++) { max_density = std::max(max_density, density_field[i]); } TC_P(max_density); for (int i = 0; i < pow<3>(grid_resolution); i++) { density_field[i] /= max_density; // normalize to 1 first density_field[i] *= target_max_density * 1; // then scale density_field[i] = std::min(density_field[i], target_max_density); } for (int i = 0; i < grid_resolution; i++) { for (int j = 0; j < grid_resolution; j++) { for (int k = 0; k < grid_resolution; k++) { auto d = density_field[i * grid_resolution * grid_resolution + j * grid_resolution + k]; if (d != 0) { // populate non-empty voxels only renderer.density.val<float32>(i, j, k) = d; } } } } renderer.preprocess_volume(); if (use_gui) { gui = std::make_unique<GUI>("Volume Renderer", Vector2i(n * 2, n)); gui->slider("depth_limit", renderer.parameters.depth_limit, 1, 20); } Vector2i render_size(n * 2, n); Array2D<Vector4> render_buffer; auto tone_map = [](real x) { return std::sqrt(x); }; constexpr int N = 1; for (int frame = 0; frame < 1000000; frame++) { for (int i = 0; i < N; i++) { renderer.sample(); } prog.profiler_print(); real scale = 1.0f / ((frame + 1) * N); render_buffer.initialize(render_size); std::unique_ptr<Canvas> canvas; canvas = std::make_unique<Canvas>(render_buffer); for (int i = 0; i < n * n * 2; i++) { render_buffer[i / n][i % n] = Vector4(tone_map(scale * renderer.buffer(0).val<float32>(i)), tone_map(scale * renderer.buffer(1).val<float32>(i)), tone_map(scale * renderer.buffer(2).val<float32>(i)), 1); } for (int i = 0; i < renderer.sky_map_size[0]; i++) { for (int j = 0; j < renderer.sky_map_size[1]; j++) { for (int d = 0; d < 3; d++) { // canvas->img[i][j][d] = sky_map(d).val<float32>(i, j) * 500; } } } if (use_gui) { gui->canvas->img = canvas->img; gui->update(); } else { canvas->img.write_as_image(fmt::format("{:05d}-{:05d}-{:05d}.png", frame, N, renderer.parameters.depth_limit)); } } }; TC_REGISTER_TASK(volume_renderer); auto volume_renderer_gui = [](std::vector<std::string> cli_param) { use_gui = true; volume_renderer(cli_param); }; TC_REGISTER_TASK(volume_renderer_gui); TLANG_NAMESPACE_END <|endoftext|>
<commit_before>#ifndef CONSOLEPLAYER_HPP #define CONSOLEPLAYER_HPP #include <istream> #include "model/IPlayer.hpp" namespace ui { namespace text { class ConsolePlayer : public model::IPlayer { public: ConsolePlayer(std::istream&); void connectGameState(const std::vector<Card>& cardsView, const std::vector<Call>& callsView, const std::vector<Trick>& tricksView); void connectDummyHand(const std::vector<Card>& cardsView); Card getCard(); Card getDummyCard(); Call getCall(); private: std::istream& stream; std::vector<Card> const * cardsView; std::vector<Call> const* callsView; std::vector<Trick> const* tricksView; std::vector<Card> const* cardsView }; } // namespace text } // namespace ui #endif <commit_msg>Typo fixed<commit_after>#ifndef CONSOLEPLAYER_HPP #define CONSOLEPLAYER_HPP #include <istream> #include "model/IPlayer.hpp" #include "" namespace ui { namespace text { class ConsolePlayer : public model::IPlayer { public: ConsolePlayer(std::istream&); void connectGameState(const std::vector<Card>& cardsView, const std::vector<Call>& callsView, const std::vector<Trick>& tricksView); void connectDummyHand(const std::vector<Card>& cardsView); Card getCard(); Card getDummyCard(); Call getCall(); private: std::istream& stream; std::vector<Card> const * cardsView; std::vector<Call> const* callsView; std::vector<Trick> const* tricksView; std::vector<Card> const* cardsView; }; } // namespace text } // namespace ui #endif <|endoftext|>
<commit_before>#include "../codecvt/codecvt_specializations.h" #include "../codecvt/utf_conversion_helpers.h" #include <cstring> #include "cppunit-header.h" #include "multistring.h" // utility wrapper to adapt locale-bound facets for wstring/wbuffer convert template<class Facet> class deletable_facet : public Facet { public: template<class ...Args> deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {} ~deletable_facet() {} }; // Primary declaration template <typename> class Test_codecvt_base; template <template<class, class...> class CVT, typename CHAR_T, typename... OTHER> class Test_codecvt_base<CVT<CHAR_T, OTHER...>> : public CppUnit::TestFixture { public: typedef CVT<CHAR_T, OTHER...> cvt_t; CPPUNIT_TEST_SUITE(Test_codecvt_base); CPPUNIT_TEST(construction); CPPUNIT_TEST(encoding); CPPUNIT_TEST(always_noconv); CPPUNIT_TEST(max_length); CPPUNIT_TEST_SUITE_END(); public: virtual ~Test_codecvt_base() { } virtual void construction() { deletable_facet<cvt_t> cvt; deletable_facet<cvt_t> cvt2(1); deletable_facet<cvt_t> cvt3(2); static_assert(std::is_same<CHAR_T, typename cvt_t::intern_type>::value, "codecvt<> intern_type is invalid"); static_assert(std::is_same<char, typename cvt_t::extern_type>::value, "codecvt<> extern_type is invalid"); CPPUNIT_ASSERT(cvt.encoding() == 0); } virtual void encoding() { deletable_facet<cvt_t> cvt; CPPUNIT_ASSERT(cvt.encoding() == 0); } virtual void always_noconv() { deletable_facet<cvt_t> cvt; CPPUNIT_ASSERT(cvt.always_noconv() == false); } virtual void max_length() { deletable_facet<cvt_t> cvt; if (std::is_same<char16_t, CHAR_T>::value) CPPUNIT_ASSERT(cvt.max_length() == 4); else if (std::is_same<char32_t, CHAR_T>::value) CPPUNIT_ASSERT(cvt.max_length() == 6); } }; template <typename> class Test_codecvtx; template <template<class, class...> class CVT, typename CHAR_T, typename... OTHER> class Test_codecvtx<CVT<CHAR_T, OTHER...>> : public Test_codecvt_base<CVT<CHAR_T, OTHER...>> { public: typedef Test_codecvt_base<CVT<CHAR_T, OTHER...>> parent; CPPUNIT_TEST_SUB_SUITE(Test_codecvtx, parent); CPPUNIT_TEST(foo); CPPUNIT_TEST_SUITE_END(); void foo() { } }; typedef std::codecvt<char16_t, char, std::mbstate_t> foo; CPPUNIT_TEST_SUITE_REGISTRATION(Test_codecvtx<foo>); <commit_msg>deleted experiment<commit_after>#include "../codecvt/codecvt_specializations.h" #include "../codecvt/utf_conversion_helpers.h" #include <cstring> #include "cppunit-header.h" #include "multistring.h" // utility wrapper to adapt locale-bound facets for wstring/wbuffer convert template<class Facet> class deletable_facet : public Facet { public: template<class ...Args> deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {} ~deletable_facet() {} }; // Primary declaration template <typename> class Test_codecvt_base; template <template<class, class...> class CVT, typename CHAR_T, typename... OTHER> class Test_codecvt_base<CVT<CHAR_T, OTHER...>> : public CppUnit::TestFixture { public: typedef CVT<CHAR_T, OTHER...> cvt_t; CPPUNIT_TEST_SUITE(Test_codecvt_base); CPPUNIT_TEST(construction); CPPUNIT_TEST(encoding); CPPUNIT_TEST(always_noconv); CPPUNIT_TEST(max_length); CPPUNIT_TEST_SUITE_END(); public: virtual ~Test_codecvt_base() { } virtual void construction() { deletable_facet<cvt_t> cvt; deletable_facet<cvt_t> cvt2(1); deletable_facet<cvt_t> cvt3(2); static_assert(std::is_same<CHAR_T, typename cvt_t::intern_type>::value, "codecvt<> intern_type is invalid"); static_assert(std::is_same<char, typename cvt_t::extern_type>::value, "codecvt<> extern_type is invalid"); CPPUNIT_ASSERT(cvt.encoding() == 0); } virtual void encoding() { deletable_facet<cvt_t> cvt; CPPUNIT_ASSERT(cvt.encoding() == 0); } virtual void always_noconv() { deletable_facet<cvt_t> cvt; CPPUNIT_ASSERT(cvt.always_noconv() == false); } virtual void max_length() { deletable_facet<cvt_t> cvt; if (std::is_same<char16_t, CHAR_T>::value) CPPUNIT_ASSERT(cvt.max_length() == 4); else if (std::is_same<char32_t, CHAR_T>::value) CPPUNIT_ASSERT(cvt.max_length() == 6); } }; <|endoftext|>
<commit_before>/** @file @brief a sample of BLS signature see https://github.com/herumi/bls @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <mcl/bn256.hpp> #if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11 #include <random> std::random_device g_rg; #else #include <cybozu/random_generator.hpp> cybozu::RandomGenerator g_rg; #endif using namespace mcl::bn256; void Hash(G1& P, const std::string& m) { Fp t; t.setMsg(m); BN::mapToG1(P, t); } int main(int argc, char *argv[]) { std::string m = argc == 1 ? "hello mcl" : argv[1]; // setup parameter bn256init(); G1 P(-1, 1); G2 Q; BN::mapToG2(Q, 1); // generate secret key and public key Fr s; s.setRand(g_rg); std::cout << "secret key " << s << std::endl; G2 pub; G2::mul(pub, Q, s); // pub = sQ std::cout << "public key " << pub << std::endl; // sign G1 sign; { G1 Hm; Hash(Hm, m); G1::mul(sign, Hm, s); // sign = s H(m) } std::cout << "msg " << m << std::endl; std::cout << "sign " << sign << std::endl; // verify { Fp12 e1, e2; G1 Hm; Hash(Hm, m); BN::pairing(e1, sign, Q); // e1 = e(sign, Q) BN::pairing(e2, Hm, pub); // e2 = e(Hm, sQ) std::cout << "verify " << (e1 == e2 ? "ok" : "ng") << std::endl; } } <commit_msg>P is not used<commit_after>/** @file @brief a sample of BLS signature see https://github.com/herumi/bls @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <mcl/bn256.hpp> #if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11 #include <random> std::random_device g_rg; #else #include <cybozu/random_generator.hpp> cybozu::RandomGenerator g_rg; #endif using namespace mcl::bn256; void Hash(G1& P, const std::string& m) { Fp t; t.setMsg(m); BN::mapToG1(P, t); } int main(int argc, char *argv[]) { std::string m = argc == 1 ? "hello mcl" : argv[1]; // setup parameter bn256init(); G2 Q; BN::mapToG2(Q, 1); // generate secret key and public key Fr s; s.setRand(g_rg); std::cout << "secret key " << s << std::endl; G2 pub; G2::mul(pub, Q, s); // pub = sQ std::cout << "public key " << pub << std::endl; // sign G1 sign; { G1 Hm; Hash(Hm, m); G1::mul(sign, Hm, s); // sign = s H(m) } std::cout << "msg " << m << std::endl; std::cout << "sign " << sign << std::endl; // verify { Fp12 e1, e2; G1 Hm; Hash(Hm, m); BN::pairing(e1, sign, Q); // e1 = e(sign, Q) BN::pairing(e2, Hm, pub); // e2 = e(Hm, sQ) std::cout << "verify " << (e1 == e2 ? "ok" : "ng") << std::endl; } } <|endoftext|>