commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
b272ebfd9dce41c0875a4bfd53c69ed1685459c5
plugins/single_plugins/workspace_viewport_implementation.cpp
plugins/single_plugins/workspace_viewport_implementation.cpp
#include <output.hpp> #include <core.hpp> #include <signal_definitions.hpp> #include <pixman-1/pixman.h> class viewport_manager : public workspace_manager { private: int vwidth, vheight, vx, vy; wayfire_output *output; weston_layer panel_layer, normal_layer, background_layer; struct { int top_padding; int bot_padding; int left_padding; int right_padding; } workarea; public: void init(wayfire_output *output); void view_bring_to_front(wayfire_view view); void view_removed(wayfire_view view); void for_each_view(view_callback_proc_t call); void for_each_view_reverse(view_callback_proc_t call); std::vector<wayfire_view> get_views_on_workspace(std::tuple<int, int>); void set_workspace(std::tuple<int, int>); std::tuple<int, int> get_current_workspace(); std::tuple<int, int> get_workspace_grid_size(); void texture_from_workspace(std::tuple<int, int> vp, GLuint &fbuff, GLuint &tex); void add_background(wayfire_view background, int x, int y); void add_panel(wayfire_view panel); void reserve_workarea(wayfire_shell_panel_position position, uint32_t width, uint32_t height); void configure_panel(wayfire_view view, int x, int y); wayfire_geometry get_workarea(); }; /* Start viewport_manager */ void viewport_manager::init(wayfire_output *o) { output = o; vx = vy = 0; weston_layer_init(&normal_layer, core->ec); weston_layer_init(&panel_layer, core->ec); weston_layer_init(&background_layer, core->ec); weston_layer_set_position(&normal_layer, WESTON_LAYER_POSITION_NORMAL); weston_layer_set_position(&panel_layer, WESTON_LAYER_POSITION_TOP_UI); weston_layer_set_position(&background_layer, WESTON_LAYER_POSITION_BACKGROUND); vwidth = core->vwidth; vheight = core->vheight; } void viewport_manager::view_bring_to_front(wayfire_view view) { debug << "view bring_to_front" << view->desktop_surface << std::endl; if (view->handle->layer_link.layer == NULL) weston_layer_entry_insert(&normal_layer.view_list, &view->handle->layer_link); } void viewport_manager::view_removed(wayfire_view view) { debug << "view removed" << view->desktop_surface << std::endl; if (view->handle->layer_link.layer) weston_layer_entry_remove(&view->handle->layer_link); } void viewport_manager::for_each_view(view_callback_proc_t call) { weston_view *view; wayfire_view v; wl_list_for_each(view, &normal_layer.view_list.link, layer_link.link) { if ((v = core->find_view(view))) call(v); } } void viewport_manager::for_each_view_reverse(view_callback_proc_t call) { weston_view *view; wayfire_view v; wl_list_for_each_reverse(view, &normal_layer.view_list.link, layer_link.link) { if ((v = core->find_view(view))) call(v); } } std::tuple<int, int> viewport_manager::get_current_workspace() { return std::make_tuple(vx, vy); } std::tuple<int, int> viewport_manager::get_workspace_grid_size() { return std::make_tuple(vwidth, vheight); } void viewport_manager::set_workspace(std::tuple<int, int> nPos) { GetTuple(nx, ny, nPos); if(nx >= vwidth || ny >= vheight || nx < 0 || ny < 0) return; if (nx == vx && ny == vy) { auto views = get_views_on_workspace({vx, vy}); if (views.size() >= 1) output->focus_view(views[0], core->get_current_seat()); return; } auto dx = (vx - nx) * output->handle->width; auto dy = (vy - ny) * output->handle->height; for_each_view([=] (wayfire_view v) { v->move(v->geometry.origin.x + dx, v->geometry.origin.y + dy); }); weston_output_schedule_repaint(output->handle); change_viewport_signal data; data.old_vx = vx; data.old_vy = vy; data.new_vx = nx; data.new_vy = ny; vx = nx; vy = ny; output->signal->emit_signal("viewport-changed", &data); output->focus_view(nullptr, core->get_current_seat()); /* we iterate through views on current viewport from bottom to top * that way we ensure that they will be focused befor all others */ auto views = get_views_on_workspace({vx, vy}); auto it = views.rbegin(); while(it != views.rend()) { output->focus_view(*it, core->get_current_seat()); ++it; } } std::vector<wayfire_view> viewport_manager::get_views_on_workspace(std::tuple<int, int> vp) { GetTuple(tx, ty, vp); wayfire_geometry g; g.origin = {(tx - vx) * output->handle->width, (ty - vy) * (output->handle->height)}; g.size = {output->handle->width, output->handle->height}; std::vector<wayfire_view> ret; for_each_view([&ret, g] (wayfire_view view) { if (rect_inside(g, view->geometry)) { ret.push_back(view); } }); return ret; } void viewport_manager::texture_from_workspace(std::tuple<int, int> vp, GLuint &fbuff, GLuint &tex) { OpenGL::bind_context(output->render->ctx); if (fbuff == (uint)-1 || tex == (uint)-1) OpenGL::prepare_framebuffer(fbuff, tex); pixman_region32_t full_region; pixman_region32_init_rect(&full_region, 0, 0, output->handle->width, output->handle->height); output->render->blit_background(fbuff, &full_region); GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbuff)); GetTuple(x, y, vp); GetTuple(cx, cy, get_current_workspace()); int dx = (cx - x) * output->handle->width, dy = (cy - y) * output->handle->height; wayfire_geometry output_rect = { .origin = {-dx, -dy}, .size = {output->handle->width, output->handle->height} }; for_each_view_reverse([=] (wayfire_view v) { /* TODO: check if it really is visible */ if (rect_inside(output_rect, v->geometry)) { v->geometry.origin.x += dx; v->geometry.origin.y += dy; v->render(0); v->geometry.origin.x -= dx; v->geometry.origin.y -= dy; } }); GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0)); } void viewport_manager::add_background(wayfire_view background, int x, int y) { background->move(x, y); output->detach_view(background); weston_layer_entry_insert(&background_layer.view_list, &background->handle->layer_link); background->is_special = true; } void viewport_manager::add_panel(wayfire_view panel) { /* views have first been created as desktop views, * so they are currently in the normal layer, we must remove them first */ output->detach_view(panel); weston_layer_entry_insert(&panel_layer.view_list, &panel->handle->layer_link); panel->is_special = true; } void viewport_manager::reserve_workarea(wayfire_shell_panel_position position, uint32_t width, uint32_t height) { switch(position) { case WAYFIRE_SHELL_PANEL_POSITION_LEFT: workarea.left_padding = width; break; case WAYFIRE_SHELL_PANEL_POSITION_RIGHT: workarea.right_padding = width; break; case WAYFIRE_SHELL_PANEL_POSITION_UP: workarea.top_padding = height; break; case WAYFIRE_SHELL_PANEL_POSITION_DOWN: workarea.bot_padding = height; break; } } void viewport_manager::configure_panel(wayfire_view view, int x, int y) { view->move(x, y); } wayfire_geometry viewport_manager::get_workarea() { return { .origin = {workarea.left_padding, workarea.top_padding}, .size = {output->handle->width - workarea.left_padding - workarea.right_padding, output->handle->height - workarea.top_padding - workarea.bot_padding} }; } class viewport_impl_plugin : public wayfire_plugin_t { void init(wayfire_config *config) { output->workspace = new viewport_manager(); output->workspace->init(output); } }; extern "C" { wayfire_plugin_t *newInstance() { return new viewport_impl_plugin(); } }
#include <output.hpp> #include <core.hpp> #include <signal_definitions.hpp> #include <pixman-1/pixman.h> class viewport_manager : public workspace_manager { private: int vwidth, vheight, vx, vy; wayfire_output *output; weston_layer panel_layer, normal_layer, background_layer; struct { int top_padding; int bot_padding; int left_padding; int right_padding; } workarea; public: void init(wayfire_output *output); void view_bring_to_front(wayfire_view view); void view_removed(wayfire_view view); void for_each_view(view_callback_proc_t call); void for_each_view_reverse(view_callback_proc_t call); std::vector<wayfire_view> get_views_on_workspace(std::tuple<int, int>); void set_workspace(std::tuple<int, int>); std::tuple<int, int> get_current_workspace(); std::tuple<int, int> get_workspace_grid_size(); void texture_from_workspace(std::tuple<int, int> vp, GLuint &fbuff, GLuint &tex); void add_background(wayfire_view background, int x, int y); void add_panel(wayfire_view panel); void reserve_workarea(wayfire_shell_panel_position position, uint32_t width, uint32_t height); void configure_panel(wayfire_view view, int x, int y); wayfire_geometry get_workarea(); }; /* Start viewport_manager */ void viewport_manager::init(wayfire_output *o) { output = o; vx = vy = 0; weston_layer_init(&normal_layer, core->ec); weston_layer_init(&panel_layer, core->ec); weston_layer_init(&background_layer, core->ec); weston_layer_set_position(&normal_layer, WESTON_LAYER_POSITION_NORMAL); weston_layer_set_position(&panel_layer, WESTON_LAYER_POSITION_TOP_UI); weston_layer_set_position(&background_layer, WESTON_LAYER_POSITION_BACKGROUND); vwidth = core->vwidth; vheight = core->vheight; } void viewport_manager::view_bring_to_front(wayfire_view view) { debug << "view bring_to_front" << view->desktop_surface << std::endl; if (view->handle->layer_link.layer == NULL) weston_layer_entry_insert(&normal_layer.view_list, &view->handle->layer_link); } void viewport_manager::view_removed(wayfire_view view) { debug << "view removed" << view->desktop_surface << std::endl; if (view->handle->layer_link.layer) weston_layer_entry_remove(&view->handle->layer_link); } void viewport_manager::for_each_view(view_callback_proc_t call) { weston_view *view; wayfire_view v; wl_list_for_each(view, &normal_layer.view_list.link, layer_link.link) { if ((v = core->find_view(view))) call(v); } } void viewport_manager::for_each_view_reverse(view_callback_proc_t call) { weston_view *view; wayfire_view v; wl_list_for_each_reverse(view, &normal_layer.view_list.link, layer_link.link) { if ((v = core->find_view(view))) call(v); } } std::tuple<int, int> viewport_manager::get_current_workspace() { return std::make_tuple(vx, vy); } std::tuple<int, int> viewport_manager::get_workspace_grid_size() { return std::make_tuple(vwidth, vheight); } void viewport_manager::set_workspace(std::tuple<int, int> nPos) { GetTuple(nx, ny, nPos); if(nx >= vwidth || ny >= vheight || nx < 0 || ny < 0) return; if (nx == vx && ny == vy) { auto views = get_views_on_workspace({vx, vy}); if (views.size() >= 1) output->focus_view(views[0], core->get_current_seat()); return; } auto dx = (vx - nx) * output->handle->width; auto dy = (vy - ny) * output->handle->height; for_each_view([=] (wayfire_view v) { v->move(v->geometry.origin.x + dx, v->geometry.origin.y + dy); }); weston_output_schedule_repaint(output->handle); change_viewport_signal data; data.old_vx = vx; data.old_vy = vy; data.new_vx = nx; data.new_vy = ny; vx = nx; vy = ny; output->signal->emit_signal("viewport-changed", &data); output->focus_view(nullptr, core->get_current_seat()); /* we iterate through views on current viewport from bottom to top * that way we ensure that they will be focused befor all others */ auto views = get_views_on_workspace({vx, vy}); auto it = views.rbegin(); while(it != views.rend()) { output->focus_view(*it, core->get_current_seat()); ++it; } } std::vector<wayfire_view> viewport_manager::get_views_on_workspace(std::tuple<int, int> vp) { GetTuple(tx, ty, vp); wayfire_geometry g; g.origin = {(tx - vx) * output->handle->width, (ty - vy) * (output->handle->height)}; g.size = {output->handle->width, output->handle->height}; std::vector<wayfire_view> ret; for_each_view([&ret, g] (wayfire_view view) { if (rect_inside(g, view->geometry)) { ret.push_back(view); } }); return ret; } void viewport_manager::texture_from_workspace(std::tuple<int, int> vp, GLuint &fbuff, GLuint &tex) { OpenGL::bind_context(output->render->ctx); if (fbuff == (uint)-1 || tex == (uint)-1) OpenGL::prepare_framebuffer(fbuff, tex); pixman_region32_t full_region; pixman_region32_init_rect(&full_region, 0, 0, output->handle->width, output->handle->height); output->render->blit_background(fbuff, &full_region); GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbuff)); GetTuple(x, y, vp); GetTuple(cx, cy, get_current_workspace()); int dx = (cx - x) * output->handle->width, dy = (cy - y) * output->handle->height; wayfire_geometry output_rect = { .origin = {-dx, -dy}, .size = {output->handle->width, output->handle->height} }; for_each_view_reverse([=] (wayfire_view v) { /* TODO: check if it really is visible */ if (rect_inside(output_rect, v->geometry)) { v->geometry.origin.x += dx; v->geometry.origin.y += dy; v->render(0); v->geometry.origin.x -= dx; v->geometry.origin.y -= dy; } }); GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0)); } void viewport_manager::add_background(wayfire_view background, int x, int y) { background->move(x, y); output->detach_view(background); weston_layer_entry_insert(&background_layer.view_list, &background->handle->layer_link); background->is_special = true; } void viewport_manager::add_panel(wayfire_view panel) { /* views have first been created as desktop views, * so they are currently in the normal layer, we must remove them first */ output->detach_view(panel); weston_layer_entry_insert(&panel_layer.view_list, &panel->handle->layer_link); panel->is_special = true; } void viewport_manager::reserve_workarea(wayfire_shell_panel_position position, uint32_t width, uint32_t height) { switch(position) { case WAYFIRE_SHELL_PANEL_POSITION_LEFT: workarea.left_padding = width; break; case WAYFIRE_SHELL_PANEL_POSITION_RIGHT: workarea.right_padding = width; break; case WAYFIRE_SHELL_PANEL_POSITION_UP: workarea.top_padding = height; break; case WAYFIRE_SHELL_PANEL_POSITION_DOWN: workarea.bot_padding = height; break; } } void viewport_manager::configure_panel(wayfire_view view, int x, int y) { view->move(x, y); } wayfire_geometry viewport_manager::get_workarea() { auto g = output->get_full_geometry(); return { .origin = {g.origin.x + workarea.left_padding, g.origin.y + workarea.top_padding}, .size = {g.size.w - workarea.left_padding - workarea.right_padding, g.size.h - workarea.top_padding - workarea.bot_padding} }; } class viewport_impl_plugin : public wayfire_plugin_t { void init(wayfire_config *config) { output->workspace = new viewport_manager(); output->workspace->init(output); } }; extern "C" { wayfire_plugin_t *newInstance() { return new viewport_impl_plugin(); } }
Fix workarea calculation
Fix workarea calculation
C++
mit
ammen99/wayfire,ammen99/wayfire
213c808d8d60e0d032effd1ac308b3144d908925
src/geom/IntersectionMatrix.cpp
src/geom/IntersectionMatrix.cpp
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/IntersectionMatrix.java rev. 1.18 * **********************************************************************/ #include <geos/geom/IntersectionMatrix.h> #include <geos/geom/Dimension.h> #include <geos/geom/Location.h> #include <geos/util/IllegalArgumentException.h> #include <sstream> #include <cassert> using namespace std; namespace geos { namespace geom { // geos::geom const int IntersectionMatrix::firstDim = 3; const int IntersectionMatrix::secondDim = 3; /*public*/ IntersectionMatrix::IntersectionMatrix() { //matrix = new int[3][3]; setAll(Dimension::False); } /*public*/ IntersectionMatrix::IntersectionMatrix(const string& elements) { setAll(Dimension::False); set(elements); } /*public*/ IntersectionMatrix::IntersectionMatrix(const IntersectionMatrix& other) { matrix = other.matrix; } /*public*/ void IntersectionMatrix::add(IntersectionMatrix* other) { for(size_t i = 0; i < firstDim; i++) { for(size_t j = 0; j < secondDim; j++) { setAtLeast(static_cast<Location>(i), static_cast<Location>(j), other->get(static_cast<Location>(i), static_cast<Location>(j))); } } } /*public*/ bool IntersectionMatrix::matches(const string& requiredDimensionSymbols) const { if(requiredDimensionSymbols.length() != 9) { ostringstream s; s << "IllegalArgumentException: Should be length 9, is " << "[" << requiredDimensionSymbols << "] instead" << endl; throw util::IllegalArgumentException(s.str()); } for(size_t ai = 0; ai < firstDim; ai++) { for(size_t bi = 0; bi < secondDim; bi++) { if(!matches(matrix[ai][bi], requiredDimensionSymbols[3 * ai + bi])) { return false; } } } return true; } /*public static*/ bool IntersectionMatrix::matches(int actualDimensionValue, char requiredDimensionSymbol) { if(requiredDimensionSymbol == '*') { return true; } if(requiredDimensionSymbol == 'T' && (actualDimensionValue >= 0 || actualDimensionValue == Dimension::True)) { return true; } if(requiredDimensionSymbol == 'F' && actualDimensionValue == Dimension::False) { return true; } if(requiredDimensionSymbol == '0' && actualDimensionValue == Dimension::P) { return true; } if(requiredDimensionSymbol == '1' && actualDimensionValue == Dimension::L) { return true; } if(requiredDimensionSymbol == '2' && actualDimensionValue == Dimension::A) { return true; } return false; } /*public static*/ bool IntersectionMatrix::matches(const string& actualDimensionSymbols, const string& requiredDimensionSymbols) { IntersectionMatrix m(actualDimensionSymbols); bool result = m.matches(requiredDimensionSymbols); return result; } /*public*/ void IntersectionMatrix::set(Location row, Location col, int dimensionValue) { matrix[static_cast<size_t>(row)][static_cast<size_t>(col)] = dimensionValue; } /*public*/ void IntersectionMatrix::set(const string& dimensionSymbols) { auto limit = dimensionSymbols.length(); for(size_t i = 0; i < limit; i++) { auto row = i / firstDim; auto col = i % secondDim; matrix[row][col] = Dimension::toDimensionValue(dimensionSymbols[i]); } } /*public*/ void IntersectionMatrix::setAtLeast(Location row, Location col, int minimumDimensionValue) { if(get(row, col) < minimumDimensionValue) { set(row, col, minimumDimensionValue); } } /*public*/ void IntersectionMatrix::setAtLeastIfValid(Location row, Location col, int minimumDimensionValue) { if(static_cast<size_t>(row) >= 0 && static_cast<size_t>(col) >= 0) { setAtLeast(row, col, minimumDimensionValue); } } /*public*/ void IntersectionMatrix::setAtLeast(string minimumDimensionSymbols) { auto limit = minimumDimensionSymbols.length(); for(size_t i = 0; i < limit; i++) { auto row = static_cast<Location>(i / firstDim); auto col = static_cast<Location>(i % secondDim); setAtLeast(row, col, Dimension::toDimensionValue(minimumDimensionSymbols[i])); } } /*public*/ void IntersectionMatrix::setAll(int dimensionValue) { for(int ai = 0; ai < firstDim; ai++) { for(int bi = 0; bi < secondDim; bi++) { set(static_cast<Location>(ai), static_cast<Location>(bi), dimensionValue); } } } /*public*/ bool IntersectionMatrix::isDisjoint() const { return get(Location::INTERIOR, Location::INTERIOR) == Dimension::False && get(Location::INTERIOR, Location::BOUNDARY) == Dimension::False && get(Location::BOUNDARY, Location::INTERIOR) == Dimension::False && get(Location::BOUNDARY, Location::BOUNDARY) == Dimension::False; } /*public*/ bool IntersectionMatrix::isIntersects() const { return !isDisjoint(); } /*public*/ bool IntersectionMatrix::isTouches(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if(dimensionOfGeometryA > dimensionOfGeometryB) { //no need to get transpose because pattern matrix is symmetrical return isTouches(dimensionOfGeometryB, dimensionOfGeometryA); } if((dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::L) || (dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::L)) { return get(Location::INTERIOR, Location::INTERIOR) == Dimension::False && (matches(get(Location::INTERIOR, Location::BOUNDARY), 'T') || matches(get(Location::BOUNDARY, Location::INTERIOR), 'T') || matches(get(Location::BOUNDARY, Location::BOUNDARY), 'T')); } return false; } /*public*/ bool IntersectionMatrix::isCrosses(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if((dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::L) || (dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::A)) { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && matches(get(Location::INTERIOR, Location::EXTERIOR), 'T'); } if((dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::P) || (dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::P) || (dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::L)) { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && matches(get(Location::EXTERIOR, Location::INTERIOR), 'T'); } if(dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::L) { return get(Location::INTERIOR, Location::INTERIOR) == 0; } return false; } /*public*/ bool IntersectionMatrix::isWithin() const { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && get(Location::INTERIOR, Location::EXTERIOR) == Dimension::False && get(Location::BOUNDARY, Location::EXTERIOR) == Dimension::False; } /*public*/ bool IntersectionMatrix::isContains() const { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && get(Location::EXTERIOR, Location::INTERIOR) == Dimension::False && get(Location::EXTERIOR, Location::BOUNDARY) == Dimension::False; } /*public*/ bool IntersectionMatrix::isEquals(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if(dimensionOfGeometryA != dimensionOfGeometryB) { return false; } return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && get(Location::EXTERIOR, Location::INTERIOR) == Dimension::False && get(Location::INTERIOR, Location::EXTERIOR) == Dimension::False && get(Location::EXTERIOR, Location::BOUNDARY) == Dimension::False && get(Location::BOUNDARY, Location::EXTERIOR) == Dimension::False; } /*public*/ bool IntersectionMatrix::isOverlaps(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if((dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::P) || (dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::A)) { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && matches(get(Location::INTERIOR, Location::EXTERIOR), 'T') && matches(get(Location::EXTERIOR, Location::INTERIOR), 'T'); } if(dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::L) { return get(Location::INTERIOR, Location::INTERIOR) == 1 && matches(get(Location::INTERIOR, Location::EXTERIOR), 'T') && matches(get(Location::EXTERIOR, Location::INTERIOR), 'T'); } return false; } /*public*/ bool IntersectionMatrix::isCovers() const { bool hasPointInCommon = matches(get(Location::INTERIOR, Location::INTERIOR), 'T') || matches(get(Location::INTERIOR, Location::BOUNDARY), 'T') || matches(get(Location::BOUNDARY, Location::INTERIOR), 'T') || matches(get(Location::BOUNDARY, Location::BOUNDARY), 'T'); return hasPointInCommon && get(Location::EXTERIOR, Location::INTERIOR) == Dimension::False && get(Location::EXTERIOR, Location::BOUNDARY) == Dimension::False; } /*public*/ bool IntersectionMatrix::isCoveredBy() const { bool hasPointInCommon = matches(get(Location::INTERIOR, Location::INTERIOR), 'T') || matches(get(Location::INTERIOR, Location::BOUNDARY), 'T') || matches(get(Location::BOUNDARY, Location::INTERIOR), 'T') || matches(get(Location::BOUNDARY, Location::BOUNDARY), 'T'); return hasPointInCommon && get(Location::INTERIOR, Location::EXTERIOR) == Dimension::False && get(Location::BOUNDARY, Location::EXTERIOR) == Dimension::False; } //Not sure IntersectionMatrix* IntersectionMatrix::transpose() { int temp = matrix[1][0]; matrix[1][0] = matrix[0][1]; matrix[0][1] = temp; temp = matrix[2][0]; matrix[2][0] = matrix[0][2]; matrix[0][2] = temp; temp = matrix[2][1]; matrix[2][1] = matrix[1][2]; matrix[1][2] = temp; return this; } /*public*/ string IntersectionMatrix::toString() const { string result(""); for(size_t ai = 0; ai < firstDim; ai++) { for(size_t bi = 0; bi < secondDim; bi++) { result += Dimension::toDimensionSymbol(matrix[ai][bi]); } } return result; } std::ostream& operator<< (std::ostream& os, const IntersectionMatrix& im) { return os << im.toString(); } } // namespace geos::geom } // namespace geos
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/IntersectionMatrix.java rev. 1.18 * **********************************************************************/ #include <geos/geom/IntersectionMatrix.h> #include <geos/geom/Dimension.h> #include <geos/geom/Location.h> #include <geos/util/IllegalArgumentException.h> #include <sstream> #include <cassert> using namespace std; namespace geos { namespace geom { // geos::geom const int IntersectionMatrix::firstDim = 3; const int IntersectionMatrix::secondDim = 3; /*public*/ IntersectionMatrix::IntersectionMatrix() { //matrix = new int[3][3]; setAll(Dimension::False); } /*public*/ IntersectionMatrix::IntersectionMatrix(const string& elements) { setAll(Dimension::False); set(elements); } /*public*/ IntersectionMatrix::IntersectionMatrix(const IntersectionMatrix& other) { matrix = other.matrix; } /*public*/ void IntersectionMatrix::add(IntersectionMatrix* other) { for(size_t i = 0; i < firstDim; i++) { for(size_t j = 0; j < secondDim; j++) { setAtLeast(static_cast<Location>(i), static_cast<Location>(j), other->get(static_cast<Location>(i), static_cast<Location>(j))); } } } /*public*/ bool IntersectionMatrix::matches(const string& requiredDimensionSymbols) const { if(requiredDimensionSymbols.length() != 9) { ostringstream s; s << "IllegalArgumentException: Should be length 9, is " << "[" << requiredDimensionSymbols << "] instead" << endl; throw util::IllegalArgumentException(s.str()); } for(size_t ai = 0; ai < firstDim; ai++) { for(size_t bi = 0; bi < secondDim; bi++) { if(!matches(matrix[ai][bi], requiredDimensionSymbols[3 * ai + bi])) { return false; } } } return true; } /*public static*/ bool IntersectionMatrix::matches(int actualDimensionValue, char requiredDimensionSymbol) { if(requiredDimensionSymbol == '*') { return true; } if(requiredDimensionSymbol == 'T' && (actualDimensionValue >= 0 || actualDimensionValue == Dimension::True)) { return true; } if(requiredDimensionSymbol == 'F' && actualDimensionValue == Dimension::False) { return true; } if(requiredDimensionSymbol == '0' && actualDimensionValue == Dimension::P) { return true; } if(requiredDimensionSymbol == '1' && actualDimensionValue == Dimension::L) { return true; } if(requiredDimensionSymbol == '2' && actualDimensionValue == Dimension::A) { return true; } return false; } /*public static*/ bool IntersectionMatrix::matches(const string& actualDimensionSymbols, const string& requiredDimensionSymbols) { IntersectionMatrix m(actualDimensionSymbols); bool result = m.matches(requiredDimensionSymbols); return result; } /*public*/ void IntersectionMatrix::set(Location row, Location col, int dimensionValue) { matrix[static_cast<size_t>(row)][static_cast<size_t>(col)] = dimensionValue; } /*public*/ void IntersectionMatrix::set(const string& dimensionSymbols) { auto limit = dimensionSymbols.length(); for(size_t i = 0; i < limit; i++) { auto row = i / firstDim; auto col = i % secondDim; matrix[row][col] = Dimension::toDimensionValue(dimensionSymbols[i]); } } /*public*/ void IntersectionMatrix::setAtLeast(Location row, Location col, int minimumDimensionValue) { if(get(row, col) < minimumDimensionValue) { set(row, col, minimumDimensionValue); } } /*public*/ void IntersectionMatrix::setAtLeastIfValid(Location row, Location col, int minimumDimensionValue) { if(row != Location::UNDEF && col != Location::UNDEF) { setAtLeast(row, col, minimumDimensionValue); } } /*public*/ void IntersectionMatrix::setAtLeast(string minimumDimensionSymbols) { auto limit = minimumDimensionSymbols.length(); for(size_t i = 0; i < limit; i++) { auto row = static_cast<Location>(i / firstDim); auto col = static_cast<Location>(i % secondDim); setAtLeast(row, col, Dimension::toDimensionValue(minimumDimensionSymbols[i])); } } /*public*/ void IntersectionMatrix::setAll(int dimensionValue) { for(int ai = 0; ai < firstDim; ai++) { for(int bi = 0; bi < secondDim; bi++) { set(static_cast<Location>(ai), static_cast<Location>(bi), dimensionValue); } } } /*public*/ bool IntersectionMatrix::isDisjoint() const { return get(Location::INTERIOR, Location::INTERIOR) == Dimension::False && get(Location::INTERIOR, Location::BOUNDARY) == Dimension::False && get(Location::BOUNDARY, Location::INTERIOR) == Dimension::False && get(Location::BOUNDARY, Location::BOUNDARY) == Dimension::False; } /*public*/ bool IntersectionMatrix::isIntersects() const { return !isDisjoint(); } /*public*/ bool IntersectionMatrix::isTouches(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if(dimensionOfGeometryA > dimensionOfGeometryB) { //no need to get transpose because pattern matrix is symmetrical return isTouches(dimensionOfGeometryB, dimensionOfGeometryA); } if((dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::L) || (dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::L)) { return get(Location::INTERIOR, Location::INTERIOR) == Dimension::False && (matches(get(Location::INTERIOR, Location::BOUNDARY), 'T') || matches(get(Location::BOUNDARY, Location::INTERIOR), 'T') || matches(get(Location::BOUNDARY, Location::BOUNDARY), 'T')); } return false; } /*public*/ bool IntersectionMatrix::isCrosses(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if((dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::L) || (dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::A) || (dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::A)) { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && matches(get(Location::INTERIOR, Location::EXTERIOR), 'T'); } if((dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::P) || (dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::P) || (dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::L)) { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && matches(get(Location::EXTERIOR, Location::INTERIOR), 'T'); } if(dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::L) { return get(Location::INTERIOR, Location::INTERIOR) == 0; } return false; } /*public*/ bool IntersectionMatrix::isWithin() const { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && get(Location::INTERIOR, Location::EXTERIOR) == Dimension::False && get(Location::BOUNDARY, Location::EXTERIOR) == Dimension::False; } /*public*/ bool IntersectionMatrix::isContains() const { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && get(Location::EXTERIOR, Location::INTERIOR) == Dimension::False && get(Location::EXTERIOR, Location::BOUNDARY) == Dimension::False; } /*public*/ bool IntersectionMatrix::isEquals(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if(dimensionOfGeometryA != dimensionOfGeometryB) { return false; } return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && get(Location::EXTERIOR, Location::INTERIOR) == Dimension::False && get(Location::INTERIOR, Location::EXTERIOR) == Dimension::False && get(Location::EXTERIOR, Location::BOUNDARY) == Dimension::False && get(Location::BOUNDARY, Location::EXTERIOR) == Dimension::False; } /*public*/ bool IntersectionMatrix::isOverlaps(int dimensionOfGeometryA, int dimensionOfGeometryB) const { if((dimensionOfGeometryA == Dimension::P && dimensionOfGeometryB == Dimension::P) || (dimensionOfGeometryA == Dimension::A && dimensionOfGeometryB == Dimension::A)) { return matches(get(Location::INTERIOR, Location::INTERIOR), 'T') && matches(get(Location::INTERIOR, Location::EXTERIOR), 'T') && matches(get(Location::EXTERIOR, Location::INTERIOR), 'T'); } if(dimensionOfGeometryA == Dimension::L && dimensionOfGeometryB == Dimension::L) { return get(Location::INTERIOR, Location::INTERIOR) == 1 && matches(get(Location::INTERIOR, Location::EXTERIOR), 'T') && matches(get(Location::EXTERIOR, Location::INTERIOR), 'T'); } return false; } /*public*/ bool IntersectionMatrix::isCovers() const { bool hasPointInCommon = matches(get(Location::INTERIOR, Location::INTERIOR), 'T') || matches(get(Location::INTERIOR, Location::BOUNDARY), 'T') || matches(get(Location::BOUNDARY, Location::INTERIOR), 'T') || matches(get(Location::BOUNDARY, Location::BOUNDARY), 'T'); return hasPointInCommon && get(Location::EXTERIOR, Location::INTERIOR) == Dimension::False && get(Location::EXTERIOR, Location::BOUNDARY) == Dimension::False; } /*public*/ bool IntersectionMatrix::isCoveredBy() const { bool hasPointInCommon = matches(get(Location::INTERIOR, Location::INTERIOR), 'T') || matches(get(Location::INTERIOR, Location::BOUNDARY), 'T') || matches(get(Location::BOUNDARY, Location::INTERIOR), 'T') || matches(get(Location::BOUNDARY, Location::BOUNDARY), 'T'); return hasPointInCommon && get(Location::INTERIOR, Location::EXTERIOR) == Dimension::False && get(Location::BOUNDARY, Location::EXTERIOR) == Dimension::False; } //Not sure IntersectionMatrix* IntersectionMatrix::transpose() { int temp = matrix[1][0]; matrix[1][0] = matrix[0][1]; matrix[0][1] = temp; temp = matrix[2][0]; matrix[2][0] = matrix[0][2]; matrix[0][2] = temp; temp = matrix[2][1]; matrix[2][1] = matrix[1][2]; matrix[1][2] = temp; return this; } /*public*/ string IntersectionMatrix::toString() const { string result(""); for(size_t ai = 0; ai < firstDim; ai++) { for(size_t bi = 0; bi < secondDim; bi++) { result += Dimension::toDimensionSymbol(matrix[ai][bi]); } } return result; } std::ostream& operator<< (std::ostream& os, const IntersectionMatrix& im) { return os << im.toString(); } } // namespace geos::geom } // namespace geos
Fix always-true conditional
Fix always-true conditional
C++
lgpl-2.1
libgeos/libgeos,libgeos/libgeos,libgeos/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,mwtoews/libgeos
942fb18245e7a8ab10558972bce27e2fa1b395aa
macros/loadlibs.C
macros/loadlibs.C
void loadlibs () { gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern"); gSystem->Load("$(ROOTSYS)/lib/libPhysics"); gSystem->Load("$(ROOTSYS)/lib/libEG"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTGeant3Dummy"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummyhijing"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTHijing"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummypythia6"); gSystem->Load("$(ROOTSYS)/lib/libEGPythia6"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCONTAINERS"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libEVGEN"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRALICE"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libFMD"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libMUON"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPHOS"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPMD"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRICH"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTRUCT"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTOF"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTRD"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libZDC"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libITS"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCASTOR"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTART"); }
void loadlibs () { gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern"); gSystem->Load("$(ROOTSYS)/lib/libPhysics"); gSystem->Load("$(ROOTSYS)/lib/libEG"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTGeant3Dummy"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummyhijing"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTHijing"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummypythia6"); gSystem->Load("$(ROOTSYS)/lib/libEGPythia6"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCONTAINERS"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummymevsim"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTMevSim"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libEVGEN"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRALICE"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libFMD"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libMUON"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPHOS"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPMD"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRICH"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTRUCT"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTOF"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTRD"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libZDC"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libITS"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCASTOR"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTART"); }
Update with mevsim libraries.
Update with mevsim libraries.
C++
bsd-3-clause
miranov25/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,alisw/AliRoot,alisw/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,alisw/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,miranov25/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot
1237a4c11679685808a677593e261e21b950749a
techlibs/xilinx/synth_xilinx.cc
techlibs/xilinx/synth_xilinx.cc
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN #define XC7_WIRE_DELAY "300" // Number with which ABC will map a 6-input gate // to one LUT6 (instead of a LUT5 + LUT2) struct SynthXilinxPass : public ScriptPass { SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -family {xcup|xcu|xc7|xc6s}\n"); log(" run synthesis for the specified Xilinx architecture\n"); log(" generate the synthesis netlist for the specified family.\n"); log(" default: xc7\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nocarry\n"); log(" disable inference of carry chains\n"); log("\n"); log(" -nobram\n"); log(" disable inference of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable inference of distributed rams\n"); log("\n"); log(" -nosrl\n"); log(" disable inference of shift registers\n"); log("\n"); log(" -nocarry\n"); log(" do not use XORCY/MUXCY/CARRY4 cells in output netlist\n"); log("\n"); log(" -nowidelut\n"); log(" do not use MUXF[78] resources to implement LUTs larger than LUT6s\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use new ABC9 flow (EXPERIMENTAL)\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } std::string top_opt, edif_file, blif_file, family; bool flatten, retime, vpr, nobram, nodram, nosrl, nocarry, nowidelut, abc9; void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; edif_file.clear(); blif_file.clear(); family = "xc7"; flatten = false; retime = false; vpr = false; nocarry = false; nobram = false; nodram = false; nosrl = false; nocarry = false; nowidelut = false; abc9 = false; } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if ((args[argidx] == "-family" || args[argidx] == "-arch") && argidx+1 < args.size()) { family = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nowidelut") { nowidelut = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-nosrl") { nosrl = true; continue; } if (args[argidx] == "-abc9") { abc9 = true; continue; } break; } extra_args(args, argidx, design); if (family != "xcup" && family != "xcu" && family != "xc7" && family != "xc6s") log_cmd_error("Invalid Xilinx -family setting: %s\n", family.c_str()); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("begin")) { if (vpr) run("read_verilog -lib -D _ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); else run("read_verilog -lib -D _ABC +/xilinx/cells_sim.v"); run("read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram || help_mode) run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')"); run(stringf("hierarchy -check %s", top_opt.c_str())); } if (check_label("flatten", "(with '-flatten' only)")) { if (flatten || help_mode) { run("proc"); run("flatten"); } } if (check_label("coarse")) { run("synth -run coarse"); // shregmap -tech xilinx can cope with $shiftx and $mux // cells for identifying variable-length shift registers, // so attempt to convert $pmux-es to the former if (!nosrl || help_mode) run("pmux2shiftx", "(skip if '-nosrl')"); // Run a number of peephole optimisations, including one // that optimises $mul cells driving $shiftx's B input // and that aids wide mux analysis run("peepopt"); } if (check_label("bram", "(skip if '-nobram')")) { if (!nobram || help_mode) { run("memory_bram -rules +/xilinx/brams.txt"); run("techmap -map +/xilinx/brams_map.v"); } } if (check_label("dram", "(skip if '-nodram')")) { if (!nodram || help_mode) { run("memory_bram -rules +/xilinx/drams.txt"); run("techmap -map +/xilinx/drams_map.v"); } } if (check_label("fine")) { run("opt -fast -full"); run("memory_map"); run("dffsr2dff"); run("dff2dffe"); run("opt -full"); if (!nosrl || help_mode) { // shregmap operates on bit-level flops, not word-level, // so break those down here run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')"); // shregmap with '-tech xilinx' infers variable length shift regs run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')"); } std::string techmap_files = " -map +/techmap.v"; if (help_mode) techmap_files += " [-map +/xilinx/arith_map.v]"; else if (!nocarry) { techmap_files += " -map +/xilinx/arith_map.v"; if (vpr) techmap_files += " -D _EXPLICIT_CARRY"; else if (abc9) techmap_files += " -D _CLB_CARRY"; } run("techmap " + techmap_files); run("opt -fast"); } if (check_label("map_cells")) { run("techmap -map +/techmap.v -map +/xilinx/cells_map.v"); run("clean"); } if (check_label("map_luts")) { run("opt_expr -mux_undef"); if (help_mode) run("abc -luts 2:2,3,6:5[,10,20] [-dff]", "(skip if 'nowidelut', only for '-retime')"); else if (abc9) { if (nowidelut) run("abc9 -lut +/xilinx/abc_xc7_nowide.lut -box +/xilinx/abc_xc7.box -W " + std::string(XC7_WIRE_DELAY) + string(retime ? " -dff" : "")); else run("abc9 -lut +/xilinx/abc_xc7.lut -box +/xilinx/abc_xc7.box -W " + std::string(XC7_WIRE_DELAY) + string(retime ? " -dff" : "")); } else { if (nowidelut) run("abc -luts 2:2,3,6:5" + string(retime ? " -dff" : "")); else run("abc -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : "")); } run("clean"); // This shregmap call infers fixed length shift registers after abc // has performed any necessary retiming if (!nosrl || help_mode) run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')"); run("techmap -map +/xilinx/lut_map.v -map +/xilinx/ff_map.v -map +/xilinx/cells_map.v"); run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat -tech xilinx"); run("check -noinit"); } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) run(stringf("write_blif %s", edif_file.c_str())); } } } SynthXilinxPass; PRIVATE_NAMESPACE_END
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN #define XC7_WIRE_DELAY "300" // Number with which ABC will map a 6-input gate // to one LUT6 (instead of a LUT5 + LUT2) struct SynthXilinxPass : public ScriptPass { SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -family {xcup|xcu|xc7|xc6s}\n"); log(" run synthesis for the specified Xilinx architecture\n"); log(" generate the synthesis netlist for the specified family.\n"); log(" default: xc7\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nocarry\n"); log(" disable inference of carry chains\n"); log("\n"); log(" -nobram\n"); log(" disable inference of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable inference of distributed rams\n"); log("\n"); log(" -nosrl\n"); log(" disable inference of shift registers\n"); log("\n"); log(" -nocarry\n"); log(" do not use XORCY/MUXCY/CARRY4 cells in output netlist\n"); log("\n"); log(" -nowidelut\n"); log(" do not use MUXF[78] resources to implement LUTs larger than LUT6s\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use new ABC9 flow (EXPERIMENTAL)\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } std::string top_opt, edif_file, blif_file, family; bool flatten, retime, vpr, nobram, nodram, nosrl, nocarry, nowidelut, abc9; void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; edif_file.clear(); blif_file.clear(); family = "xc7"; flatten = false; retime = false; vpr = false; nocarry = false; nobram = false; nodram = false; nosrl = false; nocarry = false; nowidelut = false; abc9 = false; } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if ((args[argidx] == "-family" || args[argidx] == "-arch") && argidx+1 < args.size()) { family = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nowidelut") { nowidelut = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-nosrl") { nosrl = true; continue; } if (args[argidx] == "-abc9") { abc9 = true; continue; } break; } extra_args(args, argidx, design); if (family != "xcup" && family != "xcu" && family != "xc7" && family != "xc6s") log_cmd_error("Invalid Xilinx -family setting: %s\n", family.c_str()); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("begin")) { if (vpr) run("read_verilog -lib -D _ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); else run("read_verilog -lib -D _ABC +/xilinx/cells_sim.v"); run("read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram || help_mode) run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')"); run(stringf("hierarchy -check %s", top_opt.c_str())); } if (check_label("flatten", "(with '-flatten' only)")) { if (flatten || help_mode) { run("proc"); run("flatten"); } } if (check_label("coarse")) { run("synth -run coarse"); // shregmap -tech xilinx can cope with $shiftx and $mux // cells for identifying variable-length shift registers, // so attempt to convert $pmux-es to the former if (!nosrl || help_mode) run("pmux2shiftx", "(skip if '-nosrl')"); // Run a number of peephole optimisations, including one // that optimises $mul cells driving $shiftx's B input // and that aids wide mux analysis run("peepopt"); } if (check_label("bram", "(skip if '-nobram')")) { if (!nobram || help_mode) { run("memory_bram -rules +/xilinx/brams.txt"); run("techmap -map +/xilinx/brams_map.v"); } } if (check_label("dram", "(skip if '-nodram')")) { if (!nodram || help_mode) { run("memory_bram -rules +/xilinx/drams.txt"); run("techmap -map +/xilinx/drams_map.v"); } } if (check_label("fine")) { run("opt -fast -full"); run("memory_map"); run("dffsr2dff"); run("dff2dffe"); run("opt -full"); if (!nosrl || help_mode) { // shregmap operates on bit-level flops, not word-level, // so break those down here run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')"); // shregmap with '-tech xilinx' infers variable length shift regs run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')"); } std::string techmap_files = " -map +/techmap.v"; if (help_mode) techmap_files += " [-map +/xilinx/arith_map.v]"; else if (!nocarry) { techmap_files += " -map +/xilinx/arith_map.v"; if (vpr) techmap_files += " -D _EXPLICIT_CARRY"; else if (abc9) techmap_files += " -D _CLB_CARRY"; } run("techmap " + techmap_files); run("opt -fast"); } if (check_label("map_cells")) { run("techmap -map +/techmap.v -map +/xilinx/cells_map.v"); run("clean"); } if (check_label("map_luts")) { run("opt_expr -mux_undef"); if (help_mode) run("abc -luts 2:2,3,6:5[,10,20] [-dff]", "(skip if 'nowidelut', only for '-retime')"); else if (abc9) { if (family != "xc7") log_warning("'synth_xilinx -abc9' currently supports '-family xc7' only.\n"); if (nowidelut) run("abc9 -lut +/xilinx/abc_xc7_nowide.lut -box +/xilinx/abc_xc7.box -W " + std::string(XC7_WIRE_DELAY) + string(retime ? " -dff" : "")); else run("abc9 -lut +/xilinx/abc_xc7.lut -box +/xilinx/abc_xc7.box -W " + std::string(XC7_WIRE_DELAY) + string(retime ? " -dff" : "")); } else { if (nowidelut) run("abc -luts 2:2,3,6:5" + string(retime ? " -dff" : "")); else run("abc -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : "")); } run("clean"); // This shregmap call infers fixed length shift registers after abc // has performed any necessary retiming if (!nosrl || help_mode) run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')"); run("techmap -map +/xilinx/lut_map.v -map +/xilinx/ff_map.v -map +/xilinx/cells_map.v"); run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat -tech xilinx"); run("check -noinit"); } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) run(stringf("write_blif %s", edif_file.c_str())); } } } SynthXilinxPass; PRIVATE_NAMESPACE_END
Add warning if synth_xilinx -abc9 with family != xc7
Add warning if synth_xilinx -abc9 with family != xc7
C++
isc
YosysHQ/yosys,SymbiFlow/yosys,SymbiFlow/yosys,cliffordwolf/yosys,antmicro/yosys,cliffordwolf/yosys,SymbiFlow/yosys,YosysHQ/yosys,cliffordwolf/yosys,YosysHQ/yosys,antmicro/yosys,antmicro/yosys,SymbiFlow/yosys,cliffordwolf/yosys,antmicro/yosys,cliffordwolf/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,SymbiFlow/yosys,cliffordwolf/yosys,antmicro/yosys,SymbiFlow/yosys,YosysHQ/yosys,cliffordwolf/yosys,cliffordwolf/yosys,YosysHQ/yosys,antmicro/yosys,antmicro/yosys,antmicro/yosys,cliffordwolf/yosys,SymbiFlow/yosys,SymbiFlow/yosys
16584ab7b1b4fae9bd66bf12fb89593c5daee35d
b9disassemble/b9disassemble.cpp
b9disassemble/b9disassemble.cpp
#include <iostream> #include <iterator> #include <string.h> /* Parse uint32 */ uint32_t uint32Parser(std::istream &in, std::uint32_t &out) { in.read((char *)&out, sizeof(out)); std::cout << "The uint32_t value is: " << out << std::endl; if (sizeof(out) != 4) { std::cout << "Incorrect size of uint32_t" << std::endl; return false; } else { return true; } } /* Read header "b9module" from module */ bool parseHeader(std::istream &in) { char buffer[8]; in.read(buffer, 8); auto gcount = in.gcount(); if (gcount != 8) return false; if (0 != strncmp("b9module", buffer, gcount)) return false; // TODO Set header in Module return true; } /* Read Section Code */ bool parseSectionCode(std::istream &in) { uint32_t sectionCode; if (!uint32Parser(in, sectionCode)) { return false; } if (sectionCode != 1) { std::cout << "Incorrect section code" << std::endl; return false; } std::cout << "Section Code: " << sectionCode << std::endl; // TODO Set section code in Module return true; } /* Read Function Count */ bool parseFunctionCount(std::istream &in) { uint32_t functionCount; if (!uint32Parser(in, functionCount)) { return false; } std::cout << "Function count: " << functionCount << std::endl; // TODO Set function count in module return true; } /* Disassemble Binary Module */ bool disassemble(std::istream &in, std::ostream &out) { // Read header if (parseHeader(in)) { std::cout << "Success in parseHeader" << std::endl; } else { std::cout << "Failure in parseHeader" << std::endl; return false; } // Read section code if (parseSectionCode(in)) { std::cout << "Success in parseSectionCode" << std::endl; } else { std::cout << "Failure in parseSectionCode" << std::endl; return false; } // Read function count parseFunctionCount(in); return true; } int main (int argc, char** argv) { bool ok = disassemble(std::cin, std::cout); if (!ok) { std::cout << "Failure in disassemble" << std::endl; return 1; } else { std::cout << "Success in disassemble" << std::endl; return 0; } }
#include <iostream> #include <iterator> #include <string.h> /* Parse uint32 */ uint32_t uint32Parser(std::istream &in, std::uint32_t &out) { in.read((char *)&out, sizeof(out)); std::cout << "The uint32_t value is: " << out << std::endl; if (sizeof(out) != 4) { std::cout << "Incorrect size of uint32_t" << std::endl; return false; } else { return true; } } /* Read header "b9module" from module */ bool parseHeader(std::istream &in) { char buffer[8]; in.read(buffer, 8); auto gcount = in.gcount(); if (gcount != 8) return false; if (0 != strncmp("b9module", buffer, gcount)) return false; // TODO Set header in Module return true; } /* Read Section Code */ bool parseSectionCode(std::istream &in) { uint32_t sectionCode; if (!uint32Parser(in, sectionCode)) { return false; } if (sectionCode != 1) { std::cout << "Incorrect section code" << std::endl; return false; } std::cout << "Section Code: " << sectionCode << std::endl; // TODO Set section code in Module return true; } /* Read Function Count */ bool parseFunctionCount(std::istream &in) { uint32_t functionCount; if (!uint32Parser(in, functionCount)) { return false; } std::cout << "Function count: " << functionCount << std::endl; // TODO Set function count in module return true; } /* Read function information */ bool parseFunctionData(std::istream &in) { uint32_t functionIndex; uint32_t nargs; uint32_t nregs; if (!uint32Parser(in, functionIndex)) { return false; } if (!uint32Parser(in, nargs)) { return false; } if (!uint32Parser(in, nregs)) { return false; } std::cout << "Function Index: " << functionIndex << std::endl; std::cout << "Number Arguments: " << nargs << std::endl; std::cout << "Number Registers: " << nregs << std::endl; // TODO Set function index, nargs, and nregs in Module return true; } /* Disassemble Binary Module */ bool disassemble(std::istream &in, std::ostream &out) { // Read header if (parseHeader(in)) { std::cout << "Success in parseHeader" << std::endl; } else { std::cout << "Failure in parseHeader" << std::endl; return false; } // Read section code if (parseSectionCode(in)) { std::cout << "Success in parseSectionCode" << std::endl; } else { std::cout << "Failure in parseSectionCode" << std::endl; return false; } // Read function count if (parseFunctionCount(in)) { std::cout << "Success in parseFunctionCount" << std::endl; } else { std::cout << "Failure in parseFunctionCount" << std::endl; return false; } // Read function data if (parseFunctionData(in)) { std::cout << "Success in parseFunctionData" << std::endl; } else { std::cout << "Failure in parseFunctionData" << std::endl; } return true; } int main (int argc, char** argv) { bool ok = disassemble(std::cin, std::cout); if (!ok) { std::cout << "Failure in disassemble" << std::endl; return 1; } else { std::cout << "Success in disassemble" << std::endl; return 0; } }
Add function to read function data
Add function to read function data Signed-off-by: Arianne Butler <[email protected]>
C++
apache-2.0
youngar/Base9,youngar/Base9,jduimovich/Base9,youngar/Base9,jduimovich/Base9
fa8184d3f6a7d674b040371f959f02ddfabf0aa3
Code/Polygon.cpp
Code/Polygon.cpp
// Polygon.cpp #include "Polygon.h" #include "Triangle.h" #include "IndexTriangle.h" #include "LineSegment.h" #include "Surface.h" using namespace _3DMath; Polygon::Polygon( void ) { vertexArray = new VectorArray(); indexTriangleList = new IndexTriangleList(); } /*virtual*/ Polygon::~Polygon( void ) { delete vertexArray; delete indexTriangleList; } bool Polygon::GetPlane( Plane& plane ) const { if( vertexArray->size() < 3 ) return false; Vector normal, center; normal.Set( 0.0, 0.0, 0.0 ); center.Set( 0.0, 0.0, 0.0 ); for( int i = 0; i < ( signed )vertexArray->size(); i++ ) { // This is the Newel method. int j = ( i + 1 ) % vertexArray->size(); const Vector& pointA = ( *vertexArray )[i]; const Vector& pointB = ( *vertexArray )[j]; normal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z ); normal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x ); normal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y ); center.Add( pointA ); } center.Scale( 1.0 / double( vertexArray->size() ) ); plane.SetCenterAndNormal( center, normal ); return true; } bool Polygon::SplitAgainstSurface( const Surface* surface, PolygonList& polygonList, double maxDistanceFromSurface ) const { return false; /* struct Node { Vector point; Surface::Side side; }; std::vector< Node > nodeArray; for( int i = 0; i < ( signed )vertexArray->size(); i++ ) { Node node; node.point = ( *vertexArray )[i]; node.side = surface->GetSide( node.point ); nodeArray.push_back( node ); } for( int i = 0; i < ( signed )nodeArray.size(); i++ ) { int j = ( i + 1 ) % nodeArray.size(); if( ( nodeArray[i].side == Surface::INSIDE && nodeArray[j].side == Surface::OUTSIDE ) || ( nodeArray[i].side == Surface::OUTSIDE && nodeArray[j].side == Surface::INSIDE ) ) { LineSegment lineSegment; lineSegment.vertex[0] = nodeArray[i].point; lineSegment.vertex[1] = nodeArray[j].point; SurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment ); if( !surfacePoint ) return false; Node node; surfacePoint->GetLocation( node.point ); node.side = Surface::NEITHER_SIDE; std::vector< Node >::iterator iter( nodeArray.begin() + j ); nodeArray.insert( iter, node ); } } for( int i = 0; i < 2; i++ ) { Polygon* polygon = nullptr; Surface::Side currentSide, otherSide; if( i == 0 ) { currentSide = Surface::INSIDE; otherSide = Surface::OUTSIDE; polygon = &insidePolygon; } else { currentSide = Surface::OUTSIDE; otherSide = Surface::INSIDE; polygon = &outsidePolygon; } int j; for( j = 0; j < ( signed )nodeArray.size(); j++ ) if( nodeArray[j].side == currentSide ) break; if( j == ( signed )nodeArray.size() ) return false; int k = j; do { int l = ( k + 1 ) % nodeArray.size(); if( nodeArray[k].side == Surface::NEITHER_SIDE && nodeArray[l].side == otherSide ) { while( nodeArray[l].side != Surface::NEITHER_SIDE ) l = ( l + 1 ) % nodeArray.size(); SurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( nodeArray[k].point ); SurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( nodeArray[l].point ); surface->FindDirectPath( surfacePointA, surfacePointB, *polygon->vertexArray, maxDistanceFromSurface ); l = ( l + 1 ) % nodeArray.size(); } else { polygon->vertexArray->push_back( nodeArray[k].point ); } k = l; } while( k != j ); } return true; */ } bool Polygon::Tessellate( void ) const { Plane plane; if( !GetPlane( plane ) ) return false; indexTriangleList->clear(); std::vector< int > indexArray; for( int i = 0; i < ( signed )vertexArray->size(); i++ ) indexArray.push_back(i); while( indexArray.size() > 2 ) { for( int i = 0; i < ( signed )indexArray.size(); i++ ) { IndexTriangle indexTriangle( indexArray[i], indexArray[ ( i + 1 ) % indexArray.size() ], indexArray[ ( i + 2 ) % indexArray.size() ] ); Triangle triangle; indexTriangle.GetTriangle( triangle, vertexArray ); Vector edge[2]; edge[0].Subtract( triangle.vertex[1], triangle.vertex[0] ); edge[1].Subtract( triangle.vertex[2], triangle.vertex[1] ); Vector cross; cross.Cross( edge[0], edge[1] ); double dot = cross.Dot( plane.normal ); if( dot < 0.0 ) continue; int j; for( j = 0; j < ( signed )indexArray.size(); j++ ) if( triangle.ProperlyContainsPoint( ( *vertexArray )[ indexArray[j] ] ) ) break; if( j < ( signed )indexArray.size() ) continue; indexTriangleList->push_back( indexTriangle ); indexArray.erase( indexArray.begin() + ( i + 1 ) % indexArray.size() ); break; } } return true; } // Polygon.cpp
// Polygon.cpp #include "Polygon.h" #include "Triangle.h" #include "IndexTriangle.h" #include "LineSegment.h" #include "Surface.h" using namespace _3DMath; Polygon::Polygon( void ) { vertexArray = new VectorArray(); indexTriangleList = new IndexTriangleList(); } /*virtual*/ Polygon::~Polygon( void ) { delete vertexArray; delete indexTriangleList; } bool Polygon::GetPlane( Plane& plane ) const { if( vertexArray->size() < 3 ) return false; Vector normal, center; normal.Set( 0.0, 0.0, 0.0 ); center.Set( 0.0, 0.0, 0.0 ); for( int i = 0; i < ( signed )vertexArray->size(); i++ ) { // This is the Newel method. int j = ( i + 1 ) % vertexArray->size(); const Vector& pointA = ( *vertexArray )[i]; const Vector& pointB = ( *vertexArray )[j]; normal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z ); normal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x ); normal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y ); center.Add( pointA ); } center.Scale( 1.0 / double( vertexArray->size() ) ); plane.SetCenterAndNormal( center, normal ); return true; } bool Polygon::SplitAgainstSurface( const Surface* surface, PolygonList& polygonList, double maxDistanceFromSurface ) const { struct Node { Vector point; Surface::Side side; }; std::vector< Node > nodeArray; for( int i = 0; i < ( signed )vertexArray->size(); i++ ) { Node node; node.point = ( *vertexArray )[i]; node.side = surface->GetSide( node.point ); nodeArray.push_back( node ); } std::vector< int > intersectionArray; for( int i = 0; i < ( signed )nodeArray.size(); i++ ) { int j = ( i + 1 ) % nodeArray.size(); if( ( nodeArray[i].side == Surface::INSIDE && nodeArray[j].side == Surface::OUTSIDE ) || ( nodeArray[j].side == Surface::INSIDE && nodeArray[i].side == Surface::OUTSIDE ) ) { LineSegment lineSegment; lineSegment.vertex[0] = nodeArray[i].point; lineSegment.vertex[1] = nodeArray[j].point; SurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment ); if( !surfacePoint ) return false; Node node; surfacePoint->GetLocation( node.point ); node.side = Surface::NEITHER_SIDE; std::vector< Node >::iterator iter( nodeArray.begin() + j ); nodeArray.insert( iter, node ); intersectionArray.push_back(j); } } if( intersectionArray.size() < 2 ) return false; for( int i = 0; i < ( signed )intersectionArray.size(); i++ ) { int j0 = intersectionArray[i]; int j1 = intersectionArray[ ( i + 1 ) % intersectionArray.size() ]; Polygon* polygon = new Polygon(); polygonList.push_back( polygon ); int k = ( j0 + 1 ) % nodeArray.size(); while( k != j1 ) { polygon->vertexArray->push_back( nodeArray[k].point ); k = ( k + 1 ) % nodeArray.size(); } SurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( nodeArray[ j1 ].point ); SurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( nodeArray[ j0 ].point ); bool pathFound = false; if( surfacePointA && surfacePointB ) pathFound = surface->FindDirectPath( surfacePointA, surfacePointB, *polygon->vertexArray, maxDistanceFromSurface ); delete surfacePointA; delete surfacePointB; if( !pathFound ) return false; } return true; } bool Polygon::Tessellate( void ) const { Plane plane; if( !GetPlane( plane ) ) return false; indexTriangleList->clear(); std::vector< int > indexArray; for( int i = 0; i < ( signed )vertexArray->size(); i++ ) indexArray.push_back(i); while( indexArray.size() > 2 ) { for( int i = 0; i < ( signed )indexArray.size(); i++ ) { IndexTriangle indexTriangle( indexArray[i], indexArray[ ( i + 1 ) % indexArray.size() ], indexArray[ ( i + 2 ) % indexArray.size() ] ); Triangle triangle; indexTriangle.GetTriangle( triangle, vertexArray ); Vector edge[2]; edge[0].Subtract( triangle.vertex[1], triangle.vertex[0] ); edge[1].Subtract( triangle.vertex[2], triangle.vertex[1] ); Vector cross; cross.Cross( edge[0], edge[1] ); double dot = cross.Dot( plane.normal ); if( dot < 0.0 ) continue; int j; for( j = 0; j < ( signed )indexArray.size(); j++ ) if( triangle.ProperlyContainsPoint( ( *vertexArray )[ indexArray[j] ] ) ) break; if( j < ( signed )indexArray.size() ) continue; indexTriangleList->push_back( indexTriangle ); indexArray.erase( indexArray.begin() + ( i + 1 ) % indexArray.size() ); break; } } return true; } // Polygon.cpp
revise polygon splitter (still not tested)
revise polygon splitter (still not tested)
C++
mit
spencerparkin/3DMath,spencerparkin/3DMath
fad63878e529ad775f4484330235242a7a900987
i18npool/qa/cppunit/test_breakiterator.cxx
i18npool/qa/cppunit/test_breakiterator.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is * Caolán McNamara <[email protected]> * * Contributor(s): * Caolán McNamara <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "sal/config.h" #include "sal/precppunit.hxx" #ifdef IOS #define CPPUNIT_PLUGIN_EXPORTED_NAME cppunitTest_i18npool_breakiterator #endif #include <cppuhelper/compbase1.hxx> #include <cppuhelper/bootstrap.hxx> #include <cppuhelper/basemutex.hxx> #include "cppunit/TestAssert.h" #include "cppunit/TestFixture.h" #include "cppunit/extensions/HelperMacros.h" #include "cppunit/plugin/TestPlugIn.h" #include <com/sun/star/i18n/XBreakIterator.hpp> #include <com/sun/star/i18n/CharacterIteratorMode.hpp> #include <com/sun/star/i18n/ScriptType.hpp> #include <com/sun/star/i18n/WordType.hpp> #include <rtl/strbuf.hxx> #include <string.h> using namespace ::com::sun::star; class TestBreakIterator : public CppUnit::TestFixture { public: TestBreakIterator(); ~TestBreakIterator(); virtual void setUp(); virtual void tearDown(); void testLineBreaking(); void testGraphemeIteration(); void testWeak(); void testAsian(); void testThai(); CPPUNIT_TEST_SUITE(TestBreakIterator); CPPUNIT_TEST(testLineBreaking); CPPUNIT_TEST(testGraphemeIteration); CPPUNIT_TEST(testWeak); CPPUNIT_TEST(testAsian); // CPPUNIT_TEST(testThai); CPPUNIT_TEST_SUITE_END(); private: uno::Reference<uno::XComponentContext> m_xContext; uno::Reference<lang::XMultiComponentFactory> m_xFactory; uno::Reference<lang::XMultiServiceFactory> m_xMSF; uno::Reference<i18n::XBreakIterator> m_xBreak; }; //See https://bugs.freedesktop.org/show_bug.cgi?id=31271 for motivation void TestBreakIterator::testLineBreaking() { ::rtl::OUString aTest1(RTL_CONSTASCII_USTRINGPARAM("(some text here)")); i18n::LineBreakHyphenationOptions aHyphOptions; i18n::LineBreakUserOptions aUserOptions; lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("US")); { //Here we want the line break to leave text here) on the next line i18n::LineBreakResults aResult = m_xBreak->getLineBreak(aTest1, strlen("(some tex"), aLocale, 0, aHyphOptions, aUserOptions); CPPUNIT_ASSERT_MESSAGE("Expected a break at the the start of the word", aResult.breakIndex == 6); } { //Here we want the line break to leave "here)" on the next line i18n::LineBreakResults aResult = m_xBreak->getLineBreak(aTest1, strlen("(some text here"), aLocale, 0, aHyphOptions, aUserOptions); CPPUNIT_ASSERT_MESSAGE("Expected a break at the the start of the word", aResult.breakIndex == 11); } } //See http://qa.openoffice.org/issues/show_bug.cgi?id=111152 for motivation void TestBreakIterator::testGraphemeIteration() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("bn")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IN")); { const sal_Unicode BA_HALANT_LA[] = { 0x09AC, 0x09CD, 0x09AF }; ::rtl::OUString aTest1(BA_HALANT_LA, SAL_N_ELEMENTS(BA_HALANT_LA)); sal_Int32 nDone=0; sal_Int32 nPos; nPos = m_xBreak->nextCharacters(aTest1, 0, aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == SAL_N_ELEMENTS(BA_HALANT_LA)); nPos = m_xBreak->previousCharacters(aTest1, SAL_N_ELEMENTS(BA_HALANT_LA), aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == 0); } { const sal_Unicode HA_HALANT_NA_VOWELSIGNI[] = { 0x09B9, 0x09CD, 0x09A3, 0x09BF }; ::rtl::OUString aTest1(HA_HALANT_NA_VOWELSIGNI, SAL_N_ELEMENTS(HA_HALANT_NA_VOWELSIGNI)); sal_Int32 nDone=0; sal_Int32 nPos; nPos = m_xBreak->nextCharacters(aTest1, 0, aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == SAL_N_ELEMENTS(HA_HALANT_NA_VOWELSIGNI)); nPos = m_xBreak->previousCharacters(aTest1, SAL_N_ELEMENTS(HA_HALANT_NA_VOWELSIGNI), aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == 0); } { const sal_Unicode TA_HALANT_MA_HALANT_YA [] = { 0x09A4, 0x09CD, 0x09AE, 0x09CD, 0x09AF }; ::rtl::OUString aTest1(TA_HALANT_MA_HALANT_YA, SAL_N_ELEMENTS(TA_HALANT_MA_HALANT_YA)); sal_Int32 nDone=0; sal_Int32 nPos; nPos = m_xBreak->nextCharacters(aTest1, 0, aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == SAL_N_ELEMENTS(TA_HALANT_MA_HALANT_YA)); nPos = m_xBreak->previousCharacters(aTest1, SAL_N_ELEMENTS(TA_HALANT_MA_HALANT_YA), aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == 0); } { const sal_Unicode ALEF_QAMATS [] = { 0x05D0, 0x05B8 }; ::rtl::OUString aText(ALEF_QAMATS, SAL_N_ELEMENTS(ALEF_QAMATS)); sal_Int32 nGraphemeCount = 0; sal_Int32 nCurPos = 0; while (nCurPos < aText.getLength()) { sal_Int32 nCount2 = 1; nCurPos = m_xBreak->nextCharacters(aText, nCurPos, lang::Locale(), i18n::CharacterIteratorMode::SKIPCELL, nCount2, nCount2); ++nGraphemeCount; } CPPUNIT_ASSERT_MESSAGE("Should be considered 1 grapheme", nGraphemeCount == 1); } } //A test to ensure that certain ranges and codepoints that are categorized as //weak remain as weak, so that existing docs that depend on this don't silently //change font for those weak chars void TestBreakIterator::testWeak() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("US")); { const sal_Unicode WEAKS[] = { 0x0001, 0x0002, 0x0020, 0x00A0, 0x2150, 0x215F, //Number Forms, fractions 0x2160, 0x2180, //Number Forms, roman numerals 0x2200, 0x22FF, //Mathematical Operators 0x27C0, 0x27EF, //Miscellaneous Mathematical Symbols-A 0x2980, 0x29FF, //Miscellaneous Mathematical Symbols-B 0x2A00, 0x2AFF, //Supplemental Mathematical Operators 0x2100, 0x214F, //Letterlike Symbols 0x2308, 0x230B, //Miscellaneous technical 0x25A0, 0x25FF, //Geometric Shapes 0x2B30, 0x2B4C //Miscellaneous Symbols and Arrows }; ::rtl::OUString aWeaks(WEAKS, SAL_N_ELEMENTS(WEAKS)); for (sal_Int32 i = 0; i < aWeaks.getLength(); ++i) { sal_Int16 nScript = m_xBreak->getScriptType(aWeaks, i); rtl::OStringBuffer aMsg; aMsg.append(RTL_CONSTASCII_STRINGPARAM("Char 0x")); aMsg.append(static_cast<sal_Int32>(aWeaks.getStr()[i]), 16); aMsg.append(RTL_CONSTASCII_STRINGPARAM(" should have been weak")); CPPUNIT_ASSERT_MESSAGE(aMsg.getStr(), nScript == i18n::ScriptType::WEAK); } } } //A test to ensure that certain ranges and codepoints that are categorized as //asian remain as asian, so that existing docs that depend on this don't silently //change font for those asian chars. //See https://bugs.freedesktop.org/show_bug.cgi?id=38095 void TestBreakIterator::testAsian() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("US")); { const sal_Unicode ASIANS[] = { //some typical CJK chars 0x4E00, 0x62FF, //The full HalfWidth and FullWidth block has historically been //designated as taking the CJK font :-( //HalfWidth and FullWidth forms of ASCII 0-9, categorized under //UAX24 as "Common" i.e. by that logic WEAK 0xFF10, 0xFF19, //HalfWidth and FullWidth forms of ASCII A-z, categorized under //UAX25 as "Latin", i.e. by that logic LATIN 0xFF21, 0xFF5A }; ::rtl::OUString aAsians(ASIANS, SAL_N_ELEMENTS(ASIANS)); for (sal_Int32 i = 0; i < aAsians.getLength(); ++i) { sal_Int16 nScript = m_xBreak->getScriptType(aAsians, i); rtl::OStringBuffer aMsg; aMsg.append(RTL_CONSTASCII_STRINGPARAM("Char 0x")); aMsg.append(static_cast<sal_Int32>(aAsians.getStr()[i]), 16); aMsg.append(RTL_CONSTASCII_STRINGPARAM(" should have been asian")); CPPUNIT_ASSERT_MESSAGE(aMsg.getStr(), nScript == i18n::ScriptType::ASIAN); } } } //A test to ensure that our thai word boundary detection is useful //http://lists.freedesktop.org/archives/libreoffice/2012-February/025959.html void TestBreakIterator::testThai() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("th")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TH")); { const sal_Unicode THAI1[] = { 0x0E01, 0x0E38, 0x0E2B, 0x0E25, 0x0E32, 0x0E1A }; ::rtl::OUString aTest1(THAI1, SAL_N_ELEMENTS(THAI1)); i18n::Boundary aBounds = m_xBreak->getWordBoundary(aTest1, 0, aLocale, i18n::WordType::DICTIONARY_WORD, true); CPPUNIT_ASSERT_MESSAGE("Should skip full word", aBounds.startPos == 0 && aBounds.endPos == aTest1.getLength()); } } TestBreakIterator::TestBreakIterator() { m_xContext = cppu::defaultBootstrap_InitialComponentContext(); m_xFactory = m_xContext->getServiceManager(); m_xMSF = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW); m_xBreak = uno::Reference< i18n::XBreakIterator >(m_xMSF->createInstance( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.i18n.BreakIterator"))), uno::UNO_QUERY_THROW); } void TestBreakIterator::setUp() { } TestBreakIterator::~TestBreakIterator() { uno::Reference< lang::XComponent >(m_xContext, uno::UNO_QUERY_THROW)->dispose(); } void TestBreakIterator::tearDown() { } CPPUNIT_TEST_SUITE_REGISTRATION(TestBreakIterator); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is * Caolán McNamara <[email protected]> * * Contributor(s): * Caolán McNamara <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "sal/config.h" #include "sal/precppunit.hxx" #ifdef IOS #define CPPUNIT_PLUGIN_EXPORTED_NAME cppunitTest_i18npool_breakiterator #endif #include <cppuhelper/compbase1.hxx> #include <cppuhelper/bootstrap.hxx> #include <cppuhelper/basemutex.hxx> #include "cppunit/TestAssert.h" #include "cppunit/TestFixture.h" #include "cppunit/extensions/HelperMacros.h" #include "cppunit/plugin/TestPlugIn.h" #include <com/sun/star/i18n/XBreakIterator.hpp> #include <com/sun/star/i18n/CharacterIteratorMode.hpp> #include <com/sun/star/i18n/ScriptType.hpp> #include <com/sun/star/i18n/WordType.hpp> #include <rtl/strbuf.hxx> #include <string.h> using namespace ::com::sun::star; class TestBreakIterator : public CppUnit::TestFixture { public: TestBreakIterator(); ~TestBreakIterator(); virtual void setUp(); virtual void tearDown(); void testLineBreaking(); void testGraphemeIteration(); void testWeak(); void testAsian(); void testThai(); CPPUNIT_TEST_SUITE(TestBreakIterator); CPPUNIT_TEST(testLineBreaking); CPPUNIT_TEST(testGraphemeIteration); CPPUNIT_TEST(testWeak); CPPUNIT_TEST(testAsian); // CPPUNIT_TEST(testThai); CPPUNIT_TEST_SUITE_END(); private: uno::Reference<uno::XComponentContext> m_xContext; uno::Reference<lang::XMultiComponentFactory> m_xFactory; uno::Reference<lang::XMultiServiceFactory> m_xMSF; uno::Reference<i18n::XBreakIterator> m_xBreak; }; //See https://bugs.freedesktop.org/show_bug.cgi?id=31271 for motivation void TestBreakIterator::testLineBreaking() { ::rtl::OUString aTest1(RTL_CONSTASCII_USTRINGPARAM("(some text here)")); i18n::LineBreakHyphenationOptions aHyphOptions; i18n::LineBreakUserOptions aUserOptions; lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("US")); { //Here we want the line break to leave text here) on the next line i18n::LineBreakResults aResult = m_xBreak->getLineBreak(aTest1, strlen("(some tex"), aLocale, 0, aHyphOptions, aUserOptions); CPPUNIT_ASSERT_MESSAGE("Expected a break at the the start of the word", aResult.breakIndex == 6); } { //Here we want the line break to leave "here)" on the next line i18n::LineBreakResults aResult = m_xBreak->getLineBreak(aTest1, strlen("(some text here"), aLocale, 0, aHyphOptions, aUserOptions); CPPUNIT_ASSERT_MESSAGE("Expected a break at the the start of the word", aResult.breakIndex == 11); } } //See http://qa.openoffice.org/issues/show_bug.cgi?id=111152 for motivation void TestBreakIterator::testGraphemeIteration() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("bn")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IN")); { const sal_Unicode BA_HALANT_LA[] = { 0x09AC, 0x09CD, 0x09AF }; ::rtl::OUString aTest1(BA_HALANT_LA, SAL_N_ELEMENTS(BA_HALANT_LA)); sal_Int32 nDone=0; sal_Int32 nPos; nPos = m_xBreak->nextCharacters(aTest1, 0, aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == SAL_N_ELEMENTS(BA_HALANT_LA)); nPos = m_xBreak->previousCharacters(aTest1, SAL_N_ELEMENTS(BA_HALANT_LA), aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == 0); } { const sal_Unicode HA_HALANT_NA_VOWELSIGNI[] = { 0x09B9, 0x09CD, 0x09A3, 0x09BF }; ::rtl::OUString aTest1(HA_HALANT_NA_VOWELSIGNI, SAL_N_ELEMENTS(HA_HALANT_NA_VOWELSIGNI)); sal_Int32 nDone=0; sal_Int32 nPos; nPos = m_xBreak->nextCharacters(aTest1, 0, aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == SAL_N_ELEMENTS(HA_HALANT_NA_VOWELSIGNI)); nPos = m_xBreak->previousCharacters(aTest1, SAL_N_ELEMENTS(HA_HALANT_NA_VOWELSIGNI), aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == 0); } { const sal_Unicode TA_HALANT_MA_HALANT_YA [] = { 0x09A4, 0x09CD, 0x09AE, 0x09CD, 0x09AF }; ::rtl::OUString aTest1(TA_HALANT_MA_HALANT_YA, SAL_N_ELEMENTS(TA_HALANT_MA_HALANT_YA)); sal_Int32 nDone=0; sal_Int32 nPos; nPos = m_xBreak->nextCharacters(aTest1, 0, aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == SAL_N_ELEMENTS(TA_HALANT_MA_HALANT_YA)); nPos = m_xBreak->previousCharacters(aTest1, SAL_N_ELEMENTS(TA_HALANT_MA_HALANT_YA), aLocale, i18n::CharacterIteratorMode::SKIPCELL, 1, nDone); CPPUNIT_ASSERT_MESSAGE("Should skip full grapheme", nPos == 0); } { const sal_Unicode ALEF_QAMATS [] = { 0x05D0, 0x05B8 }; ::rtl::OUString aText(ALEF_QAMATS, SAL_N_ELEMENTS(ALEF_QAMATS)); sal_Int32 nGraphemeCount = 0; sal_Int32 nCurPos = 0; while (nCurPos < aText.getLength()) { sal_Int32 nCount2 = 1; nCurPos = m_xBreak->nextCharacters(aText, nCurPos, lang::Locale(), i18n::CharacterIteratorMode::SKIPCELL, nCount2, nCount2); ++nGraphemeCount; } CPPUNIT_ASSERT_MESSAGE("Should be considered 1 grapheme", nGraphemeCount == 1); } } //A test to ensure that certain ranges and codepoints that are categorized as //weak remain as weak, so that existing docs that depend on this don't silently //change font for those weak chars void TestBreakIterator::testWeak() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("US")); { const sal_Unicode WEAKS[] = { 0x0001, 0x0002, 0x0020, 0x00A0, 0x2150, 0x215F, //Number Forms, fractions 0x2160, 0x2180, //Number Forms, roman numerals 0x2200, 0x22FF, //Mathematical Operators 0x27C0, 0x27EF, //Miscellaneous Mathematical Symbols-A 0x2980, 0x29FF, //Miscellaneous Mathematical Symbols-B 0x2A00, 0x2AFF, //Supplemental Mathematical Operators 0x2100, 0x214F, //Letterlike Symbols 0x2308, 0x230B, //Miscellaneous technical 0x25A0, 0x25FF, //Geometric Shapes 0x2B30, 0x2B4C //Miscellaneous Symbols and Arrows }; ::rtl::OUString aWeaks(WEAKS, SAL_N_ELEMENTS(WEAKS)); for (sal_Int32 i = 0; i < aWeaks.getLength(); ++i) { sal_Int16 nScript = m_xBreak->getScriptType(aWeaks, i); rtl::OStringBuffer aMsg; aMsg.append(RTL_CONSTASCII_STRINGPARAM("Char 0x")); aMsg.append(static_cast<sal_Int32>(aWeaks.getStr()[i]), 16); aMsg.append(RTL_CONSTASCII_STRINGPARAM(" should have been weak")); CPPUNIT_ASSERT_MESSAGE(aMsg.getStr(), nScript == i18n::ScriptType::WEAK); } } } //A test to ensure that certain ranges and codepoints that are categorized as //asian remain as asian, so that existing docs that depend on this don't silently //change font for those asian chars. //See https://bugs.freedesktop.org/show_bug.cgi?id=38095 void TestBreakIterator::testAsian() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("US")); { const sal_Unicode ASIANS[] = { //some typical CJK chars 0x4E00, 0x62FF, //The full HalfWidth and FullWidth block has historically been //designated as taking the CJK font :-( //HalfWidth and FullWidth forms of ASCII 0-9, categorized under //UAX24 as "Common" i.e. by that logic WEAK 0xFF10, 0xFF19, //HalfWidth and FullWidth forms of ASCII A-z, categorized under //UAX25 as "Latin", i.e. by that logic LATIN 0xFF21, 0xFF5A }; ::rtl::OUString aAsians(ASIANS, SAL_N_ELEMENTS(ASIANS)); for (sal_Int32 i = 0; i < aAsians.getLength(); ++i) { sal_Int16 nScript = m_xBreak->getScriptType(aAsians, i); rtl::OStringBuffer aMsg; aMsg.append(RTL_CONSTASCII_STRINGPARAM("Char 0x")); aMsg.append(static_cast<sal_Int32>(aAsians.getStr()[i]), 16); aMsg.append(RTL_CONSTASCII_STRINGPARAM(" should have been asian")); CPPUNIT_ASSERT_MESSAGE(aMsg.getStr(), nScript == i18n::ScriptType::ASIAN); } } } //A test to ensure that our thai word boundary detection is useful //http://lists.freedesktop.org/archives/libreoffice/2012-February/025959.html void TestBreakIterator::testThai() { lang::Locale aLocale; aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("th")); aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TH")); i18n::Boundary aBounds; { const sal_Unicode THAI1[] = { 0x0E01, 0x0E38, 0x0E2B, 0x0E25, 0x0E32, 0x0E1A }; ::rtl::OUString aTest(THAI1, SAL_N_ELEMENTS(THAI1)); aBounds = m_xBreak->getWordBoundary(aTest, 0, aLocale, i18n::WordType::DICTIONARY_WORD, true); CPPUNIT_ASSERT_MESSAGE("Should skip full word", aBounds.startPos == 0 && aBounds.endPos == aTest.getLength()); } { const sal_Unicode NORTHERN_THAI1[] = { 0x0E01, 0x0E38, 0x0E4A, 0x0E2B, 0x0E25, 0x0E32, 0x0E1A }; ::rtl::OUString aTest(NORTHERN_THAI1, SAL_N_ELEMENTS(NORTHERN_THAI1)); aBounds = m_xBreak->getWordBoundary(aTest, 0, aLocale, i18n::WordType::DICTIONARY_WORD, true); CPPUNIT_ASSERT_MESSAGE("Should skip full word", aBounds.startPos == 0 && aBounds.endPos == aTest.getLength()); } } TestBreakIterator::TestBreakIterator() { m_xContext = cppu::defaultBootstrap_InitialComponentContext(); m_xFactory = m_xContext->getServiceManager(); m_xMSF = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW); m_xBreak = uno::Reference< i18n::XBreakIterator >(m_xMSF->createInstance( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.i18n.BreakIterator"))), uno::UNO_QUERY_THROW); } void TestBreakIterator::setUp() { } TestBreakIterator::~TestBreakIterator() { uno::Reference< lang::XComponent >(m_xContext, uno::UNO_QUERY_THROW)->dispose(); } void TestBreakIterator::tearDown() { } CPPUNIT_TEST_SUITE_REGISTRATION(TestBreakIterator); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
add northern-thai example
add northern-thai example
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
28b2dcf5fbb1fd132d18ce9f4431759fe25aec19
OADB/COMMON/MULTIPLICITY/macros/docs/GenerateDocumentation01.C
OADB/COMMON/MULTIPLICITY/macros/docs/GenerateDocumentation01.C
#include "AliMult" void GenerateDocumentation01() { //This macro auto-generates documentation (twiki-style) //based on all OADBs currently deployed in the AliPhysics //directory specified here: TString lPathToOADBs = "$HOME/alice/ali-master/AliPhysics/OADB/COMMON/MULTIPLICITY/data/"; cout<<"Expanding path name..."<<endl; gSystem->ExpandPathName( lPathToOADBs ); cout<< "Expanded to: "<<lPathToOADBs.Data()<<endl; //Start: determine list of available OADBs TSystemDirectory dir(lPathToOADBs.Data(), lPathToOADBs.Data()); TList *files = dir.GetListOfFiles(); //sorting... files->Sort(); //Number of automatically found OADB files Long_t lNOADBs = 0; //Output text file TString lOutputDoc = "doc.txt"; ofstream lDocs; lDocs.open ( lOutputDoc.Data() ); if (files) { TSystemFile *file; TString fname; TIter next(files); while ((file=(TSystemFile*)next())) { fname = file->GetName(); TString lProdName = fname; TString lCalibRuns = ""; TString lTime = ""; TString lCommitMessage = ""; TString lEvSels = ""; TString lEstims = ""; TString lEstimPerRun = ""; lProdName.ReplaceAll("OADB-",""); lProdName.ReplaceAll(".root",""); if (!file->IsDirectory() && fname.EndsWith(".root")) { cout<<"======================================================"<<endl; cout<<" OADB entry for period ["<<lProdName.Data() <<"] found!"<<endl; cout<<" -> Opening OADB and checking for information ... "<<endl; //Mod time //Long_t id,size,flags,mt; //gSystem->GetPathInfo(Form("%s%s",lPathToOADBs.Data(),fname.Data()),&id,&size,&flags,&mt); //TTimeStamp st(mt); //cout<<"Date : "<<st.GetDate()<<endl; //lTime.Append(Form("%i",st.GetDate())); //Modification time, as per git command: // git log -1 --format="%ai" -- OADB-blablabla.root lTime = gSystem->GetFromPipe(Form("cd %s; git log -1 --format=\"%%ai\" -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data())); lCommitMessage = gSystem->GetFromPipe(Form("cd %s; git log -1 --oneline -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data())); cout<<"======================================================"<<endl; cout<<lTime.Data()<<endl; cout<<"Commit Message Text: "<<lCommitMessage.Data()<<endl; //Will now append lCommitMessage to lTime lCommitMessage.Prepend(" <noautolink><element title=\"Last Commit Message: "); lCommitMessage.Append("\"> %ICONURL{help}% </element></noautolink>"); lTime.Append(lCommitMessage); cout<<" lTime string, final: "<<lTime.Data()<<endl; cout<<"======================================================"<<endl; TFile * f = new TFile (Form("%s%s",lPathToOADBs.Data(),fname.Data())); AliOADBContainer * oadbContMS = (AliOADBContainer*) f->Get("MultSel"); cout<<" ---> contains this many runs: "<<oadbContMS->GetNumberOfEntries()<<endl; AliOADBMultSelection * oadbMultSelection = 0x0; for(Long_t ir=0; ir<oadbContMS->GetNumberOfEntries(); ir++) { //Acquire the MultSelection Object for this run and get the specific //calibration information (Anchor point and anchor percentile) for each estimator oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(ir); //Get estimator info lCalibRuns.Append("<element title=\""); for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) { TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName(); Float_t lAP = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPoint(); Float_t lAPPerc = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPercentile(); lCalibRuns.Append(Form("%s",def.Data())); //Name if(oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetUseAnchor()) { lCalibRuns.Append(Form(": Raw Val %.3f, Percentile: %.3f",lAP,lAPPerc)); //Characteristics } else { lCalibRuns.Append(": Unanchored"); //Characteristics } if ( iEst != oadbMultSelection->GetMultSelection()->GetNEstimators()-1 ) lCalibRuns.Append("&#10;"); //Name } lCalibRuns.Append(Form("\"> %i</element>",oadbContMS->LowerLimit(ir))); if( ir != oadbContMS->GetNumberOfEntries()-1 ) lCalibRuns.Append(", "); } cout<<" ---> Detected calibrated runs: "<<endl; cout<<lCalibRuns.Data()<<endl; cout<<" ---> Acquiring example object by index... "<<endl; oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(0); cout<<" -> Adding: Event selection information ..."<<endl; if( oadbMultSelection ) { lEvSels.Append(Form("Vertex position &#124;z&#124; < %.1f cm",oadbMultSelection->GetEventCuts()->GetVzCut() ) ); if( oadbMultSelection->GetEventCuts()->GetTriggerCut() ) lEvSels.Append(" + Physics selected (Minimum Bias: kMB/kINT7)"); if( oadbMultSelection->GetEventCuts()->GetINELgtZEROCut() ) lEvSels.Append(" + INEL&gt;0 with SPD tracklets"); if( oadbMultSelection->GetEventCuts()->GetTrackletsVsClustersCut() ) lEvSels.Append(" + tracklets versus clusters cut"); if( oadbMultSelection->GetEventCuts()->GetRejectPileupInMultBinsCut() ) lEvSels.Append(" + Pileup in Mult bins rejection"); if( oadbMultSelection->GetEventCuts()->GetVertexConsistencyCut() ) lEvSels.Append(" + SPD and Track Vertex Consistency OK"); if( oadbMultSelection->GetEventCuts()->GetNonZeroNContribs() ) lEvSels.Append(" + At least 1 contributor to PV"); oadbMultSelection->GetMultSelection()->PrintInfo(); for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) { //syntax = <element title="test test test mom mom mom"> %ICONURL{help}% </div> TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetDefinition(); cout<<"Def = "<<def.Data()<<endl; //Replace &gt; and &lt;s for html code def.ReplaceAll("<","&lt;"); def.ReplaceAll(">","&gt;"); lEstims.Append("<element title=\""); lEstims.Append(Form("%s",def.Data())); lEstims.Append(Form("\"> !%s</element>",oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName())); if(iEst!=oadbMultSelection->GetMultSelection()->GetNEstimators()-1) lEstims.Append(", "); } } cout<<" ---> Event Selection: "<<lEvSels.Data()<<endl; //Appending event selection as a tooltip next to the dataset name lProdName.Prepend("*"); lProdName.Append("*"); lProdName.Append(Form(" <element title=\"Event Selection: %s\"",lEvSels.Data() )); lProdName.Append("> %ICONURL{help}% </element>"); cout<<" ---> Estimator string: "<<lEstims.Data()<<endl; cout<<" -> Adding: estimator definition information ..."<<endl; cout<<"======================================================"<<endl; //Print this in this format: //| LHCxxx | RUNLIST | xx/xx/xxx | ESTIMATORS | lDocs<<"| "<<lProdName.Data()<<" | "<<lCalibRuns.Data()<<" | "<<lTime.Data()<<" | "<<lEstims.Data()<<" |"<<endl; } } } }
#include "AliMultSelection.h" #include "AliMultSelection.h" #include "AliMultSelection.h" #include "AliMultSelection.h" void GenerateDocumentation01() { //This macro auto-generates documentation (twiki-style) //based on all OADBs currently deployed in the AliPhysics //directory specified here: TString lPathToOADBs = "$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/data/"; cout<<"Expanding path name..."<<endl; gSystem->ExpandPathName( lPathToOADBs ); cout<< "Expanded to: "<<lPathToOADBs.Data()<<endl; //Start: determine list of available OADBs TSystemDirectory dir(lPathToOADBs.Data(), lPathToOADBs.Data()); TList *files = dir.GetListOfFiles(); //sorting... files->Sort(); //Number of automatically found OADB files Long_t lNOADBs = 0; //Output text file TString lOutputDoc = "doc.txt"; ofstream lDocs; lDocs.open ( lOutputDoc.Data() ); if (files) { TSystemFile *file; TString fname; TIter next(files); while ((file=(TSystemFile*)next())) { fname = file->GetName(); TString lProdName = fname; TString lCalibRuns = ""; TString lTime = ""; TString lCommitMessage = ""; TString lEvSels = ""; TString lEstims = ""; TString lEstimPerRun = ""; lProdName.ReplaceAll("OADB-",""); lProdName.ReplaceAll(".root",""); if (!file->IsDirectory() && fname.EndsWith(".root")) { cout<<"======================================================"<<endl; cout<<" OADB entry for period ["<<lProdName.Data() <<"] found!"<<endl; cout<<" -> Opening OADB and checking for information ... "<<endl; //Mod time //Long_t id,size,flags,mt; //gSystem->GetPathInfo(Form("%s%s",lPathToOADBs.Data(),fname.Data()),&id,&size,&flags,&mt); //TTimeStamp st(mt); //cout<<"Date : "<<st.GetDate()<<endl; //lTime.Append(Form("%i",st.GetDate())); //Modification time, as per git command: // git log -1 --format="%ai" -- OADB-blablabla.root lTime = gSystem->GetFromPipe(Form("cd %s; git log -1 --format=\"%%ai\" -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data())); lCommitMessage = gSystem->GetFromPipe(Form("cd %s; git log -1 --oneline -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data())); cout<<"======================================================"<<endl; cout<<lTime.Data()<<endl; cout<<"Commit Message Text: "<<lCommitMessage.Data()<<endl; //Will now append lCommitMessage to lTime lCommitMessage.Prepend(" <noautolink><element title=\"Last Commit Message: "); lCommitMessage.Append("\"> %ICONURL{help}% </element></noautolink>"); lTime.Append(lCommitMessage); cout<<" lTime string, final: "<<lTime.Data()<<endl; cout<<"======================================================"<<endl; TFile * f = new TFile (Form("%s%s",lPathToOADBs.Data(),fname.Data())); AliOADBContainer * oadbContMS = (AliOADBContainer*) f->Get("MultSel"); cout<<" ---> contains this many runs: "<<oadbContMS->GetNumberOfEntries()<<endl; AliOADBMultSelection * oadbMultSelection = 0x0; for(Long_t ir=0; ir<oadbContMS->GetNumberOfEntries(); ir++) { //Acquire the MultSelection Object for this run and get the specific //calibration information (Anchor point and anchor percentile) for each estimator oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(ir); //Get estimator info lCalibRuns.Append("<element title=\""); for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) { TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName(); Float_t lAP = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPoint(); Float_t lAPPerc = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPercentile(); lCalibRuns.Append(Form("%s",def.Data())); //Name if(oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetUseAnchor()) { lCalibRuns.Append(Form(": Raw Val %.3f, Percentile: %.3f",lAP,lAPPerc)); //Characteristics } else { lCalibRuns.Append(": Unanchored"); //Characteristics } if ( iEst != oadbMultSelection->GetMultSelection()->GetNEstimators()-1 ) lCalibRuns.Append("&#10;"); //Name } lCalibRuns.Append(Form("\"> %i</element>",oadbContMS->LowerLimit(ir))); if( ir != oadbContMS->GetNumberOfEntries()-1 ) lCalibRuns.Append(", "); } cout<<" ---> Detected calibrated runs: "<<endl; cout<<lCalibRuns.Data()<<endl; cout<<" ---> Acquiring example object by index... "<<endl; oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(0); cout<<" -> Adding: Event selection information ..."<<endl; if( oadbMultSelection ) { lEvSels.Append(Form("Vertex position &#124;z&#124; < %.1f cm",oadbMultSelection->GetEventCuts()->GetVzCut() ) ); if( oadbMultSelection->GetEventCuts()->GetTriggerCut() ) lEvSels.Append(" + Physics selected (Minimum Bias: kMB/kINT7)"); if( oadbMultSelection->GetEventCuts()->GetINELgtZEROCut() ) lEvSels.Append(" + INEL&gt;0 with SPD tracklets"); if( oadbMultSelection->GetEventCuts()->GetTrackletsVsClustersCut() ) lEvSels.Append(" + tracklets versus clusters cut"); if( oadbMultSelection->GetEventCuts()->GetRejectPileupInMultBinsCut() ) lEvSels.Append(" + Pileup in Mult bins rejection"); if( oadbMultSelection->GetEventCuts()->GetVertexConsistencyCut() ) lEvSels.Append(" + SPD and Track Vertex Consistency OK"); if( oadbMultSelection->GetEventCuts()->GetNonZeroNContribs() ) lEvSels.Append(" + At least 1 contributor to PV"); oadbMultSelection->GetMultSelection()->PrintInfo(); for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) { //syntax = <element title="test test test mom mom mom"> %ICONURL{help}% </div> TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetDefinition(); cout<<"Def = "<<def.Data()<<endl; //Replace &gt; and &lt;s for html code def.ReplaceAll("<","&lt;"); def.ReplaceAll(">","&gt;"); lEstims.Append("<element title=\""); lEstims.Append(Form("%s",def.Data())); lEstims.Append(Form("\"> !%s</element>",oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName())); if(iEst!=oadbMultSelection->GetMultSelection()->GetNEstimators()-1) lEstims.Append(", "); } } cout<<" ---> Event Selection: "<<lEvSels.Data()<<endl; //Appending event selection as a tooltip next to the dataset name lProdName.Prepend("*"); lProdName.Append("*"); lProdName.Append(Form(" <element title=\"Event Selection: %s\"",lEvSels.Data() )); lProdName.Append("> %ICONURL{help}% </element>"); cout<<" ---> Estimator string: "<<lEstims.Data()<<endl; cout<<" -> Adding: estimator definition information ..."<<endl; cout<<"======================================================"<<endl; //Print this in this format: //| LHCxxx | RUNLIST | xx/xx/xxx | ESTIMATORS | lDocs<<"| "<<lProdName.Data()<<" | "<<lCalibRuns.Data()<<" | "<<lTime.Data()<<" | "<<lEstims.Data()<<" |"<<endl; } } } }
Make generate OADB macro work again (ROOT6, etc)
Make generate OADB macro work again (ROOT6, etc)
C++
bsd-3-clause
sebaleh/AliPhysics,lcunquei/AliPhysics,lcunquei/AliPhysics,carstooon/AliPhysics,adriansev/AliPhysics,akubera/AliPhysics,hcab14/AliPhysics,pbuehler/AliPhysics,amaringarcia/AliPhysics,amaringarcia/AliPhysics,carstooon/AliPhysics,amatyja/AliPhysics,rihanphys/AliPhysics,fcolamar/AliPhysics,hcab14/AliPhysics,amatyja/AliPhysics,fcolamar/AliPhysics,alisw/AliPhysics,victor-gonzalez/AliPhysics,pchrista/AliPhysics,victor-gonzalez/AliPhysics,fbellini/AliPhysics,pchrista/AliPhysics,fbellini/AliPhysics,AMechler/AliPhysics,mpuccio/AliPhysics,hcab14/AliPhysics,dmuhlhei/AliPhysics,rihanphys/AliPhysics,preghenella/AliPhysics,akubera/AliPhysics,akubera/AliPhysics,akubera/AliPhysics,sebaleh/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,lcunquei/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,rihanphys/AliPhysics,SHornung1/AliPhysics,dmuhlhei/AliPhysics,nschmidtALICE/AliPhysics,hzanoli/AliPhysics,fbellini/AliPhysics,pbuehler/AliPhysics,dmuhlhei/AliPhysics,pbuehler/AliPhysics,adriansev/AliPhysics,amatyja/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics,fbellini/AliPhysics,nschmidtALICE/AliPhysics,preghenella/AliPhysics,lcunquei/AliPhysics,pbuehler/AliPhysics,amaringarcia/AliPhysics,amatyja/AliPhysics,alisw/AliPhysics,lcunquei/AliPhysics,rbailhac/AliPhysics,dmuhlhei/AliPhysics,dmuhlhei/AliPhysics,AMechler/AliPhysics,adriansev/AliPhysics,preghenella/AliPhysics,pchrista/AliPhysics,kreisl/AliPhysics,carstooon/AliPhysics,preghenella/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,pbuehler/AliPhysics,kreisl/AliPhysics,mpuccio/AliPhysics,hcab14/AliPhysics,hzanoli/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,fbellini/AliPhysics,pchrista/AliPhysics,nschmidtALICE/AliPhysics,alisw/AliPhysics,akubera/AliPhysics,mpuccio/AliPhysics,fcolamar/AliPhysics,kreisl/AliPhysics,mpuccio/AliPhysics,rbailhac/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics,rbailhac/AliPhysics,amatyja/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,carstooon/AliPhysics,amaringarcia/AliPhysics,hzanoli/AliPhysics,adriansev/AliPhysics,dmuhlhei/AliPhysics,kreisl/AliPhysics,fbellini/AliPhysics,SHornung1/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,pchrista/AliPhysics,victor-gonzalez/AliPhysics,hzanoli/AliPhysics,rbailhac/AliPhysics,akubera/AliPhysics,preghenella/AliPhysics,kreisl/AliPhysics,carstooon/AliPhysics,kreisl/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,amatyja/AliPhysics,SHornung1/AliPhysics,alisw/AliPhysics,alisw/AliPhysics,lcunquei/AliPhysics,amatyja/AliPhysics,sebaleh/AliPhysics,carstooon/AliPhysics,sebaleh/AliPhysics,preghenella/AliPhysics,victor-gonzalez/AliPhysics,preghenella/AliPhysics,hzanoli/AliPhysics,SHornung1/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,akubera/AliPhysics,AMechler/AliPhysics,rbailhac/AliPhysics,fcolamar/AliPhysics,fcolamar/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,mpuccio/AliPhysics,hcab14/AliPhysics,carstooon/AliPhysics,hzanoli/AliPhysics,amaringarcia/AliPhysics,fbellini/AliPhysics,mpuccio/AliPhysics,dmuhlhei/AliPhysics,alisw/AliPhysics,hzanoli/AliPhysics,pchrista/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,SHornung1/AliPhysics,AMechler/AliPhysics,hcab14/AliPhysics,nschmidtALICE/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,sebaleh/AliPhysics,lcunquei/AliPhysics,AMechler/AliPhysics,rbailhac/AliPhysics,hcab14/AliPhysics,SHornung1/AliPhysics
b889665b89116c2ea0f8180f19a48838d9b895dd
projects/minesweeper/minesweeper_gui/src/main.cpp
projects/minesweeper/minesweeper_gui/src/main.cpp
#include <array> #include <functional> #include <memory> #include <fmt/core.h> #include <nonstd/span.hpp> #include "Minesweeper.hpp" #include "WxWidgetsWrapper.hpp" class MyApp : public wxApp { public: bool OnInit() override; }; enum class BaseState : uint8_t { Closed = 0, Hoovered, Boomed, Opened, }; constexpr auto baseStateCount = 4; enum class FigureType : uint8_t { Empty = 0, One, Two, Three, Four, Five, Six, Seven, Eight, Mine, Flag, }; constexpr auto figureTypeCount = 11; template <typename TTo, typename TFrom> constexpr TTo safeCast(const TFrom &from) { return static_cast<TTo>(from); } template <typename TEnum> constexpr std::underlying_type_t<TEnum> getNumericValue(const TEnum enumValue) { return static_cast<std::underlying_type_t<TEnum>>(enumValue); } class FieldBitmaps { public: explicit FieldBitmaps(int bitmapSize) { std::fill(backgrounds.begin(), backgrounds.end(), wxBitmap{bitmapSize, bitmapSize}); std::fill(figures.begin(), figures.end(), wxBitmap{bitmapSize, bitmapSize}); } [[nodiscard]] const wxBitmap &getBackground(const BaseState &guiState) const { static_assert(getNumericValue(BaseState::Opened) + 1 == std::tuple_size_v<decltype(backgrounds)>, "Number of background bitmaps doesn't match the count of enum values"); switch (guiState) { case BaseState::Closed: case BaseState::Hoovered: case BaseState::Boomed: case BaseState::Opened: return backgrounds[getNumericValue(guiState)]; } throw std::runtime_error(fmt::format("Invalid GUI state {}!", getNumericValue(guiState))); } [[nodiscard]] wxBitmap &getBackground(const BaseState &guiState) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<wxBitmap &>(const_cast<const FieldBitmaps *>(this)->getBackground(guiState)); } [[nodiscard]] const wxBitmap &getFigure(const FigureType &fieldType) const { static_assert(getNumericValue(FigureType::Flag) + 1 == std::tuple_size_v<decltype(figures)>, "Number of figure bitmaps doesn't match the count of enum values"); switch (fieldType) { case FigureType::Empty: case FigureType::One: case FigureType::Two: case FigureType::Three: case FigureType::Four: case FigureType::Five: case FigureType::Six: case FigureType::Seven: case FigureType::Eight: case FigureType::Mine: case FigureType::Flag: return figures[getNumericValue(fieldType)]; } throw std::runtime_error(fmt::format("Invalid field type {}!", getNumericValue(fieldType))); } [[nodiscard]] wxBitmap &getFigure(const FigureType &fieldType) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<wxBitmap &>(const_cast<const FieldBitmaps *>(this)->getFigure(fieldType)); } std::array<wxBitmap, baseStateCount> backgrounds; std::array<wxBitmap, figureTypeCount> figures; }; class FieldState { public: FieldState(const uint64_t &row, const uint64_t &column) : row{row} , column{column} { } void updateWithBaseState(const BaseState &newBaseState) { baseState = newBaseState; } void updateWithFigureType(const FigureType &newFigureType) { if (newFigureType == FigureType::Flag && baseState != BaseState::Closed) { return; } figureType = newFigureType; } void draw(wxDC &dc, const FieldBitmaps &bitmaps) const { dc.DrawBitmap(getBackground(bitmaps), 0, 0, false); if (shouldDrawFigure()) { dc.DrawBitmap(getFigure(bitmaps), 0, 0, false); } } private: [[nodiscard]] bool shouldDrawFigure() const { return baseState == BaseState::Boomed || baseState == BaseState::Opened || figureType == FigureType::Flag; } [[nodiscard]] const wxBitmap &getBackground(const FieldBitmaps &bitmaps) const { return bitmaps.getBackground(baseState); } [[nodiscard]] const wxBitmap &getFigure(const FieldBitmaps &bitmaps) const { return bitmaps.getFigure(figureType); } static constexpr auto defaultFigureType = FigureType::Empty; BaseState baseState{BaseState::Closed}; FigureType figureType{defaultFigureType}; CLANG_MAYBE_UNUSED uint64_t row{0U}; CLANG_MAYBE_UNUSED uint64_t column{0U}; }; class FieldsFrame; class FieldPanel : public wxPanel { public: FieldPanel(wxPanel &parent, const uint64_t row, const uint64_t column, const FieldBitmaps &bitmaps); // cppcheck-suppress unknownMacro DECLARE_EVENT_TABLE() // NOLINT(cppcoreguidelines-avoid-c-arrays) private: FieldsFrame &frame(); void Render(wxDC &dc); void PaintEvent(wxPaintEvent & /*unused*/); void RightClickEvent(wxMouseEvent & /*unused*/); void LeftClickEvent(wxMouseEvent & /*unused*/); void MouseEnterEvent(wxMouseEvent &event); void MouseLeaveEvent(wxMouseEvent &event); FieldState state; const FieldBitmaps &bitmaps; }; BEGIN_EVENT_TABLE(FieldPanel, wxPanel) // NOLINT(cert-err58-cpp, cppcoreguidelines-avoid-c-arrays) EVT_PAINT(FieldPanel::PaintEvent) EVT_RIGHT_DOWN(FieldPanel::RightClickEvent) EVT_LEFT_UP(FieldPanel::LeftClickEvent) EVT_LEFT_DOWN(FieldPanel::MouseEnterEvent) EVT_ENTER_WINDOW(FieldPanel::MouseEnterEvent) EVT_LEAVE_WINDOW(FieldPanel::MouseLeaveEvent) END_EVENT_TABLE() class FieldsFrame : public wxFrame { public: FieldsFrame(); private: static constexpr auto bitmapSize = 40; FieldBitmaps bitmaps{bitmapSize}; std::vector<std::reference_wrapper<FieldPanel>> panels{}; void CreateFields(const uint64_t width, const uint64_t height); void DestroyFields(); void OnHello(wxCommandEvent & /*unused*/); void OnExit(wxCommandEvent & /*unused*/); void OnAbout(wxCommandEvent & /*unused*/); void OnButtonClicked(wxCommandEvent &event); wxPanel *fieldHolderPanel{nullptr}; }; enum { ID_Hello = 1, }; wxIMPLEMENT_APP(MyApp); // NOLINT(cert-err58-cpp) bool MyApp::OnInit() { auto frame = std::make_unique<FieldsFrame>(); frame->Show(true); frame.release(); return true; } FieldPanel::FieldPanel(wxPanel &parent, const uint64_t row, const uint64_t column, const FieldBitmaps &bitmaps) : wxPanel(&parent) , state{row, column} , bitmaps{bitmaps} { SetBackgroundStyle(wxBG_STYLE_PAINT); } void FieldPanel::PaintEvent(wxPaintEvent & /*unused*/) { wxBufferedPaintDC dc(this); Render(dc); } void FieldPanel::RightClickEvent(wxMouseEvent & /*unused*/) { state.updateWithFigureType(FigureType::Flag); Refresh(); } void FieldPanel::LeftClickEvent(wxMouseEvent & /*unused*/) { state.updateWithBaseState(BaseState::Opened); Refresh(); } void FieldPanel::MouseEnterEvent(wxMouseEvent &event) { if (!event.LeftIsDown()) { return; } state.updateWithBaseState(BaseState::Hoovered); Refresh(); } void FieldPanel::MouseLeaveEvent(wxMouseEvent &event) { if (!event.LeftIsDown()) { return; } state.updateWithBaseState(BaseState::Closed); Refresh(); } FieldsFrame &FieldPanel::frame() { return *dynamic_cast<FieldsFrame *>(GetParent()); } void FieldPanel::Render(wxDC &dc) { state.draw(dc, bitmaps); } FieldsFrame::FieldsFrame() // NOLINTNEXTLINE(hicpp-signed-bitwise) : wxFrame(nullptr, wxID_ANY, "Hello World", wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER) { auto menuFile = std::make_unique<wxMenu>(); menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item"); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); auto menuHelp = std::make_unique<wxMenu>(); menuHelp->Append(wxID_ABOUT); auto menuBar = std::make_unique<wxMenuBar>(); menuBar->Append(menuFile.get(), "&File"); menuFile.release(); menuBar->Append(menuHelp.get(), "&Help"); menuHelp.release(); SetMenuBar(menuBar.get()); menuBar.release(); CreateStatusBar(); SetStatusText("Welcome to wxWidgets!"); Bind(wxEVT_MENU, &FieldsFrame::OnHello, this, ID_Hello); Bind(wxEVT_MENU, &FieldsFrame::OnAbout, this, wxID_ABOUT); Bind(wxEVT_MENU, &FieldsFrame::OnExit, this, wxID_EXIT); wxMemoryDC dc; auto paint = [&dc](wxBitmap &bitmap, const wxColor &color) { const auto size = bitmap.GetSize(); constexpr auto borderSize = 5; assert(size.x >= 2 * borderSize); assert(size.y >= 2 * borderSize); dc.SelectObject(bitmap); dc.SetPen(color); dc.SetBrush(*wxGREY_BRUSH); dc.DrawRectangle(0, 0, size.x, size.y); dc.SetPen(*wxGREY_PEN); dc.SetBrush(wxBrush{color}); dc.DrawRectangle(borderSize, borderSize, size.x - 2 * borderSize, size.y - 2 * borderSize); dc.SelectObject(wxNullBitmap); }; paint(bitmaps.getBackground(BaseState::Closed), wxColor{50, 50, 170}); paint(bitmaps.getBackground(BaseState::Boomed), *wxRED); paint(bitmaps.getBackground(BaseState::Hoovered), wxColor{180, 150, 0}); paint(bitmaps.getBackground(BaseState::Opened), *wxLIGHT_GREY); auto *topSizer = new wxBoxSizer(wxVERTICAL); auto fieldHolderPanelOwner = std::make_unique<wxPanel>(this); topSizer->Add(fieldHolderPanelOwner.get()); fieldHolderPanel = fieldHolderPanelOwner.release(); SetSizerAndFit(topSizer); CreateFields(10, 10); } void FieldsFrame::CreateFields(const uint64_t width, const uint64_t height) { fieldHolderPanel->Hide(); auto gridSizerOwner = std::make_unique<wxGridSizer>(safeCast<int>(height), safeCast<int>(width), 0, 0); const auto fieldCount = width * height; auto fieldSize = wxSize(bitmapSize, bitmapSize); panels.reserve(fieldCount); for (uint64_t fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex) { auto fieldPanel = std::make_unique<FieldPanel>(*fieldHolderPanel, fieldIndex / width, fieldIndex % width, bitmaps); fieldPanel->SetSize(fieldSize); fieldPanel->SetMinSize(fieldSize); fieldPanel->SetMaxSize(fieldSize); fieldPanel->SetWindowStyle(wxBORDER_NONE | wxBU_EXACTFIT); auto panelRef = std::ref(*fieldPanel); panels.push_back(std::move(panelRef)); gridSizerOwner->Add(fieldPanel.get(), wxALL, 1); fieldPanel.release(); } auto *gridSizer = gridSizerOwner.get(); fieldHolderPanel->SetSizer(gridSizer); gridSizerOwner.release(); gridSizer->Fit(fieldHolderPanel); gridSizer->SetSizeHints(fieldHolderPanel); fieldHolderPanel->Show(true); GetSizer()->Fit(this); } void FieldsFrame::DestroyFields() { fieldHolderPanel->SetSizer(nullptr); panels.clear(); if (fieldHolderPanel->DestroyChildren() != true) { throw std::runtime_error("Something went wrong"); } } void FieldsFrame::OnExit(wxCommandEvent & /*unused*/) { Close(true); } void FieldsFrame::OnAbout(wxCommandEvent & /*unused*/) { wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION); CreateFields(20, 20); Refresh(); } void FieldsFrame::OnHello(wxCommandEvent & /*unused*/) { wxLogMessage("Hello world from wxWidgets!"); DestroyFields(); }
#include <array> #include <functional> #include <memory> #include <fmt/core.h> #include <nonstd/span.hpp> #include "Minesweeper.hpp" #include "WxWidgetsWrapper.hpp" class MyApp : public wxApp { public: bool OnInit() override; }; enum class BaseState : uint8_t { Closed = 0, Hoovered, Boomed, Opened, }; constexpr auto baseStateCount = 4; enum class FigureType : uint8_t { Empty = 0, One, Two, Three, Four, Five, Six, Seven, Eight, Mine, Flag, }; constexpr auto figureTypeCount = 11; template <typename TTo, typename TFrom> constexpr TTo safeCast(const TFrom &from) { return static_cast<TTo>(from); } template <typename TEnum> constexpr std::underlying_type_t<TEnum> getNumericValue(const TEnum enumValue) { return static_cast<std::underlying_type_t<TEnum>>(enumValue); } class FieldBitmaps { public: explicit FieldBitmaps(int bitmapSize) { std::fill(backgrounds.begin(), backgrounds.end(), wxBitmap{bitmapSize, bitmapSize}); std::fill(figures.begin(), figures.end(), wxBitmap{bitmapSize, bitmapSize}); } [[nodiscard]] const wxBitmap &getBackground(const BaseState &guiState) const { static_assert(getNumericValue(BaseState::Opened) + 1 == std::tuple_size_v<decltype(backgrounds)>, "Number of background bitmaps doesn't match the count of enum values"); switch (guiState) { case BaseState::Closed: case BaseState::Hoovered: case BaseState::Boomed: case BaseState::Opened: return backgrounds[getNumericValue(guiState)]; } throw std::runtime_error(fmt::format("Invalid GUI state {}!", getNumericValue(guiState))); } [[nodiscard]] wxBitmap &getBackground(const BaseState &guiState) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<wxBitmap &>(const_cast<const FieldBitmaps *>(this)->getBackground(guiState)); } [[nodiscard]] const wxBitmap &getFigure(const FigureType &fieldType) const { static_assert(getNumericValue(FigureType::Flag) + 1 == std::tuple_size_v<decltype(figures)>, "Number of figure bitmaps doesn't match the count of enum values"); switch (fieldType) { case FigureType::Empty: case FigureType::One: case FigureType::Two: case FigureType::Three: case FigureType::Four: case FigureType::Five: case FigureType::Six: case FigureType::Seven: case FigureType::Eight: case FigureType::Mine: case FigureType::Flag: return figures[getNumericValue(fieldType)]; } throw std::runtime_error(fmt::format("Invalid field type {}!", getNumericValue(fieldType))); } [[nodiscard]] wxBitmap &getFigure(const FigureType &fieldType) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<wxBitmap &>(const_cast<const FieldBitmaps *>(this)->getFigure(fieldType)); } std::array<wxBitmap, baseStateCount> backgrounds; std::array<wxBitmap, figureTypeCount> figures; }; class FieldState { public: FieldState(const uint64_t &row, const uint64_t &column) : row{row} , column{column} { } void updateWithBaseState(const BaseState &newBaseState) { baseState = newBaseState; } void updateWithFigureType(const FigureType &newFigureType) { if (newFigureType == FigureType::Flag && baseState != BaseState::Closed) { return; } figureType = newFigureType; } void draw(wxDC &dc, const FieldBitmaps &bitmaps) const { dc.DrawBitmap(getBackground(bitmaps), 0, 0, false); if (shouldDrawFigure()) { dc.DrawBitmap(getFigure(bitmaps), 0, 0, false); } } private: [[nodiscard]] bool shouldDrawFigure() const { return baseState == BaseState::Boomed || baseState == BaseState::Opened || figureType == FigureType::Flag; } [[nodiscard]] const wxBitmap &getBackground(const FieldBitmaps &bitmaps) const { return bitmaps.getBackground(baseState); } [[nodiscard]] const wxBitmap &getFigure(const FieldBitmaps &bitmaps) const { return bitmaps.getFigure(figureType); } static constexpr auto defaultFigureType = FigureType::Empty; BaseState baseState{BaseState::Closed}; FigureType figureType{defaultFigureType}; CLANG_MAYBE_UNUSED uint64_t row{0U}; CLANG_MAYBE_UNUSED uint64_t column{0U}; }; class FieldsFrame; class FieldPanel : public wxPanel { public: FieldPanel(wxPanel &parent, const uint64_t row, const uint64_t column, const FieldBitmaps &bitmaps); // cppcheck-suppress unknownMacro DECLARE_EVENT_TABLE() // NOLINT(cppcoreguidelines-avoid-c-arrays) private: FieldsFrame &frame(); void Render(wxDC &dc); void PaintEvent(wxPaintEvent & /*unused*/); void RightClickEvent(wxMouseEvent & /*unused*/); void LeftClickEvent(wxMouseEvent & /*unused*/); void MouseEnterEvent(wxMouseEvent &event); void MouseLeaveEvent(wxMouseEvent &event); FieldState state; const FieldBitmaps &bitmaps; }; BEGIN_EVENT_TABLE(FieldPanel, wxPanel) // NOLINT(cert-err58-cpp, cppcoreguidelines-avoid-c-arrays) EVT_PAINT(FieldPanel::PaintEvent) EVT_RIGHT_DOWN(FieldPanel::RightClickEvent) EVT_LEFT_UP(FieldPanel::LeftClickEvent) EVT_LEFT_DOWN(FieldPanel::MouseEnterEvent) EVT_ENTER_WINDOW(FieldPanel::MouseEnterEvent) EVT_LEAVE_WINDOW(FieldPanel::MouseLeaveEvent) END_EVENT_TABLE() class FieldsFrame : public wxFrame { public: FieldsFrame(); private: static constexpr auto bitmapSize = 40; FieldBitmaps bitmaps{bitmapSize}; std::vector<std::reference_wrapper<FieldPanel>> panels{}; void CreateFields(const uint64_t width, const uint64_t height); void DestroyFields(); void OnHello(wxCommandEvent & /*unused*/); void OnExit(wxCommandEvent & /*unused*/); void OnAbout(wxCommandEvent & /*unused*/); wxPanel *fieldHolderPanel{nullptr}; }; enum { ID_Hello = 1, }; wxIMPLEMENT_APP(MyApp); // NOLINT(cert-err58-cpp) bool MyApp::OnInit() { auto frame = std::make_unique<FieldsFrame>(); frame->Show(true); frame.release(); return true; } FieldPanel::FieldPanel(wxPanel &parent, const uint64_t row, const uint64_t column, const FieldBitmaps &bitmaps) : wxPanel(&parent) , state{row, column} , bitmaps{bitmaps} { SetBackgroundStyle(wxBG_STYLE_PAINT); } void FieldPanel::PaintEvent(wxPaintEvent & /*unused*/) { wxBufferedPaintDC dc(this); Render(dc); } void FieldPanel::RightClickEvent(wxMouseEvent & /*unused*/) { state.updateWithFigureType(FigureType::Flag); Refresh(); } void FieldPanel::LeftClickEvent(wxMouseEvent & /*unused*/) { state.updateWithBaseState(BaseState::Opened); Refresh(); } void FieldPanel::MouseEnterEvent(wxMouseEvent &event) { if (!event.LeftIsDown()) { return; } state.updateWithBaseState(BaseState::Hoovered); Refresh(); } void FieldPanel::MouseLeaveEvent(wxMouseEvent &event) { if (!event.LeftIsDown()) { return; } state.updateWithBaseState(BaseState::Closed); Refresh(); } FieldsFrame &FieldPanel::frame() { return *dynamic_cast<FieldsFrame *>(GetParent()); } void FieldPanel::Render(wxDC &dc) { state.draw(dc, bitmaps); } FieldsFrame::FieldsFrame() // NOLINTNEXTLINE(hicpp-signed-bitwise) : wxFrame(nullptr, wxID_ANY, "Hello World", wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER) { auto menuFile = std::make_unique<wxMenu>(); menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item"); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); auto menuHelp = std::make_unique<wxMenu>(); menuHelp->Append(wxID_ABOUT); auto menuBar = std::make_unique<wxMenuBar>(); menuBar->Append(menuFile.get(), "&File"); menuFile.release(); menuBar->Append(menuHelp.get(), "&Help"); menuHelp.release(); SetMenuBar(menuBar.get()); menuBar.release(); CreateStatusBar(); SetStatusText("Welcome to wxWidgets!"); Bind(wxEVT_MENU, &FieldsFrame::OnHello, this, ID_Hello); Bind(wxEVT_MENU, &FieldsFrame::OnAbout, this, wxID_ABOUT); Bind(wxEVT_MENU, &FieldsFrame::OnExit, this, wxID_EXIT); wxMemoryDC dc; auto paint = [&dc](wxBitmap &bitmap, const wxColor &color) { const auto size = bitmap.GetSize(); constexpr auto borderSize = 5; assert(size.x >= 2 * borderSize); assert(size.y >= 2 * borderSize); dc.SelectObject(bitmap); dc.SetPen(color); dc.SetBrush(*wxGREY_BRUSH); dc.DrawRectangle(0, 0, size.x, size.y); dc.SetPen(*wxGREY_PEN); dc.SetBrush(wxBrush{color}); dc.DrawRectangle(borderSize, borderSize, size.x - 2 * borderSize, size.y - 2 * borderSize); dc.SelectObject(wxNullBitmap); }; paint(bitmaps.getBackground(BaseState::Closed), wxColor{50, 50, 170}); paint(bitmaps.getBackground(BaseState::Boomed), *wxRED); paint(bitmaps.getBackground(BaseState::Hoovered), wxColor{180, 150, 0}); paint(bitmaps.getBackground(BaseState::Opened), *wxLIGHT_GREY); auto *topSizer = new wxBoxSizer(wxVERTICAL); auto fieldHolderPanelOwner = std::make_unique<wxPanel>(this); topSizer->Add(fieldHolderPanelOwner.get()); fieldHolderPanel = fieldHolderPanelOwner.release(); SetSizerAndFit(topSizer); CreateFields(10, 10); } void FieldsFrame::CreateFields(const uint64_t width, const uint64_t height) { fieldHolderPanel->Hide(); auto gridSizerOwner = std::make_unique<wxGridSizer>(safeCast<int>(height), safeCast<int>(width), 0, 0); const auto fieldCount = width * height; auto fieldSize = wxSize(bitmapSize, bitmapSize); panels.reserve(fieldCount); for (uint64_t fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex) { auto fieldPanel = std::make_unique<FieldPanel>(*fieldHolderPanel, fieldIndex / width, fieldIndex % width, bitmaps); fieldPanel->SetSize(fieldSize); fieldPanel->SetMinSize(fieldSize); fieldPanel->SetMaxSize(fieldSize); fieldPanel->SetWindowStyle(wxBORDER_NONE | wxBU_EXACTFIT); auto panelRef = std::ref(*fieldPanel); panels.push_back(std::move(panelRef)); gridSizerOwner->Add(fieldPanel.get(), wxALL, 1); fieldPanel.release(); } auto *gridSizer = gridSizerOwner.get(); fieldHolderPanel->SetSizer(gridSizer); gridSizerOwner.release(); gridSizer->Fit(fieldHolderPanel); gridSizer->SetSizeHints(fieldHolderPanel); fieldHolderPanel->Show(true); GetSizer()->Fit(this); } void FieldsFrame::DestroyFields() { fieldHolderPanel->SetSizer(nullptr); panels.clear(); if (fieldHolderPanel->DestroyChildren() != true) { throw std::runtime_error("Something went wrong"); } } void FieldsFrame::OnExit(wxCommandEvent & /*unused*/) { Close(true); } void FieldsFrame::OnAbout(wxCommandEvent & /*unused*/) { wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION); CreateFields(20, 20); Refresh(); } void FieldsFrame::OnHello(wxCommandEvent & /*unused*/) { wxLogMessage("Hello world from wxWidgets!"); DestroyFields(); }
Remove undefined function declaration
Remove undefined function declaration
C++
mit
antaljanosbenjamin/miscellaneous,antaljanosbenjamin/miscellaneous
e43bf973fbd8170cd8d9b2fc2469dec57286b06e
cpp/test/Sara/FeatureDescriptors/test_featuredescriptors_sift.cpp
cpp/test/Sara/FeatureDescriptors/test_featuredescriptors_sift.cpp
// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2015-2017 David Ok <[email protected]> // // 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/. // ========================================================================== // #define BOOST_TEST_MODULE "FeatureDescriptors/SIFT Descriptor" #include <DO/Sara/FeatureDescriptors/SIFT.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace DO::Sara; BOOST_AUTO_TEST_SUITE(TestSIFTDescriptors) BOOST_AUTO_TEST_CASE(test_computation) { constexpr int N{5}; auto grad_polar_coords = Image<Vector2f>{N, N}; const Point2f c = grad_polar_coords.sizes().cast<float>() / 2.f; const auto theta = atan2(0 - c.y(), 0 - c.x()); // Set all gradients to zero except at coords (gx, gy). for (int y = 0; y < grad_polar_coords.height(); ++y) for (int x = 0; x < grad_polar_coords.width(); ++x) grad_polar_coords(x, y) = Vector2f::Zero(); grad_polar_coords(0, 0) = Vector2f{1.f, theta}; auto feature = OERegion{c, 1.f}; auto sift = ComputeSIFTDescriptor<>{}(feature, grad_polar_coords); BOOST_CHECK(sift.matrix() != decltype(sift)::Zero()); } BOOST_AUTO_TEST_SUITE_END()
// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2015-2017 David Ok <[email protected]> // // 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/. // ========================================================================== // #define BOOST_TEST_MODULE "FeatureDescriptors/SIFT Descriptor" #include <DO/Sara/FeatureDescriptors/SIFT.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace DO::Sara; BOOST_AUTO_TEST_SUITE(TestSIFTDescriptors) BOOST_AUTO_TEST_CASE(test_computation) { constexpr int N{5}; auto grad_polar_coords = Image<Vector2f>{N, N}; const Point2f c = grad_polar_coords.sizes().cast<float>() / 2.f; const auto theta = atan2(0 - c.y(), 0 - c.x()); // Set all gradients to zero except at coords (gx, gy). for (int y = 0; y < grad_polar_coords.height(); ++y) for (int x = 0; x < grad_polar_coords.width(); ++x) grad_polar_coords(x, y) = Vector2f::Zero(); grad_polar_coords(0, 0) = Vector2f{1.f, theta}; // Check the API for a single feature. auto feature = OERegion{c, 1.f}; auto sift = ComputeSIFTDescriptor<>{}(feature, grad_polar_coords); BOOST_CHECK(sift.matrix() != decltype(sift)::Zero()); // Check the API from a list of features. auto feature_list = std::vector<OERegion>{{feature}}; auto scale_octave_pairs = std::vector<Point2i>{{0, 0}}; auto polar_gradient_pyramid = ImagePyramid<Vector2f>{}; polar_gradient_pyramid.reset(1, 1, 1.6, 1.); polar_gradient_pyramid(0, 0) = grad_polar_coords; auto sift_list = ComputeSIFTDescriptor<>{}(feature_list, scale_octave_pairs, polar_gradient_pyramid); BOOST_CHECK_EQUAL(sift_list.sizes(), Eigen::Vector2i(1, 128)); BOOST_CHECK(sift_list.matrix().row(0) == sift.transpose()); } BOOST_AUTO_TEST_SUITE_END()
add unit test.
MAINT: add unit test.
C++
mpl-2.0
DO-CV/sara,DO-CV/sara,DO-CV/sara,DO-CV/sara,DO-CV/sara,DO-CV/sara
b9f943ea32621d1333574611c9cd624d703a4470
TTKCore/musicrightareawidget.cpp
TTKCore/musicrightareawidget.cpp
#include "musicrightareawidget.h" #include "ui_musicapplication.h" #include "musicuiobject.h" #include "musiclrccontainerfordesktop.h" #include "musicvideoplaywidget.h" #include "musicdownloadstatuslabel.h" #include "musicsettingwidget.h" #include "musicmessagebox.h" #include "musicconnectionpool.h" #include <QPropertyAnimation> MusicRightAreaWidget::MusicRightAreaWidget(QWidget *parent) : QWidget(parent), m_videoPlayer(nullptr) { m_supperClass = parent; m_lrcDisplayAll = false; m_musiclrcfordesktop = new MusicLrcContainerForDesktop(parent); m_downloadStatusLabel = new MusicDownloadStatusLabel(parent); m_setting = new MusicSettingWidget(this); connect(m_setting, SIGNAL(parameterSettingChanged()), parent, SLOT(getParameterSetting())); M_CONNECTION->setValue("MusicRightAreaWidget", this); M_CONNECTION->poolConnect("MusicSongSearchOnlineTableWidget", "MusicRightAreaWidget"); } MusicRightAreaWidget::~MusicRightAreaWidget() { delete m_setting; delete m_videoPlayer; delete m_downloadStatusLabel; delete m_musiclrcfordesktop; } void MusicRightAreaWidget::setupUi(Ui::MusicApplication* ui) { m_ui = ui; m_downloadStatusLabel->setMovieLabel(m_ui->showDownloadGif); ui->lrcDisplayAllButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->lrcDisplayAllButton->setIconSize(QSize(15, 56)); connect(ui->lrcDisplayAllButton, SIGNAL(clicked()), SLOT(musicLrcDisplayAllButtonClicked())); ui->musicSearchBackButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicSearchBackButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); ui->musicSearchBackButton->setIconSize(QSize(25, 25)); ui->musicSearchBackButton->setIcon(QIcon(QString::fromUtf8(":/image/back"))); // connect(ui->musicSearchBackButton, SIGNAL(clicked()), SLOT(musicSearchRefreshButtonRefreshed())); ui->musicSearchRefreshButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicSearchRefreshButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); ui->musicSearchRefreshButton->setIconSize(QSize(25, 25)); ui->musicSearchRefreshButton->setIcon(QIcon(QString::fromUtf8(":/image/flash"))); connect(ui->musicSearchRefreshButton, SIGNAL(clicked()), SLOT(musicSearchRefreshButtonRefreshed())); ui->musicIndexWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicIndexWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); connect(ui->musicIndexWidgetButton, SIGNAL(clicked()), SLOT(musicIndexWidgetButtonSearched())); ui->musicSearchWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); connect(ui->musicSearchWidgetButton, SIGNAL(clicked()), SLOT(musicSearchWidgetButtonSearched())); ui->musicLrcWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicLrcWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); connect(ui->musicLrcWidgetButton, SIGNAL(clicked()), SLOT(musicLrcWidgetButtonSearched())); ui->vedioWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); connect(ui->vedioWidgetButton, SIGNAL(clicked()), SLOT(musicVideoWidgetButtonSearched())); /////////////////////////////////////////////////////// connect(m_musiclrcfordesktop, SIGNAL(theCurrentLrcUpdated()), m_supperClass, SLOT(musicCurrentLrcUpdated())); connect(m_musiclrcfordesktop, SIGNAL(changeCurrentLrcColorSetting()), m_supperClass, SLOT(musicSetting())); connect(m_musiclrcfordesktop, SIGNAL(changeCurrentLrcColorCustom()), m_setting, SLOT(changeDesktopLrcWidget())); connect(m_musiclrcfordesktop, SIGNAL(desktopLrcClosed()), SIGNAL(desktopLrcClosed())); connect(m_musiclrcfordesktop, SIGNAL(setWindowLockedChanged(bool)), SIGNAL(lockDesktopLrc(bool))); /////////////////////////////////////////////////////// connect(ui->musiclrccontainerforinline, SIGNAL(changeCurrentLrcColorCustom()), m_setting, SLOT(changeInlineLrcWidget())); connect(ui->musiclrccontainerforinline, SIGNAL(theCurrentLrcUpdated()), m_supperClass, SLOT(musicCurrentLrcUpdated())); connect(ui->musiclrccontainerforinline, SIGNAL(theArtBgHasChanged()), SIGNAL(updateBgThemeDownload())); connect(ui->musiclrccontainerforinline, SIGNAL(changeCurrentLrcColorSetting()), m_supperClass, SLOT(musicSetting())); connect(ui->musiclrccontainerforinline, SIGNAL(updateCurrentTime(qint64)), m_supperClass, SLOT(updateCurrentTime(qint64))); connect(ui->musicSongSearchLine, SIGNAL(enterFinished(QString)), SLOT(songResearchButtonSearched(QString))); /////////////////////////////////////////////////////// } void MusicRightAreaWidget::stopLrcMask() const { if( checkSettingParameterValue() ) { m_ui->musiclrccontainerforinline->stopLrcMask(); m_musiclrcfordesktop->stopLrcMask(); } } void MusicRightAreaWidget::startTimerClock() const { if( checkSettingParameterValue() ) { m_ui->musiclrccontainerforinline->startTimerClock(); m_musiclrcfordesktop->startTimerClock(); } } void MusicRightAreaWidget::showPlayStatus(bool status) const { m_musiclrcfordesktop->showPlayStatus(status); } void MusicRightAreaWidget::setDestopLrcVisible(const QString &status) const { setDestopLrcVisible( status == "true" ? true : false); } bool MusicRightAreaWidget::getDestopLrcVisible() const { return m_musiclrcfordesktop->isVisible(); } void MusicRightAreaWidget::setInlineLrcVisible(const QString &status) const { m_ui->musiclrccontainerforinline->setVisible(status == "true" ? true : false); } bool MusicRightAreaWidget::getInlineLrcVisible() const { m_ui->musiclrccontainerforinline->isVisible(); } void MusicRightAreaWidget::setSettingParameter() const { m_musiclrcfordesktop->setSettingParameter(); m_ui->musiclrccontainerforinline->setSettingParameter(); } bool MusicRightAreaWidget::checkSettingParameterValue() const { return ( M_SETTING->value(MusicSettingManager::ShowInlineLrcChoiced).toBool() || M_SETTING->value(MusicSettingManager::ShowDesktopLrcChoiced).toBool() ) ? true : false; } void MusicRightAreaWidget::updateCurrentLrc(qint64 current, qint64 total, bool playStatus) const { m_ui->musiclrccontainerforinline->setCurrentTime(current); //Direct access to the audio file is the total time, in milliseconds QString currentLrc, laterLrc; qint64 intervalTime; if(m_ui->musiclrccontainerforinline->findText(total, currentLrc, laterLrc, intervalTime)) { //If this is a new line of the lyrics, then restart lyrics display mask if(currentLrc != m_ui->musiclrccontainerforinline->text()) { if(!playStatus) { m_ui->musiclrccontainerforinline->updateCurrentLrc(intervalTime); } m_musiclrcfordesktop->setCurrentTime(intervalTime); m_musiclrcfordesktop->updateCurrentLrc(currentLrc, laterLrc, intervalTime); } } } void MusicRightAreaWidget::loadCurrentSongLrc(const QString &name, const QString &path) const { if( checkSettingParameterValue() ) { m_ui->musiclrccontainerforinline->stopLrcMask(); m_ui->musiclrccontainerforinline->setCurrentSongName( name ); m_ui->musiclrccontainerforinline->transLrcFileToTime( path.trimmed() ); m_musiclrcfordesktop->setCurrentSongName( name ); } } void MusicRightAreaWidget::setSongSpeedAndSlow(qint64 time) const { m_ui->musiclrccontainerforinline->setSongSpeedAndSlow(time); } void MusicRightAreaWidget::musicCheckHasLrcAlready() const { m_downloadStatusLabel->musicCheckHasLrcAlready(); } void MusicRightAreaWidget::showSettingWidget() const { m_setting->initControllerParameter(); m_setting->exec(); } void MusicRightAreaWidget::getParameterSetting() const { setSettingParameter(); bool config = M_SETTING->value(MusicSettingManager::ShowInlineLrcChoiced).toBool(); m_ui->musiclrccontainerforinline->setVisible(config); config = M_SETTING->value(MusicSettingManager::ShowDesktopLrcChoiced).toBool(); m_musiclrcfordesktop->setVisible(config); m_ui->musicDesktopLrc->setChecked(config); } void MusicRightAreaWidget::setDestopLrcVisible(bool v) const { m_ui->musicDesktopLrc->setChecked(v); m_musiclrcfordesktop->setVisible(v); m_musiclrcfordesktop->initCurrentLrc(); M_SETTING->setValue(MusicSettingManager::ShowDesktopLrcChoiced, v); } void MusicRightAreaWidget::setWindowLockedChanged() { m_musiclrcfordesktop->setWindowLockedChanged(); } void MusicRightAreaWidget::deleteVideoWidget() { delete m_videoPlayer; m_videoPlayer = nullptr; } void MusicRightAreaWidget::musicSearchButtonSearched() { QString searchedQString = m_ui->musicSongSearchLine->text().trimmed(); //The string searched wouldn't allow to be none if( !searchedQString.isEmpty() && searchedQString != tr("please input search text") ) { musicButtonStyleClear(); m_ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); m_ui->SurfaceStackedWidget->setCurrentIndex(1); createVideoWidget(false); m_ui->songSearchWidget->startSearchQuery(searchedQString); } else { MusicMessageBox message; message.setText(tr("please input search text")); message.exec(); } } void MusicRightAreaWidget::songResearchButtonSearched(const QString &name) { m_ui->musicSongSearchLine->setText(name); musicSearchButtonSearched(); } void MusicRightAreaWidget::musicIndexWidgetButtonSearched() { musicButtonStyleClear(); m_ui->musicIndexWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); //Show the first index of widget m_ui->SurfaceStackedWidget->setCurrentIndex(0); createVideoWidget(false); } void MusicRightAreaWidget::musicSearchWidgetButtonSearched() { musicButtonStyleClear(); m_ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); //Show searched song lists m_ui->SurfaceStackedWidget->setCurrentIndex(1); createVideoWidget(false); } void MusicRightAreaWidget::musicLrcWidgetButtonSearched() { musicButtonStyleClear(); m_ui->musicLrcWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); //Show lrc display widget m_ui->SurfaceStackedWidget->setCurrentIndex(2); createVideoWidget(false); m_ui->musicWindowSpace->setVisible(false); m_ui->lrcDisplayAllButton->setIcon(QIcon(":/lrc/lrcDisplayAll")); m_ui->lrcDisplayAllButton->setVisible(true); emit updateBgThemeDownload(); } void MusicRightAreaWidget::musicVideoWidgetButtonSearched() { musicButtonStyleClear(); m_ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); createVideoWidget(true); } void MusicRightAreaWidget::musicSearchRefreshButtonRefreshed() { createVideoWidget(false); //Refresh the search music song musicSearchButtonSearched(); } void MusicRightAreaWidget::createVideoWidget(bool create) { if(create) { if(m_videoPlayer) { return; } deleteVideoWidget(); m_videoPlayer = new MusicVideoPlayWidget(false); m_videoPlayer->setObjectToClose(this); m_videoPlayer->blockMoveOption(true); m_ui->SurfaceStackedWidget->addWidget(m_videoPlayer); m_ui->SurfaceStackedWidget->setCurrentIndex(3); } else if(m_videoPlayer) { m_ui->SurfaceStackedWidget->removeWidget(m_videoPlayer); deleteVideoWidget(); } m_ui->musicWindowSpace->setVisible(true); m_ui->lrcDisplayAllButton->setVisible(false); if(m_lrcDisplayAll) { musicLrcDisplayAllButtonClicked(); } emit updateBackgroundTheme(); } void MusicRightAreaWidget::musicButtonStyleClear() { m_ui->musicIndexWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); m_ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); m_ui->musicLrcWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); m_ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); } void MusicRightAreaWidget::musicVideoButtonSearched(const QString &name) { musicVideoWidgetButtonSearched(); if(m_videoPlayer) { m_videoPlayer->videoResearchButtonSearched(name); } } void MusicRightAreaWidget::musicVideoSetPopup(bool popup) { if(popup) { createVideoWidget(false); musicButtonStyleClear(); m_ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); m_videoPlayer = new MusicVideoPlayWidget(true); m_videoPlayer->setObjectToClose(this); m_videoPlayer->show(); } else { createVideoWidget(false); createVideoWidget(true); } } void MusicRightAreaWidget::musicVideoFullscreen(bool full) { m_videoPlayer->resizeWindow(full); m_videoPlayer->blockMoveOption(full); } void MusicRightAreaWidget::musicLrcDisplayAllButtonClicked() { m_lrcDisplayAll = !m_lrcDisplayAll; m_ui->songsContainer->setHidden(m_lrcDisplayAll); QPropertyAnimation *lrcDisplayAllAnimation = new QPropertyAnimation(m_ui->lrcDisplayAllButton, "pos", this); lrcDisplayAllAnimation->setDuration(100); lrcDisplayAllAnimation->setStartValue(QPoint(m_lrcDisplayAll ? 392 : 61, 320)); lrcDisplayAllAnimation->setEndValue(QPoint(m_lrcDisplayAll ? 61 : 392, 320)); lrcDisplayAllAnimation->start(); // m_ui->lrcDisplayAllButton->move(m_lrcDisplayAll ? 61 : 392, 320); m_ui->SurfaceStackedWidget->setGeometry(m_lrcDisplayAll ? 60 : 390, 144, m_lrcDisplayAll ? 871: 541, 455); m_ui->musiclrccontainerforinline->resizeWidth(m_lrcDisplayAll ? 330 : 0); m_ui->lrcDisplayAllButton->setIcon(QIcon(m_lrcDisplayAll ? ":/lrc/lrcDisplayNor" : ":/lrc/lrcDisplayAll")); }
#include "musicrightareawidget.h" #include "ui_musicapplication.h" #include "musicuiobject.h" #include "musiclrccontainerfordesktop.h" #include "musicvideoplaywidget.h" #include "musicdownloadstatuslabel.h" #include "musicsettingwidget.h" #include "musicmessagebox.h" #include "musicconnectionpool.h" #include <QPropertyAnimation> MusicRightAreaWidget::MusicRightAreaWidget(QWidget *parent) : QWidget(parent), m_videoPlayer(nullptr) { m_supperClass = parent; m_lrcDisplayAll = false; m_musiclrcfordesktop = new MusicLrcContainerForDesktop(parent); m_downloadStatusLabel = new MusicDownloadStatusLabel(parent); m_setting = new MusicSettingWidget(this); connect(m_setting, SIGNAL(parameterSettingChanged()), parent, SLOT(getParameterSetting())); M_CONNECTION->setValue("MusicRightAreaWidget", this); M_CONNECTION->poolConnect("MusicSongSearchOnlineTableWidget", "MusicRightAreaWidget"); } MusicRightAreaWidget::~MusicRightAreaWidget() { delete m_setting; delete m_videoPlayer; delete m_downloadStatusLabel; delete m_musiclrcfordesktop; } void MusicRightAreaWidget::setupUi(Ui::MusicApplication* ui) { m_ui = ui; m_downloadStatusLabel->setMovieLabel(m_ui->showDownloadGif); ui->lrcDisplayAllButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->lrcDisplayAllButton->setIconSize(QSize(15, 56)); connect(ui->lrcDisplayAllButton, SIGNAL(clicked()), SLOT(musicLrcDisplayAllButtonClicked())); ui->musicSearchBackButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicSearchBackButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); ui->musicSearchBackButton->setIconSize(QSize(25, 25)); ui->musicSearchBackButton->setIcon(QIcon(QString::fromUtf8(":/image/back"))); // connect(ui->musicSearchBackButton, SIGNAL(clicked()), SLOT(musicSearchRefreshButtonRefreshed())); ui->musicSearchRefreshButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicSearchRefreshButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); ui->musicSearchRefreshButton->setIconSize(QSize(25, 25)); ui->musicSearchRefreshButton->setIcon(QIcon(QString::fromUtf8(":/image/flash"))); connect(ui->musicSearchRefreshButton, SIGNAL(clicked()), SLOT(musicSearchRefreshButtonRefreshed())); ui->musicIndexWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicIndexWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); connect(ui->musicIndexWidgetButton, SIGNAL(clicked()), SLOT(musicIndexWidgetButtonSearched())); ui->musicSearchWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); connect(ui->musicSearchWidgetButton, SIGNAL(clicked()), SLOT(musicSearchWidgetButtonSearched())); ui->musicLrcWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->musicLrcWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); connect(ui->musicLrcWidgetButton, SIGNAL(clicked()), SLOT(musicLrcWidgetButtonSearched())); ui->vedioWidgetButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); connect(ui->vedioWidgetButton, SIGNAL(clicked()), SLOT(musicVideoWidgetButtonSearched())); /////////////////////////////////////////////////////// connect(m_musiclrcfordesktop, SIGNAL(theCurrentLrcUpdated()), m_supperClass, SLOT(musicCurrentLrcUpdated())); connect(m_musiclrcfordesktop, SIGNAL(changeCurrentLrcColorSetting()), m_supperClass, SLOT(musicSetting())); connect(m_musiclrcfordesktop, SIGNAL(changeCurrentLrcColorCustom()), m_setting, SLOT(changeDesktopLrcWidget())); connect(m_musiclrcfordesktop, SIGNAL(desktopLrcClosed()), SIGNAL(desktopLrcClosed())); connect(m_musiclrcfordesktop, SIGNAL(setWindowLockedChanged(bool)), SIGNAL(lockDesktopLrc(bool))); /////////////////////////////////////////////////////// connect(ui->musiclrccontainerforinline, SIGNAL(changeCurrentLrcColorCustom()), m_setting, SLOT(changeInlineLrcWidget())); connect(ui->musiclrccontainerforinline, SIGNAL(theCurrentLrcUpdated()), m_supperClass, SLOT(musicCurrentLrcUpdated())); connect(ui->musiclrccontainerforinline, SIGNAL(theArtBgHasChanged()), SIGNAL(updateBgThemeDownload())); connect(ui->musiclrccontainerforinline, SIGNAL(changeCurrentLrcColorSetting()), m_supperClass, SLOT(musicSetting())); connect(ui->musiclrccontainerforinline, SIGNAL(updateCurrentTime(qint64)), m_supperClass, SLOT(updateCurrentTime(qint64))); connect(ui->musicSongSearchLine, SIGNAL(enterFinished(QString)), SLOT(songResearchButtonSearched(QString))); /////////////////////////////////////////////////////// } void MusicRightAreaWidget::stopLrcMask() const { if( checkSettingParameterValue() ) { m_ui->musiclrccontainerforinline->stopLrcMask(); m_musiclrcfordesktop->stopLrcMask(); } } void MusicRightAreaWidget::startTimerClock() const { if( checkSettingParameterValue() ) { m_ui->musiclrccontainerforinline->startTimerClock(); m_musiclrcfordesktop->startTimerClock(); } } void MusicRightAreaWidget::showPlayStatus(bool status) const { m_musiclrcfordesktop->showPlayStatus(status); } void MusicRightAreaWidget::setDestopLrcVisible(const QString &status) const { setDestopLrcVisible( status == "true" ? true : false); } bool MusicRightAreaWidget::getDestopLrcVisible() const { return m_musiclrcfordesktop->isVisible(); } void MusicRightAreaWidget::setInlineLrcVisible(const QString &status) const { m_ui->musiclrccontainerforinline->setVisible(status == "true" ? true : false); } bool MusicRightAreaWidget::getInlineLrcVisible() const { return m_ui->musiclrccontainerforinline->isVisible(); } void MusicRightAreaWidget::setSettingParameter() const { m_musiclrcfordesktop->setSettingParameter(); m_ui->musiclrccontainerforinline->setSettingParameter(); } bool MusicRightAreaWidget::checkSettingParameterValue() const { return ( M_SETTING->value(MusicSettingManager::ShowInlineLrcChoiced).toBool() || M_SETTING->value(MusicSettingManager::ShowDesktopLrcChoiced).toBool() ) ? true : false; } void MusicRightAreaWidget::updateCurrentLrc(qint64 current, qint64 total, bool playStatus) const { m_ui->musiclrccontainerforinline->setCurrentTime(current); //Direct access to the audio file is the total time, in milliseconds QString currentLrc, laterLrc; qint64 intervalTime; if(m_ui->musiclrccontainerforinline->findText(total, currentLrc, laterLrc, intervalTime)) { //If this is a new line of the lyrics, then restart lyrics display mask if(currentLrc != m_ui->musiclrccontainerforinline->text()) { if(!playStatus) { m_ui->musiclrccontainerforinline->updateCurrentLrc(intervalTime); } m_musiclrcfordesktop->setCurrentTime(intervalTime); m_musiclrcfordesktop->updateCurrentLrc(currentLrc, laterLrc, intervalTime); } } } void MusicRightAreaWidget::loadCurrentSongLrc(const QString &name, const QString &path) const { if( checkSettingParameterValue() ) { m_ui->musiclrccontainerforinline->stopLrcMask(); m_ui->musiclrccontainerforinline->setCurrentSongName( name ); m_ui->musiclrccontainerforinline->transLrcFileToTime( path.trimmed() ); m_musiclrcfordesktop->setCurrentSongName( name ); } } void MusicRightAreaWidget::setSongSpeedAndSlow(qint64 time) const { m_ui->musiclrccontainerforinline->setSongSpeedAndSlow(time); } void MusicRightAreaWidget::musicCheckHasLrcAlready() const { m_downloadStatusLabel->musicCheckHasLrcAlready(); } void MusicRightAreaWidget::showSettingWidget() const { m_setting->initControllerParameter(); m_setting->exec(); } void MusicRightAreaWidget::getParameterSetting() const { setSettingParameter(); bool config = M_SETTING->value(MusicSettingManager::ShowInlineLrcChoiced).toBool(); m_ui->musiclrccontainerforinline->setVisible(config); config = M_SETTING->value(MusicSettingManager::ShowDesktopLrcChoiced).toBool(); m_musiclrcfordesktop->setVisible(config); m_ui->musicDesktopLrc->setChecked(config); } void MusicRightAreaWidget::setDestopLrcVisible(bool v) const { m_ui->musicDesktopLrc->setChecked(v); m_musiclrcfordesktop->setVisible(v); m_musiclrcfordesktop->initCurrentLrc(); M_SETTING->setValue(MusicSettingManager::ShowDesktopLrcChoiced, v); } void MusicRightAreaWidget::setWindowLockedChanged() { m_musiclrcfordesktop->setWindowLockedChanged(); } void MusicRightAreaWidget::deleteVideoWidget() { delete m_videoPlayer; m_videoPlayer = nullptr; } void MusicRightAreaWidget::musicSearchButtonSearched() { QString searchedQString = m_ui->musicSongSearchLine->text().trimmed(); //The string searched wouldn't allow to be none if( !searchedQString.isEmpty() && searchedQString != tr("please input search text") ) { musicButtonStyleClear(); m_ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); m_ui->SurfaceStackedWidget->setCurrentIndex(1); createVideoWidget(false); m_ui->songSearchWidget->startSearchQuery(searchedQString); } else { MusicMessageBox message; message.setText(tr("please input search text")); message.exec(); } } void MusicRightAreaWidget::songResearchButtonSearched(const QString &name) { m_ui->musicSongSearchLine->setText(name); musicSearchButtonSearched(); } void MusicRightAreaWidget::musicIndexWidgetButtonSearched() { musicButtonStyleClear(); m_ui->musicIndexWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); //Show the first index of widget m_ui->SurfaceStackedWidget->setCurrentIndex(0); createVideoWidget(false); } void MusicRightAreaWidget::musicSearchWidgetButtonSearched() { musicButtonStyleClear(); m_ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); //Show searched song lists m_ui->SurfaceStackedWidget->setCurrentIndex(1); createVideoWidget(false); } void MusicRightAreaWidget::musicLrcWidgetButtonSearched() { musicButtonStyleClear(); m_ui->musicLrcWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); //Show lrc display widget m_ui->SurfaceStackedWidget->setCurrentIndex(2); createVideoWidget(false); m_ui->musicWindowSpace->setVisible(false); m_ui->lrcDisplayAllButton->setIcon(QIcon(":/lrc/lrcDisplayAll")); m_ui->lrcDisplayAllButton->setVisible(true); emit updateBgThemeDownload(); } void MusicRightAreaWidget::musicVideoWidgetButtonSearched() { musicButtonStyleClear(); m_ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); createVideoWidget(true); } void MusicRightAreaWidget::musicSearchRefreshButtonRefreshed() { createVideoWidget(false); //Refresh the search music song musicSearchButtonSearched(); } void MusicRightAreaWidget::createVideoWidget(bool create) { if(create) { if(m_videoPlayer) { return; } deleteVideoWidget(); m_videoPlayer = new MusicVideoPlayWidget(false); m_videoPlayer->setObjectToClose(this); m_videoPlayer->blockMoveOption(true); m_ui->SurfaceStackedWidget->addWidget(m_videoPlayer); m_ui->SurfaceStackedWidget->setCurrentIndex(3); } else if(m_videoPlayer) { m_ui->SurfaceStackedWidget->removeWidget(m_videoPlayer); deleteVideoWidget(); } m_ui->musicWindowSpace->setVisible(true); m_ui->lrcDisplayAllButton->setVisible(false); if(m_lrcDisplayAll) { musicLrcDisplayAllButtonClicked(); } emit updateBackgroundTheme(); } void MusicRightAreaWidget::musicButtonStyleClear() { m_ui->musicIndexWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); m_ui->musicSearchWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); m_ui->musicLrcWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); m_ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle07); } void MusicRightAreaWidget::musicVideoButtonSearched(const QString &name) { musicVideoWidgetButtonSearched(); if(m_videoPlayer) { m_videoPlayer->videoResearchButtonSearched(name); } } void MusicRightAreaWidget::musicVideoSetPopup(bool popup) { if(popup) { createVideoWidget(false); musicButtonStyleClear(); m_ui->vedioWidgetButton->setStyleSheet(MusicUIObject::MPushButtonStyle16); m_videoPlayer = new MusicVideoPlayWidget(true); m_videoPlayer->setObjectToClose(this); m_videoPlayer->show(); } else { createVideoWidget(false); createVideoWidget(true); } } void MusicRightAreaWidget::musicVideoFullscreen(bool full) { m_videoPlayer->resizeWindow(full); m_videoPlayer->blockMoveOption(full); } void MusicRightAreaWidget::musicLrcDisplayAllButtonClicked() { m_lrcDisplayAll = !m_lrcDisplayAll; m_ui->songsContainer->setHidden(m_lrcDisplayAll); QPropertyAnimation *lrcDisplayAllAnimation = new QPropertyAnimation(m_ui->lrcDisplayAllButton, "pos", this); lrcDisplayAllAnimation->setDuration(100); lrcDisplayAllAnimation->setStartValue(QPoint(m_lrcDisplayAll ? 392 : 61, 320)); lrcDisplayAllAnimation->setEndValue(QPoint(m_lrcDisplayAll ? 61 : 392, 320)); lrcDisplayAllAnimation->start(); // m_ui->lrcDisplayAllButton->move(m_lrcDisplayAll ? 61 : 392, 320); m_ui->SurfaceStackedWidget->setGeometry(m_lrcDisplayAll ? 60 : 390, 144, m_lrcDisplayAll ? 871: 541, 455); m_ui->musiclrccontainerforinline->resizeWidth(m_lrcDisplayAll ? 330 : 0); m_ui->lrcDisplayAllButton->setIcon(QIcon(m_lrcDisplayAll ? ":/lrc/lrcDisplayNor" : ":/lrc/lrcDisplayAll")); }
add return value[333125]
add return value[333125]
C++
lgpl-2.1
Greedysky/Musicplayer,Greedysky/Musicplayer,Greedysky/Musicplayer
f6921c5efe516982f8536b29bac6450efde7953a
Include/X86/Parameters.hh
Include/X86/Parameters.hh
#ifndef X86_PARAMETERS_HH #define X86_PARAMETERS_HH #ifdef __ASSEMBLER__ # define U(x) x #else # define U(x) x##u #endif // // Memory map: // // ---------- // 0xffffffff -- recursive page directory // ... // 0xffc00000 -- end of page directory mapping // ... // 0xffffeffc -- kernel stack start // ... // 0xc0501000 -- kernel heap start // ... // 0xc0000000 -- kernel start // ... // 0xbffffffc -- user stack start (grows down) // ... // 0x40000000 -- user heap start // ... // 0x10000000 -- user code start // #define KernelCodeSegment 0x08 #define KernelDataSegment 0x10 #define UserCodeSegment 0x18 #define UserDataSegment 0x20 #define KernelVirtualBase U(0xc0000000) #define KernelLoadAddress U(0x100000) #define KernelPageNumber (KernelVirtualBase >> 22) #define PageSize U(4096) #define PageMask (PageSize - 1) #define PageTableBase U(0xffc00000) #define PageDirectoryBase U(0xfffff000) #define KernelStackStart U(0xffffeffc) #define KernelStackSize U(0x10000) #define KernelHeapStart U(0xc0501000) #define UserStackStart U(0xbffffffc) #define UserHeapStart U(0x40000000) #define CodeStart U(0x10000000) #define CodeSize U(0x400000) #define MapStart (KernelStackStart - KernelStackSize) #define InitialStackSize U(0x2000) #endif
#ifndef X86_PARAMETERS_HH #define X86_PARAMETERS_HH #ifdef __ASSEMBLER__ # define U(x) x #else # define U(x) x##u #endif // // Memory map: // // ---------- // 0xffffffff -- recursive page directory // ... // 0xffc00000 -- end of page directory mapping // 0xffbffc00 -- secondary page directory (for create process) // ... // 0xff800000 -- end of secondary pd, stack start // ... // 0xc0501000 -- kernel heap start // ... // 0xc0000000 // #define KernelCodeSegment 0x08 #define KernelDataSegment 0x10 #define UserCodeSegment 0x18 #define UserDataSegment 0x20 #define KernelVirtualBase U(0xc0000000) #define KernelLoadAddress U(0x100000) #define KernelPageNumber (KernelVirtualBase >> 22) #define PageSize U(4096) #define PageMask (PageSize - 1) #define PageTableBase U(0xffc00000) #define PageDirectoryBase U(0xfffff000) #define SecondaryPageTableBase U(0xff800000) #define SecondaryPageDirectoryBase U(0xffbffc0) #define KernelStackStart SecondaryPageTableBase #define KernelStackSize U(0x10000) #define KernelHeapStart U(0xc0501000) #define UserStackStart U(0xbffffffc) #define UserHeapStart U(0x40000000) #define CodeStart U(0x10000000) #define MapStart (KernelStackStart - KernelStackSize) #define InitialStackSize U(0x2000) #endif
Revert "Update memory map"
Revert "Update memory map" This reverts commit 005c6efdda2b7e08a084e06551ed41e25aaa2dd7.
C++
bsd-2-clause
ahoka/esrtk,ahoka/esrtk,ahoka/esrtk
d1be885278f1debf896bb48cff37e23245ff55d4
test/SmallObj/SmallSingleton.cpp
test/SmallObj/SmallSingleton.cpp
//////////////////////////////////////////////////////////////////////////////// // The Loki Library // Copyright (c) 2005 Richard Sposato // Copyright (c) 2005 Peter Kmmel // Permission to use, copy, modify, distribute and sell this software for any // purpose is hereby granted without fee, provided that the above copyright // notice appear in all copies and that both that copyright notice and this // permission notice appear in supporting documentation. // The authors make no representations about the // suitability of this software for any purpose. It is provided "as is" // without express or implied warranty. //////////////////////////////////////////////////////////////////////////////// // $Header$ #include "../../include/loki/SmallObj.h" #include "../../include/loki/Singleton.h" #include <iostream> // define DO_EXTRA_LOKI_TESTS in src/SmallObj.cpp to get // a message when a SmallObject is created/deleted. using namespace std; // ---------------------------------------------------------------------------- // // FollowIntoDeath policy // // ---------------------------------------------------------------------------- typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL, LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE, LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::FollowIntoDeath::With<Loki::DefaultLifetime>::AsMasterLifetime > MasterObject; // this is default so you could also use: // typedef Loki::SmallValueObject<> MasterObject; class FollowerSingleton : public MasterObject { public: typedef Loki::SingletonHolder< FollowerSingleton, Loki::CreateUsingNew, Loki::FollowIntoDeath::AfterMaster<FollowerSingleton::ObjAllocatorSingleton>::IsDestroyed, LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL > MySmallSingleton; /// Returns reference to the singleton. inline static FollowerSingleton & Instance( void ) { return MySmallSingleton::Instance(); } FollowerSingleton( void ) { cout << "FollowerSingleton created" << endl; } ~FollowerSingleton( void ) { cout << "~FollowerSingleton" << endl; } void DoThat( void ) { cout << "FollowerSingleton::DoThat" << endl << endl; } private: char m_stuff[ 16 ]; }; // ---------------------------------------------------------------------------- // // DieOrder policy // // ---------------------------------------------------------------------------- typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL, LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE, LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::DieOrder::Last > DieLastObject; class DieFirstSingleton : public DieLastObject { public: typedef Loki::SingletonHolder< DieFirstSingleton, Loki::CreateUsingNew, Loki::DieOrder::First, LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL > MySmallSingleton; /// Returns reference to the singleton. inline static DieFirstSingleton & Instance( void ) { return MySmallSingleton::Instance(); } DieFirstSingleton( void ) { cout << "DieFirstSingleton created" << endl; } ~DieFirstSingleton( void ) { cout << "~DieFirstSingleton" << endl; } void DoThat( void ) { cout << "DieFirstSingleton::DoThat" << endl << endl; } private: char m_stuff[ 16 ]; }; // ---------------------------------------------------------------------------- // // SingletonWithLongevity policy // // ---------------------------------------------------------------------------- typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL, LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE, LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::SingletonWithLongevity > LongLivedObject; class LongLivedSingleton : public LongLivedObject { public: typedef Loki::SingletonHolder< LongLivedSingleton, Loki::CreateUsingNew, Loki::SingletonWithLongevity, LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL > MySmallSingleton; /// Returns reference to the singleton. inline static LongLivedSingleton & Instance( void ) { return MySmallSingleton::Instance(); } LongLivedSingleton( void ) { cout << "LongLivedSingleton created" << endl; } ~LongLivedSingleton( void ) { cout << "~LongLivedSingleton" << endl; } void DoThat( void ) { cout << "LongLivedSingleton::DoThat" << endl << endl; } private: char m_stuff[ 16 ]; }; inline unsigned int GetLongevity( LongLivedSingleton * ) { /// @note Must return a longevity level lower than the one in SmallObj.h. return 1; } // ---------------------------------------------------------------------------- // // detect memory leaks on MSVC Ide // // ---------------------------------------------------------------------------- #ifdef _MSC_VER #include <crtdbg.h> #include <cassert> void heap_debug() { int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; //tmpFlag |= _CRTDBG_CHECK_MasterLWMasterYS_DF; // Turn off CRT block checking bit tmpFlag &= ~_CRTDBG_CHECK_CRT_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag ); } #endif // ---------------------------------------------------------------------------- // // main // // ---------------------------------------------------------------------------- int main() { #ifdef _MSC_VER heap_debug(); #endif cout << endl << "This program tests the three recommended lifetime policies for Loki's " << endl << "Small-Object Allocator and singleton objects that are derived " << endl << "from SmallObject or SmallValueObject." << endl << endl << "Use one of the following lifetime policies" << endl << "to manage the lifetime dependency:" << endl << endl << "1. FollowIntoDeath:" << endl << " SmallObject has " << endl << " FollowIntoDeath::With<LIFETIME>::AsMasterLiftime policy" << endl << " and the derived Singleton has " << endl << " FollowIntoDeath::After<MASTERSINGLETON>::IsDestroyed policy" << endl << " This is tested by the FollowerSingleton class." << endl << endl << "2. DieOrder:" << endl << " SmallObject has " << endl << " DieOrder::Last policy " << endl << " and the derived Singleton has " << endl << " DieOrder::First" << endl << " This is tested by the DieFirstSingleton class." << endl << endl << "3. Both SmallObject and derived Singleton use SingletonWithLongevity policy." << endl << " This is tested by the LongLivedSingleton class." << endl << endl << endl << "If this program executes without crashing or asserting" << endl << "at exit time, then all 3 policies work." << endl << endl; FollowerSingleton::Instance().DoThat(); DieFirstSingleton::Instance().DoThat(); LongLivedSingleton::Instance().DoThat(); system("PAUSE"); cout << endl<< endl << "now leaving main" << endl << endl; return 0; } // ---------------------------------------------------------------------------- // $Log$ // Revision 1.6 2005/11/02 14:15:44 syntheticpp // use new singleton lifetime policies // // Revision 1.5 2005/11/02 14:11:18 syntheticpp // use new singleton lifetime policies // // Revision 1.4 2005/11/02 13:58:18 syntheticpp // use new singleton lifetime policies // // Revision 1.3 2005/10/30 14:03:23 syntheticpp // replace tabs space // // Revision 1.2 2005/10/29 10:21:46 syntheticpp // find loki include files without a correct sreach pathand some small fixes // // Revision 1.1 2005/10/14 18:48:10 rich_sposato // Adding SmallSingleton test project to CVS. //
//////////////////////////////////////////////////////////////////////////////// // The Loki Library // Copyright (c) 2005 Richard Sposato // Copyright (c) 2005 Peter Kmmel // Permission to use, copy, modify, distribute and sell this software for any // purpose is hereby granted without fee, provided that the above copyright // notice appear in all copies and that both that copyright notice and this // permission notice appear in supporting documentation. // The authors make no representations about the // suitability of this software for any purpose. It is provided "as is" // without express or implied warranty. //////////////////////////////////////////////////////////////////////////////// // $Header$ #include "../../include/loki/SmallObj.h" #include "../../include/loki/Singleton.h" #include <iostream> // define DO_EXTRA_LOKI_TESTS in src/SmallObj.cpp to get // a message when a SmallObject is created/deleted. using namespace std; // ---------------------------------------------------------------------------- // // FollowIntoDeath policy // // ---------------------------------------------------------------------------- typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL, LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE, LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::FollowIntoDeath::With<Loki::DefaultLifetime>::AsMasterLifetime > MasterObject; // this is default so you could also use: // typedef Loki::SmallValueObject<> MasterObject; class FollowerSingleton : public MasterObject { public: typedef Loki::SingletonHolder< FollowerSingleton, Loki::CreateUsingNew, Loki::FollowIntoDeath::AfterMaster<FollowerSingleton::ObjAllocatorSingleton>::IsDestroyed, LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL > MySmallSingleton; /// Returns reference to the singleton. inline static FollowerSingleton & Instance( void ) { return MySmallSingleton::Instance(); } FollowerSingleton( void ) { cout << "FollowerSingleton created" << endl; } ~FollowerSingleton( void ) { cout << "~FollowerSingleton" << endl; } void DoThat( void ) { cout << "FollowerSingleton::DoThat" << endl << endl; } private: char m_stuff[ 16 ]; }; // ---------------------------------------------------------------------------- // // DieOrder policy // // ---------------------------------------------------------------------------- typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL, LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE, LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::DieOrder::Last > DieLastObject; class DieFirstSingleton : public DieLastObject { public: typedef Loki::SingletonHolder< DieFirstSingleton, Loki::CreateUsingNew, Loki::DieOrder::First, LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL > MySmallSingleton; /// Returns reference to the singleton. inline static DieFirstSingleton & Instance( void ) { return MySmallSingleton::Instance(); } DieFirstSingleton( void ) { cout << "DieFirstSingleton created" << endl; } ~DieFirstSingleton( void ) { cout << "~DieFirstSingleton" << endl; } void DoThat( void ) { cout << "DieFirstSingleton::DoThat" << endl << endl; } private: char m_stuff[ 16 ]; }; // ---------------------------------------------------------------------------- // // SingletonWithLongevity policy // // ---------------------------------------------------------------------------- typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL, LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE, LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::SingletonWithLongevity > LongLivedObject; class LongLivedSingleton : public LongLivedObject { public: typedef Loki::SingletonHolder< LongLivedSingleton, Loki::CreateUsingNew, Loki::SingletonWithLongevity, LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL > MySmallSingleton; /// Returns reference to the singleton. inline static LongLivedSingleton & Instance( void ) { return MySmallSingleton::Instance(); } LongLivedSingleton( void ) { cout << "LongLivedSingleton created" << endl; } ~LongLivedSingleton( void ) { cout << "~LongLivedSingleton" << endl; } void DoThat( void ) { cout << "LongLivedSingleton::DoThat" << endl << endl; } private: char m_stuff[ 16 ]; }; inline unsigned int GetLongevity( LongLivedSingleton * ) { /// @note Must return a longevity level lower than the one in SmallObj.h. return 1; } // ---------------------------------------------------------------------------- // // detect memory leaks on MSVC Ide // // ---------------------------------------------------------------------------- #ifdef _MSC_VER #include <crtdbg.h> #include <cassert> void heap_debug() { int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; //tmpFlag |= _CRTDBG_CHECK_MasterLWMasterYS_DF; // Turn off CRT block checking bit tmpFlag &= ~_CRTDBG_CHECK_CRT_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag ); } #endif // ---------------------------------------------------------------------------- // // main // // ---------------------------------------------------------------------------- int main() { #ifdef _MSC_VER heap_debug(); #endif cout << endl << "This program tests the three recommended lifetime policies for Loki's " << endl << "Small-Object Allocator and singleton objects that are derived " << endl << "from SmallObject or SmallValueObject." << endl << endl << "Use one of the following lifetime policies" << endl << "to manage the lifetime dependency:" << endl << endl << "1. FollowIntoDeath:" << endl << " SmallObject has " << endl << " FollowIntoDeath::With<LIFETIME>::AsMasterLiftime policy" << endl << " and the derived Singleton has " << endl << " FollowIntoDeath::AfterMaster<MASTERSINGLETON>::IsDestroyed policy" << endl << " This is tested by the FollowerSingleton class." << endl << endl << "2. DieOrder:" << endl << " SmallObject has " << endl << " DieOrder::Last policy " << endl << " and the derived Singleton has " << endl << " DieOrder::First" << endl << " This is tested by the DieFirstSingleton class." << endl << endl << "3. Both SmallObject and derived Singleton use SingletonWithLongevity policy." << endl << " This is tested by the LongLivedSingleton class." << endl << endl << endl << "If this program executes without crashing or asserting" << endl << "at exit time, then all 3 policies work." << endl << endl; FollowerSingleton::Instance().DoThat(); DieFirstSingleton::Instance().DoThat(); LongLivedSingleton::Instance().DoThat(); system("PAUSE"); cout << endl<< endl << "now leaving main" << endl << endl; return 0; } // ---------------------------------------------------------------------------- // $Log$ // Revision 1.7 2005/11/02 15:00:38 syntheticpp // use new singleton lifetime policies // // Revision 1.6 2005/11/02 14:15:44 syntheticpp // use new singleton lifetime policies // // Revision 1.5 2005/11/02 14:11:18 syntheticpp // use new singleton lifetime policies // // Revision 1.4 2005/11/02 13:58:18 syntheticpp // use new singleton lifetime policies // // Revision 1.3 2005/10/30 14:03:23 syntheticpp // replace tabs space // // Revision 1.2 2005/10/29 10:21:46 syntheticpp // find loki include files without a correct sreach pathand some small fixes // // Revision 1.1 2005/10/14 18:48:10 rich_sposato // Adding SmallSingleton test project to CVS. //
use new singleton lifetime policies
use new singleton lifetime policies git-svn-id: 2bceadd671bcc8d4f7a34159d1bc3b98592acb3b@346 7ec92016-0320-0410-acc4-a06ded1c099a
C++
mit
Streamlet/ZLibWrap,Streamlet/ZLibWrap,Streamlet/ZLibWrap,Streamlet/ZLibWrap,Streamlet/ZLibWrap
51421247ace51460d5fa77e8f41651e9f7fac465
_studio/shared/umc/codec/h264_dec/src/umc_h264_au_splitter.cpp
_studio/shared/umc/codec/h264_dec/src/umc_h264_au_splitter.cpp
// Copyright (c) 2017-2018 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "umc_defs.h" #if defined (MFX_ENABLE_H264_VIDEO_DECODE) #include <memory> #include "umc_h264_au_splitter.h" #include "umc_h264_nal_spl.h" namespace UMC { /****************************************************************************************************/ // SeiPayloadArray class routine /****************************************************************************************************/ SeiPayloadArray::SeiPayloadArray() { m_payloads.reserve(3); } SeiPayloadArray::SeiPayloadArray(const SeiPayloadArray & payloads) { size_t count = payloads.GetPayloadCount(); for (size_t i = 0; i < count; i++) { AddPayload(payloads.GetPayload(i)); } } SeiPayloadArray::~SeiPayloadArray() { Release(); } size_t SeiPayloadArray::GetPayloadCount() const { return m_payloads.size(); } UMC_H264_DECODER::H264SEIPayLoad* SeiPayloadArray::GetPayload(size_t pos) const { if (pos >= m_payloads.size()) return 0; return m_payloads[pos]; } UMC_H264_DECODER::H264SEIPayLoad* SeiPayloadArray::FindPayload(SEI_TYPE type) const { int32_t pos = FindPayloadPos(type); return (pos < 0) ? 0 : GetPayload(pos); } int32_t SeiPayloadArray::FindPayloadPos(SEI_TYPE type) const { size_t count = m_payloads.size(); for (size_t i = 0; i < count; i++) { UMC_H264_DECODER::H264SEIPayLoad* payload = m_payloads[i]; if (payload->payLoadType == type) return (int32_t)i; } return -1; } void SeiPayloadArray::MovePayloadsFrom(SeiPayloadArray &payloads) { size_t count = payloads.GetPayloadCount(); for (size_t i = 0; i < count; i++) { AddPayload(payloads.GetPayload(i)); } payloads.Release(); } void SeiPayloadArray::Release() { PayloadArray::iterator iter = m_payloads.begin(); PayloadArray::iterator iter_end = m_payloads.end(); for (; iter != iter_end; ++iter) { UMC_H264_DECODER::H264SEIPayLoad* payload = *iter; payload->DecrementReference(); } m_payloads.clear(); } void SeiPayloadArray::AddPayload(UMC_H264_DECODER::H264SEIPayLoad* payload) { if (!payload) return; payload->IncrementReference(); int32_t pos = FindPayloadPos(payload->payLoadType); if (pos >= 0) // always use last payload { m_payloads[pos]->DecrementReference(); m_payloads[pos] = payload; return; } m_payloads.push_back(payload); } /****************************************************************************************************/ // SetOfSlices class routine /****************************************************************************************************/ SetOfSlices::SetOfSlices() : m_frame(0) , m_isCompleted(false) , m_isFull(false) { } SetOfSlices::SetOfSlices(const SetOfSlices& set) : m_frame(set.m_frame) , m_isCompleted(set.m_isCompleted) , m_isFull(set.m_isFull) , m_payloads(set.m_payloads) , m_pSliceQueue(set.m_pSliceQueue) { for (auto pSlice : m_pSliceQueue) { pSlice->IncrementReference(); } } SetOfSlices::~SetOfSlices() { Release(); } SetOfSlices& SetOfSlices::operator=(const SetOfSlices& set) { if (this == &set) { return *this; } *this = set; for (auto pSlice : m_pSliceQueue) { pSlice->IncrementReference(); } return *this; } H264Slice * SetOfSlices::GetSlice(size_t pos) const { if (pos >= m_pSliceQueue.size()) return nullptr; return m_pSliceQueue[pos]; } size_t SetOfSlices::GetSliceCount() const { return m_pSliceQueue.size(); } void SetOfSlices::AddSlice(H264Slice * slice) { m_pSliceQueue.push_back(slice); } void SetOfSlices::Release() { size_t count = m_pSliceQueue.size(); for (size_t sliceId = 0; sliceId < count; sliceId++) { H264Slice * slice = m_pSliceQueue[sliceId]; slice->DecrementReference(); } Reset(); } void SetOfSlices::Reset() { m_frame = 0; m_isCompleted = false; m_isFull = false; m_pSliceQueue.clear(); m_payloads.Release(); } void SetOfSlices::AddSet(const SetOfSlices *set) { size_t count = set->GetSliceCount(); for (size_t sliceId = 0; sliceId < count; sliceId++) { AddSlice(set->GetSlice(sliceId)); } } void SetOfSlices::CleanUseless() { size_t count = m_pSliceQueue.size(); for (size_t sliceId = 0; sliceId < count; sliceId++) { H264Slice * curSlice = m_pSliceQueue[sliceId]; if (curSlice->m_bDecoded) { m_pSliceQueue.erase(m_pSliceQueue.begin() + sliceId); // remove count = m_pSliceQueue.size(); --sliceId; curSlice->Release(); curSlice->DecrementReference(); } } } void SetOfSlices::SortSlices() { static int32_t MAX_MB_NUMBER = 0x7fffffff; if (!m_pSliceQueue.empty() && m_pSliceQueue[0]->IsSliceGroups()) return; size_t count = m_pSliceQueue.size(); for (size_t sliceId = 0; sliceId < count; sliceId++) { H264Slice * curSlice = m_pSliceQueue[sliceId]; int32_t minFirst = MAX_MB_NUMBER; size_t minSlice = 0; for (size_t j = sliceId; j < count; j++) { H264Slice * slice = m_pSliceQueue[j]; if (slice->GetStreamFirstMB() < curSlice->GetStreamFirstMB() && minFirst > slice->GetStreamFirstMB() && curSlice->GetSliceHeader()->nal_ext.svc.dependency_id == slice->GetSliceHeader()->nal_ext.svc.dependency_id && curSlice->GetSliceHeader()->nal_ext.svc.quality_id == slice->GetSliceHeader()->nal_ext.svc.quality_id) { minFirst = slice->GetStreamFirstMB(); minSlice = j; } } if (minFirst != MAX_MB_NUMBER) { H264Slice * temp = m_pSliceQueue[sliceId]; m_pSliceQueue[sliceId] = m_pSliceQueue[minSlice]; m_pSliceQueue[minSlice] = temp; } } for (size_t sliceId = 0; sliceId < count - 1; sliceId++) { H264Slice * slice = m_pSliceQueue[sliceId]; H264Slice * nextSlice = m_pSliceQueue[sliceId + 1]; if (nextSlice->IsSliceGroups() || slice->IsSliceGroups()) continue; if (nextSlice->GetSliceHeader()->nal_ext.svc.quality_id == slice->GetSliceHeader()->nal_ext.svc.quality_id) slice->SetMaxMB(nextSlice->GetStreamFirstMB()); if (slice->GetStreamFirstMB() == slice->GetMaxMB()) { count--; for (size_t i = sliceId; i < count; i++) { m_pSliceQueue[i] = m_pSliceQueue[i + 1]; } m_pSliceQueue.resize(count); slice->DecrementReference(); sliceId = uint32_t(-1); continue; } } } /****************************************************************************************************/ // AccessUnit class routine /****************************************************************************************************/ AccessUnit::AccessUnit() : m_isInitialized(false) , m_isFullAU(false) , m_auCounter(0) { } AccessUnit::~AccessUnit() { } uint32_t AccessUnit::GetAUIndentifier() const { return m_auCounter; } size_t AccessUnit::GetLayersCount() const { return m_layers.size(); } void AccessUnit::CleanUseless() { size_t count = m_layers.size(); for (size_t pos = 0; pos < count; pos++) { SetOfSlices * set = &m_layers[pos]; set->CleanUseless(); if (!set->GetSliceCount()) { m_layers.erase(m_layers.begin() + pos); count = m_layers.size(); pos--; } } } int32_t AccessUnit::FindLayerByDependency(int32_t dependency) { size_t count = m_layers.size(); for (size_t i = 0; i < count; i++) { SetOfSlices * set = &m_layers[i]; if (set->GetSlice(0) && set->GetSlice(0)->GetSliceHeader()->nal_ext.svc.dependency_id == dependency) return (int32_t)i; } return -1; } SetOfSlices * AccessUnit::GetLastLayer() { if (m_layers.empty()) return nullptr; return &m_layers.back(); } SetOfSlices * AccessUnit::GetLayer(size_t pos) { if (pos >= m_layers.size()) return nullptr; return &m_layers[pos]; } void AccessUnit::CombineSets() { if (m_layers.empty()) return; SetOfSlices * setOfSlices = &m_layers[0]; size_t count = m_layers.size(); for (size_t i = 1; i < count; i++) { SetOfSlices * set = &m_layers[i]; setOfSlices->AddSet(set); set->Reset(); } m_layers.resize(1); } bool AccessUnit::IsFullAU() const { return m_isFullAU; } void AccessUnit::CompleteLastLayer() { if (!m_layers.empty()) m_layers.back().m_isFull = true; } bool AccessUnit::AddSlice(H264Slice * slice) { if (!slice) { if (!m_layers.empty()) { m_isFullAU = true; } return false; } SetOfSlices * setOfSlices = GetLayerBySlice(slice); if (!setOfSlices) { if (!m_layers.empty()) { SetOfSlices * lastSetOfSlices = GetLastLayer(); if (lastSetOfSlices->GetSlice(0)->GetSliceHeader()->nal_ext.svc.dependency_id > slice->GetSliceHeader()->nal_ext.svc.dependency_id) { m_isFullAU = true; return false; } } setOfSlices = AddLayer(slice); setOfSlices->m_payloads.MovePayloadsFrom(m_payloads); } H264Slice * lastSlice = setOfSlices->GetSlice(setOfSlices->GetSliceCount() - 1); if (!IsPictureTheSame(lastSlice, slice) || setOfSlices->m_isFull) { m_isFullAU = true; return false; } m_payloads.Release(); setOfSlices->AddSlice(slice); return true; } void AccessUnit::Release() { for (auto & set: m_layers) { set.Release(); } Reset(); m_payloads.Release(); } void AccessUnit::Reset() { for (auto & set: m_layers) { set.Reset(); } m_layers.clear(); m_auCounter++; m_isFullAU = false; m_isInitialized = false; } void AccessUnit::SortforASO() { for (auto & set: m_layers) { set.SortSlices(); } } SetOfSlices * AccessUnit::AddLayer(H264Slice * ) { SetOfSlices setofSlices; m_layers.push_back(setofSlices); return &m_layers.back(); } bool AccessUnit::IsItSliceOfThisAU(H264Slice * slice) { SetOfSlices * setOfSlices = GetLayerBySlice(slice); if (!setOfSlices) return false; H264Slice * lastSlice = setOfSlices->GetSlice(0); return IsPictureTheSame(lastSlice, slice); } SetOfSlices * AccessUnit::GetLayerBySlice(H264Slice * slice) { if (!slice) return nullptr; size_t count = m_layers.size(); for (size_t i = 0; i < count; i++) { H264Slice * temp = m_layers[i].GetSlice(0); if (!temp) continue; if (temp->GetSliceHeader()->nal_ext.mvc.view_id == slice->GetSliceHeader()->nal_ext.mvc.view_id && temp->GetSliceHeader()->nal_ext.svc.dependency_id == slice->GetSliceHeader()->nal_ext.svc.dependency_id) return &m_layers[i]; } return nullptr; } AU_Splitter::AU_Splitter(H264_Heap_Objects *objectHeap) : m_Headers(objectHeap) , m_objHeap(objectHeap) { } AU_Splitter::~AU_Splitter() { Close(); } void AU_Splitter::Init() { Close(); m_pNALSplitter.reset(new NALUnitSplitter()); m_pNALSplitter->Init(); } void AU_Splitter::Close() { m_pNALSplitter.reset(0); } void AU_Splitter::Reset() { if (m_pNALSplitter.get()) m_pNALSplitter->Reset(); m_Headers.Reset(); } NalUnit * AU_Splitter::GetNalUnit(MediaData * src) { return m_pNALSplitter->GetNalUnits(src); } NALUnitSplitter * AU_Splitter::GetNalUnitSplitter() { return m_pNALSplitter.get(); } } // namespace UMC #endif // MFX_ENABLE_H264_VIDEO_DECODE
// Copyright (c) 2017-2018 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "umc_defs.h" #if defined (MFX_ENABLE_H264_VIDEO_DECODE) #include <memory> #include "umc_h264_au_splitter.h" #include "umc_h264_nal_spl.h" namespace UMC { /****************************************************************************************************/ // SeiPayloadArray class routine /****************************************************************************************************/ SeiPayloadArray::SeiPayloadArray() { m_payloads.reserve(3); } SeiPayloadArray::SeiPayloadArray(const SeiPayloadArray & payloads) :m_payloads() { size_t count = payloads.GetPayloadCount(); for (size_t i = 0; i < count; i++) { AddPayload(payloads.GetPayload(i)); } } SeiPayloadArray::~SeiPayloadArray() { Release(); } size_t SeiPayloadArray::GetPayloadCount() const { return m_payloads.size(); } UMC_H264_DECODER::H264SEIPayLoad* SeiPayloadArray::GetPayload(size_t pos) const { if (pos >= m_payloads.size()) return 0; return m_payloads[pos]; } UMC_H264_DECODER::H264SEIPayLoad* SeiPayloadArray::FindPayload(SEI_TYPE type) const { int32_t pos = FindPayloadPos(type); return (pos < 0) ? 0 : GetPayload(pos); } int32_t SeiPayloadArray::FindPayloadPos(SEI_TYPE type) const { size_t count = m_payloads.size(); for (size_t i = 0; i < count; i++) { UMC_H264_DECODER::H264SEIPayLoad* payload = m_payloads[i]; if (payload->payLoadType == type) return (int32_t)i; } return -1; } void SeiPayloadArray::MovePayloadsFrom(SeiPayloadArray &payloads) { size_t count = payloads.GetPayloadCount(); for (size_t i = 0; i < count; i++) { AddPayload(payloads.GetPayload(i)); } payloads.Release(); } void SeiPayloadArray::Release() { PayloadArray::iterator iter = m_payloads.begin(); PayloadArray::iterator iter_end = m_payloads.end(); for (; iter != iter_end; ++iter) { UMC_H264_DECODER::H264SEIPayLoad* payload = *iter; payload->DecrementReference(); } m_payloads.clear(); } void SeiPayloadArray::AddPayload(UMC_H264_DECODER::H264SEIPayLoad* payload) { if (!payload) return; payload->IncrementReference(); int32_t pos = FindPayloadPos(payload->payLoadType); if (pos >= 0) // always use last payload { m_payloads[pos]->DecrementReference(); m_payloads[pos] = payload; return; } m_payloads.push_back(payload); } /****************************************************************************************************/ // SetOfSlices class routine /****************************************************************************************************/ SetOfSlices::SetOfSlices() : m_frame(0) , m_isCompleted(false) , m_isFull(false) { } SetOfSlices::SetOfSlices(const SetOfSlices& set) : m_frame(set.m_frame) , m_isCompleted(set.m_isCompleted) , m_isFull(set.m_isFull) , m_payloads(set.m_payloads) , m_pSliceQueue(set.m_pSliceQueue) { for (auto pSlice : m_pSliceQueue) { pSlice->IncrementReference(); } } SetOfSlices::~SetOfSlices() { Release(); } SetOfSlices& SetOfSlices::operator=(const SetOfSlices& set) { if (this == &set) { return *this; } *this = set; for (auto pSlice : m_pSliceQueue) { pSlice->IncrementReference(); } return *this; } H264Slice * SetOfSlices::GetSlice(size_t pos) const { if (pos >= m_pSliceQueue.size()) return nullptr; return m_pSliceQueue[pos]; } size_t SetOfSlices::GetSliceCount() const { return m_pSliceQueue.size(); } void SetOfSlices::AddSlice(H264Slice * slice) { m_pSliceQueue.push_back(slice); } void SetOfSlices::Release() { size_t count = m_pSliceQueue.size(); for (size_t sliceId = 0; sliceId < count; sliceId++) { H264Slice * slice = m_pSliceQueue[sliceId]; slice->DecrementReference(); } Reset(); } void SetOfSlices::Reset() { m_frame = 0; m_isCompleted = false; m_isFull = false; m_pSliceQueue.clear(); m_payloads.Release(); } void SetOfSlices::AddSet(const SetOfSlices *set) { size_t count = set->GetSliceCount(); for (size_t sliceId = 0; sliceId < count; sliceId++) { AddSlice(set->GetSlice(sliceId)); } } void SetOfSlices::CleanUseless() { size_t count = m_pSliceQueue.size(); for (size_t sliceId = 0; sliceId < count; sliceId++) { H264Slice * curSlice = m_pSliceQueue[sliceId]; if (curSlice->m_bDecoded) { m_pSliceQueue.erase(m_pSliceQueue.begin() + sliceId); // remove count = m_pSliceQueue.size(); --sliceId; curSlice->Release(); curSlice->DecrementReference(); } } } void SetOfSlices::SortSlices() { static int32_t MAX_MB_NUMBER = 0x7fffffff; if (!m_pSliceQueue.empty() && m_pSliceQueue[0]->IsSliceGroups()) return; size_t count = m_pSliceQueue.size(); for (size_t sliceId = 0; sliceId < count; sliceId++) { H264Slice * curSlice = m_pSliceQueue[sliceId]; int32_t minFirst = MAX_MB_NUMBER; size_t minSlice = 0; for (size_t j = sliceId; j < count; j++) { H264Slice * slice = m_pSliceQueue[j]; if (slice->GetStreamFirstMB() < curSlice->GetStreamFirstMB() && minFirst > slice->GetStreamFirstMB() && curSlice->GetSliceHeader()->nal_ext.svc.dependency_id == slice->GetSliceHeader()->nal_ext.svc.dependency_id && curSlice->GetSliceHeader()->nal_ext.svc.quality_id == slice->GetSliceHeader()->nal_ext.svc.quality_id) { minFirst = slice->GetStreamFirstMB(); minSlice = j; } } if (minFirst != MAX_MB_NUMBER) { H264Slice * temp = m_pSliceQueue[sliceId]; m_pSliceQueue[sliceId] = m_pSliceQueue[minSlice]; m_pSliceQueue[minSlice] = temp; } } for (size_t sliceId = 0; sliceId < count - 1; sliceId++) { H264Slice * slice = m_pSliceQueue[sliceId]; H264Slice * nextSlice = m_pSliceQueue[sliceId + 1]; if (nextSlice->IsSliceGroups() || slice->IsSliceGroups()) continue; if (nextSlice->GetSliceHeader()->nal_ext.svc.quality_id == slice->GetSliceHeader()->nal_ext.svc.quality_id) slice->SetMaxMB(nextSlice->GetStreamFirstMB()); if (slice->GetStreamFirstMB() == slice->GetMaxMB()) { count--; for (size_t i = sliceId; i < count; i++) { m_pSliceQueue[i] = m_pSliceQueue[i + 1]; } m_pSliceQueue.resize(count); slice->DecrementReference(); sliceId = uint32_t(-1); continue; } } } /****************************************************************************************************/ // AccessUnit class routine /****************************************************************************************************/ AccessUnit::AccessUnit() : m_isInitialized(false) , m_isFullAU(false) , m_auCounter(0) { } AccessUnit::~AccessUnit() { } uint32_t AccessUnit::GetAUIndentifier() const { return m_auCounter; } size_t AccessUnit::GetLayersCount() const { return m_layers.size(); } void AccessUnit::CleanUseless() { size_t count = m_layers.size(); for (size_t pos = 0; pos < count; pos++) { SetOfSlices * set = &m_layers[pos]; set->CleanUseless(); if (!set->GetSliceCount()) { m_layers.erase(m_layers.begin() + pos); count = m_layers.size(); pos--; } } } int32_t AccessUnit::FindLayerByDependency(int32_t dependency) { size_t count = m_layers.size(); for (size_t i = 0; i < count; i++) { SetOfSlices * set = &m_layers[i]; if (set->GetSlice(0) && set->GetSlice(0)->GetSliceHeader()->nal_ext.svc.dependency_id == dependency) return (int32_t)i; } return -1; } SetOfSlices * AccessUnit::GetLastLayer() { if (m_layers.empty()) return nullptr; return &m_layers.back(); } SetOfSlices * AccessUnit::GetLayer(size_t pos) { if (pos >= m_layers.size()) return nullptr; return &m_layers[pos]; } void AccessUnit::CombineSets() { if (m_layers.empty()) return; SetOfSlices * setOfSlices = &m_layers[0]; size_t count = m_layers.size(); for (size_t i = 1; i < count; i++) { SetOfSlices * set = &m_layers[i]; setOfSlices->AddSet(set); set->Reset(); } m_layers.resize(1); } bool AccessUnit::IsFullAU() const { return m_isFullAU; } void AccessUnit::CompleteLastLayer() { if (!m_layers.empty()) m_layers.back().m_isFull = true; } bool AccessUnit::AddSlice(H264Slice * slice) { if (!slice) { if (!m_layers.empty()) { m_isFullAU = true; } return false; } SetOfSlices * setOfSlices = GetLayerBySlice(slice); if (!setOfSlices) { if (!m_layers.empty()) { SetOfSlices * lastSetOfSlices = GetLastLayer(); if (lastSetOfSlices->GetSlice(0)->GetSliceHeader()->nal_ext.svc.dependency_id > slice->GetSliceHeader()->nal_ext.svc.dependency_id) { m_isFullAU = true; return false; } } setOfSlices = AddLayer(slice); setOfSlices->m_payloads.MovePayloadsFrom(m_payloads); } H264Slice * lastSlice = setOfSlices->GetSlice(setOfSlices->GetSliceCount() - 1); if (!IsPictureTheSame(lastSlice, slice) || setOfSlices->m_isFull) { m_isFullAU = true; return false; } m_payloads.Release(); setOfSlices->AddSlice(slice); return true; } void AccessUnit::Release() { for (auto & set: m_layers) { set.Release(); } Reset(); m_payloads.Release(); } void AccessUnit::Reset() { for (auto & set: m_layers) { set.Reset(); } m_layers.clear(); m_auCounter++; m_isFullAU = false; m_isInitialized = false; } void AccessUnit::SortforASO() { for (auto & set: m_layers) { set.SortSlices(); } } SetOfSlices * AccessUnit::AddLayer(H264Slice * ) { SetOfSlices setofSlices; m_layers.push_back(setofSlices); return &m_layers.back(); } bool AccessUnit::IsItSliceOfThisAU(H264Slice * slice) { SetOfSlices * setOfSlices = GetLayerBySlice(slice); if (!setOfSlices) return false; H264Slice * lastSlice = setOfSlices->GetSlice(0); return IsPictureTheSame(lastSlice, slice); } SetOfSlices * AccessUnit::GetLayerBySlice(H264Slice * slice) { if (!slice) return nullptr; size_t count = m_layers.size(); for (size_t i = 0; i < count; i++) { H264Slice * temp = m_layers[i].GetSlice(0); if (!temp) continue; if (temp->GetSliceHeader()->nal_ext.mvc.view_id == slice->GetSliceHeader()->nal_ext.mvc.view_id && temp->GetSliceHeader()->nal_ext.svc.dependency_id == slice->GetSliceHeader()->nal_ext.svc.dependency_id) return &m_layers[i]; } return nullptr; } AU_Splitter::AU_Splitter(H264_Heap_Objects *objectHeap) : m_Headers(objectHeap) , m_objHeap(objectHeap) { } AU_Splitter::~AU_Splitter() { Close(); } void AU_Splitter::Init() { Close(); m_pNALSplitter.reset(new NALUnitSplitter()); m_pNALSplitter->Init(); } void AU_Splitter::Close() { m_pNALSplitter.reset(0); } void AU_Splitter::Reset() { if (m_pNALSplitter.get()) m_pNALSplitter->Reset(); m_Headers.Reset(); } NalUnit * AU_Splitter::GetNalUnit(MediaData * src) { return m_pNALSplitter->GetNalUnits(src); } NALUnitSplitter * AU_Splitter::GetNalUnitSplitter() { return m_pNALSplitter.get(); } } // namespace UMC #endif // MFX_ENABLE_H264_VIDEO_DECODE
Add m_payloads initializaion on constructor
Add m_payloads initializaion on constructor
C++
mit
Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK,Intel-Media-SDK/MediaSDK
5bddb82c828f709f23c56eb01df6eb578dac9a51
include/distortos/estd/ContiguousRange.hpp
include/distortos/estd/ContiguousRange.hpp
/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-08-23 */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <iterator> #include <cstddef> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \param T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \param N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr ContiguousRange(T (&array)[N]) noexcept : ContiguousRange{array, array + N} { } /// \return iterator to first element in the range constexpr iterator begin() const noexcept { return begin_; } /// \return iterator to "one past the last" element in the range constexpr iterator end() const noexcept { return end_; } /// \return number of elements in the range constexpr size_type size() const noexcept { return end_ - begin_; } private: /// iterator to first element in the range const iterator begin_; /// iterator to "one past the last" element in the range const iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_
/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-11-03 */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <iterator> #include <cstddef> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \param T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \param N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (&array)[N]) noexcept : ContiguousRange{array, array + N} { } /// \return iterator to first element in the range constexpr iterator begin() const noexcept { return begin_; } /// \return iterator to "one past the last" element in the range constexpr iterator end() const noexcept { return end_; } /// \return number of elements in the range constexpr size_type size() const noexcept { return end_ - begin_; } private: /// iterator to first element in the range const iterator begin_; /// iterator to "one past the last" element in the range const iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_
make all default and single-argument constructors "explicit"
ContiguousRange: make all default and single-argument constructors "explicit"
C++
mpl-2.0
CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos
20895ffc3d7049cb80e188d78402d13ca5591996
tensorflow/core/framework/op.cc
tensorflow/core/framework/op.cc
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/op.h" #include <algorithm> #include <memory> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/platform/host_info.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { // OpRegistry ----------------------------------------------------------------- OpRegistryInterface::~OpRegistryInterface() {} Status OpRegistryInterface::LookUpOpDef(const string& op_type_name, const OpDef** op_def) const { *op_def = nullptr; const OpRegistrationData* op_reg_data = nullptr; TF_RETURN_IF_ERROR(LookUp(op_type_name, &op_reg_data)); *op_def = &op_reg_data->op_def; return Status::OK(); } OpRegistry::OpRegistry() : initialized_(false) {} OpRegistry::~OpRegistry() { for (const auto& e : registry_) delete e.second; } void OpRegistry::Register(const OpRegistrationDataFactory& op_data_factory) { mutex_lock lock(mu_); if (initialized_) { TF_QCHECK_OK(RegisterAlreadyLocked(op_data_factory)); } else { deferred_.push_back(op_data_factory); } } Status OpRegistry::LookUp(const string& op_type_name, const OpRegistrationData** op_reg_data) const { *op_reg_data = nullptr; const OpRegistrationData* res = nullptr; bool first_call = false; { // Scope for lock. mutex_lock lock(mu_); first_call = MustCallDeferred(); res = gtl::FindWithDefault(registry_, op_type_name, nullptr); // Note: Can't hold mu_ while calling Export() below. } if (first_call) { TF_QCHECK_OK(ValidateKernelRegistrations(*this)); } if (res == nullptr) { static bool first_unregistered = true; if (first_unregistered) { OpList op_list; Export(true, &op_list); if (VLOG_IS_ON(3)) { LOG(INFO) << "All registered Ops:"; for (const auto& op : op_list.op()) LOG(INFO) << SummarizeOpDef(op); } first_unregistered = false; } Status status = errors::NotFound("Op type not registered '", op_type_name, "' in binary running on ", port::Hostname(), ". ", "Make sure the Op and Kernel are registered in the " "binary running in this process."); VLOG(1) << status.ToString(); return status; } *op_reg_data = res; return Status::OK(); } void OpRegistry::GetRegisteredOps(std::vector<OpDef>* op_defs) { mutex_lock lock(mu_); MustCallDeferred(); for (const auto& p : registry_) { op_defs->push_back(p.second->op_def); } } Status OpRegistry::SetWatcher(const Watcher& watcher) { mutex_lock lock(mu_); if (watcher_ && watcher) { return errors::AlreadyExists( "Cannot over-write a valid watcher with another."); } watcher_ = watcher; return Status::OK(); } void OpRegistry::Export(bool include_internal, OpList* ops) const { mutex_lock lock(mu_); MustCallDeferred(); std::vector<std::pair<string, const OpRegistrationData*>> sorted( registry_.begin(), registry_.end()); std::sort(sorted.begin(), sorted.end()); auto out = ops->mutable_op(); out->Clear(); out->Reserve(sorted.size()); for (const auto& item : sorted) { if (include_internal || !StringPiece(item.first).starts_with("_")) { *out->Add() = item.second->op_def; } } } void OpRegistry::DeferRegistrations() { mutex_lock lock(mu_); initialized_ = false; } void OpRegistry::ClearDeferredRegistrations() { mutex_lock lock(mu_); deferred_.clear(); } Status OpRegistry::ProcessRegistrations() const { mutex_lock lock(mu_); return CallDeferred(); } string OpRegistry::DebugString(bool include_internal) const { OpList op_list; Export(include_internal, &op_list); string ret; for (const auto& op : op_list.op()) { strings::StrAppend(&ret, SummarizeOpDef(op), "\n"); } return ret; } bool OpRegistry::MustCallDeferred() const { if (initialized_) return false; initialized_ = true; for (size_t i = 0; i < deferred_.size(); ++i) { TF_QCHECK_OK(RegisterAlreadyLocked(deferred_[i])); } deferred_.clear(); return true; } Status OpRegistry::CallDeferred() const { if (initialized_) return Status::OK(); initialized_ = true; for (size_t i = 0; i < deferred_.size(); ++i) { Status s = RegisterAlreadyLocked(deferred_[i]); if (!s.ok()) { return s; } } deferred_.clear(); return Status::OK(); } Status OpRegistry::RegisterAlreadyLocked( const OpRegistrationDataFactory& op_data_factory) const { std::unique_ptr<OpRegistrationData> op_reg_data(new OpRegistrationData); Status s = op_data_factory(op_reg_data.get()); if (s.ok()) { s = ValidateOpDef(op_reg_data->op_def); if (s.ok() && !gtl::InsertIfNotPresent(&registry_, op_reg_data->op_def.name(), op_reg_data.get())) { s = errors::AlreadyExists("Op with name ", op_reg_data->op_def.name()); } } Status watcher_status = s; if (watcher_) { watcher_status = watcher_(s, op_reg_data->op_def); } if (s.ok()) { op_reg_data.release(); } else { op_reg_data.reset(); } return watcher_status; } // static OpRegistry* OpRegistry::Global() { static OpRegistry* global_op_registry = new OpRegistry; return global_op_registry; } // OpListOpRegistry ----------------------------------------------------------- OpListOpRegistry::OpListOpRegistry(const OpList* op_list) { for (const OpDef& op_def : op_list->op()) { auto* op_reg_data = new OpRegistrationData(); op_reg_data->op_def = op_def; index_[op_def.name()] = op_reg_data; } } OpListOpRegistry::~OpListOpRegistry() { for (const auto& e : index_) delete e.second; } Status OpListOpRegistry::LookUp(const string& op_type_name, const OpRegistrationData** op_reg_data) const { auto iter = index_.find(op_type_name); if (iter == index_.end()) { *op_reg_data = nullptr; return errors::NotFound("Op type not registered '", op_type_name, "' in binary running on ", port::Hostname(), ". ", "Make sure the Op and Kernel are registered in the " "binary running in this process."); } *op_reg_data = iter->second; return Status::OK(); } // Other registration --------------------------------------------------------- namespace register_op { OpDefBuilderReceiver::OpDefBuilderReceiver( const OpDefBuilderWrapper<true>& wrapper) { OpRegistry::Global()->Register( [wrapper](OpRegistrationData* op_reg_data) -> Status { return wrapper.builder().Finalize(op_reg_data); }); } } // namespace register_op } // namespace tensorflow
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/op.h" #include <algorithm> #include <memory> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/platform/host_info.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { // OpRegistry ----------------------------------------------------------------- OpRegistryInterface::~OpRegistryInterface() {} Status OpRegistryInterface::LookUpOpDef(const string& op_type_name, const OpDef** op_def) const { *op_def = nullptr; const OpRegistrationData* op_reg_data = nullptr; TF_RETURN_IF_ERROR(LookUp(op_type_name, &op_reg_data)); *op_def = &op_reg_data->op_def; return Status::OK(); } OpRegistry::OpRegistry() : initialized_(false) {} OpRegistry::~OpRegistry() { for (const auto& e : registry_) delete e.second; } void OpRegistry::Register(const OpRegistrationDataFactory& op_data_factory) { mutex_lock lock(mu_); if (initialized_) { TF_QCHECK_OK(RegisterAlreadyLocked(op_data_factory)); } else { deferred_.push_back(op_data_factory); } } Status OpRegistry::LookUp(const string& op_type_name, const OpRegistrationData** op_reg_data) const { *op_reg_data = nullptr; const OpRegistrationData* res = nullptr; bool first_call = false; bool first_unregistered = false; { // Scope for lock. mutex_lock lock(mu_); first_call = MustCallDeferred(); res = gtl::FindWithDefault(registry_, op_type_name, nullptr); static bool unregistered_before = false; first_unregistered = !unregistered_before && (res == nullptr); if (first_unregistered) { unregistered_before = true; } // Note: Can't hold mu_ while calling Export() below. } if (first_call) { TF_QCHECK_OK(ValidateKernelRegistrations(*this)); } if (res == nullptr) { if (first_unregistered) { OpList op_list; Export(true, &op_list); if (VLOG_IS_ON(3)) { LOG(INFO) << "All registered Ops:"; for (const auto& op : op_list.op()) { LOG(INFO) << SummarizeOpDef(op); } } } Status status = errors::NotFound("Op type not registered '", op_type_name, "' in binary running on ", port::Hostname(), ". ", "Make sure the Op and Kernel are registered in the " "binary running in this process."); VLOG(1) << status.ToString(); return status; } *op_reg_data = res; return Status::OK(); } void OpRegistry::GetRegisteredOps(std::vector<OpDef>* op_defs) { mutex_lock lock(mu_); MustCallDeferred(); for (const auto& p : registry_) { op_defs->push_back(p.second->op_def); } } Status OpRegistry::SetWatcher(const Watcher& watcher) { mutex_lock lock(mu_); if (watcher_ && watcher) { return errors::AlreadyExists( "Cannot over-write a valid watcher with another."); } watcher_ = watcher; return Status::OK(); } void OpRegistry::Export(bool include_internal, OpList* ops) const { mutex_lock lock(mu_); MustCallDeferred(); std::vector<std::pair<string, const OpRegistrationData*>> sorted( registry_.begin(), registry_.end()); std::sort(sorted.begin(), sorted.end()); auto out = ops->mutable_op(); out->Clear(); out->Reserve(sorted.size()); for (const auto& item : sorted) { if (include_internal || !StringPiece(item.first).starts_with("_")) { *out->Add() = item.second->op_def; } } } void OpRegistry::DeferRegistrations() { mutex_lock lock(mu_); initialized_ = false; } void OpRegistry::ClearDeferredRegistrations() { mutex_lock lock(mu_); deferred_.clear(); } Status OpRegistry::ProcessRegistrations() const { mutex_lock lock(mu_); return CallDeferred(); } string OpRegistry::DebugString(bool include_internal) const { OpList op_list; Export(include_internal, &op_list); string ret; for (const auto& op : op_list.op()) { strings::StrAppend(&ret, SummarizeOpDef(op), "\n"); } return ret; } bool OpRegistry::MustCallDeferred() const { if (initialized_) return false; initialized_ = true; for (size_t i = 0; i < deferred_.size(); ++i) { TF_QCHECK_OK(RegisterAlreadyLocked(deferred_[i])); } deferred_.clear(); return true; } Status OpRegistry::CallDeferred() const { if (initialized_) return Status::OK(); initialized_ = true; for (size_t i = 0; i < deferred_.size(); ++i) { Status s = RegisterAlreadyLocked(deferred_[i]); if (!s.ok()) { return s; } } deferred_.clear(); return Status::OK(); } Status OpRegistry::RegisterAlreadyLocked( const OpRegistrationDataFactory& op_data_factory) const { std::unique_ptr<OpRegistrationData> op_reg_data(new OpRegistrationData); Status s = op_data_factory(op_reg_data.get()); if (s.ok()) { s = ValidateOpDef(op_reg_data->op_def); if (s.ok() && !gtl::InsertIfNotPresent(&registry_, op_reg_data->op_def.name(), op_reg_data.get())) { s = errors::AlreadyExists("Op with name ", op_reg_data->op_def.name()); } } Status watcher_status = s; if (watcher_) { watcher_status = watcher_(s, op_reg_data->op_def); } if (s.ok()) { op_reg_data.release(); } else { op_reg_data.reset(); } return watcher_status; } // static OpRegistry* OpRegistry::Global() { static OpRegistry* global_op_registry = new OpRegistry; return global_op_registry; } // OpListOpRegistry ----------------------------------------------------------- OpListOpRegistry::OpListOpRegistry(const OpList* op_list) { for (const OpDef& op_def : op_list->op()) { auto* op_reg_data = new OpRegistrationData(); op_reg_data->op_def = op_def; index_[op_def.name()] = op_reg_data; } } OpListOpRegistry::~OpListOpRegistry() { for (const auto& e : index_) delete e.second; } Status OpListOpRegistry::LookUp(const string& op_type_name, const OpRegistrationData** op_reg_data) const { auto iter = index_.find(op_type_name); if (iter == index_.end()) { *op_reg_data = nullptr; return errors::NotFound("Op type not registered '", op_type_name, "' in binary running on ", port::Hostname(), ". ", "Make sure the Op and Kernel are registered in the " "binary running in this process."); } *op_reg_data = iter->second; return Status::OK(); } // Other registration --------------------------------------------------------- namespace register_op { OpDefBuilderReceiver::OpDefBuilderReceiver( const OpDefBuilderWrapper<true>& wrapper) { OpRegistry::Global()->Register( [wrapper](OpRegistrationData* op_reg_data) -> Status { return wrapper.builder().Finalize(op_reg_data); }); } } // namespace register_op } // namespace tensorflow
Modify static bool variable in OpRegistry::Lookup() while mutex is locked.
Modify static bool variable in OpRegistry::Lookup() while mutex is locked. PiperOrigin-RevId: 177078725
C++
apache-2.0
davidzchen/tensorflow,ageron/tensorflow,allenlavoie/tensorflow,arborh/tensorflow,kobejean/tensorflow,hehongliang/tensorflow,ppwwyyxx/tensorflow,eaplatanios/tensorflow,freedomtan/tensorflow,chemelnucfin/tensorflow,freedomtan/tensorflow,ppwwyyxx/tensorflow,brchiu/tensorflow,aselle/tensorflow,ageron/tensorflow,apark263/tensorflow,zasdfgbnm/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jhseu/tensorflow,AnishShah/tensorflow,eaplatanios/tensorflow,annarev/tensorflow,jbedorf/tensorflow,kobejean/tensorflow,caisq/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gojira/tensorflow,nolanliou/tensorflow,manipopopo/tensorflow,xodus7/tensorflow,alshedivat/tensorflow,adit-chandra/tensorflow,jbedorf/tensorflow,hfp/tensorflow-xsmm,yongtang/tensorflow,caisq/tensorflow,yanchen036/tensorflow,Xeralux/tensorflow,jart/tensorflow,alshedivat/tensorflow,dongjoon-hyun/tensorflow,Mistobaan/tensorflow,asimshankar/tensorflow,paolodedios/tensorflow,ppwwyyxx/tensorflow,petewarden/tensorflow,ageron/tensorflow,dendisuhubdy/tensorflow,karllessard/tensorflow,Xeralux/tensorflow,eaplatanios/tensorflow,renyi533/tensorflow,Mistobaan/tensorflow,Intel-Corporation/tensorflow,jalexvig/tensorflow,paolodedios/tensorflow,xzturn/tensorflow,AnishShah/tensorflow,dendisuhubdy/tensorflow,gojira/tensorflow,Intel-Corporation/tensorflow,arborh/tensorflow,lukeiwanski/tensorflow,dendisuhubdy/tensorflow,girving/tensorflow,karllessard/tensorflow,snnn/tensorflow,girving/tensorflow,manipopopo/tensorflow,aselle/tensorflow,ghchinoy/tensorflow,kobejean/tensorflow,snnn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jart/tensorflow,brchiu/tensorflow,jwlawson/tensorflow,caisq/tensorflow,eadgarchen/tensorflow,rabipanda/tensorflow,Xeralux/tensorflow,hfp/tensorflow-xsmm,jhseu/tensorflow,jart/tensorflow,karllessard/tensorflow,gunan/tensorflow,brchiu/tensorflow,Mistobaan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jbedorf/tensorflow,davidzchen/tensorflow,drpngx/tensorflow,aam-at/tensorflow,kobejean/tensorflow,renyi533/tensorflow,jalexvig/tensorflow,zasdfgbnm/tensorflow,manipopopo/tensorflow,codrut3/tensorflow,freedomtan/tensorflow,Bismarrck/tensorflow,annarev/tensorflow,DavidNorman/tensorflow,DavidNorman/tensorflow,adit-chandra/tensorflow,alsrgv/tensorflow,manipopopo/tensorflow,Kongsea/tensorflow,girving/tensorflow,ravindrapanda/tensorflow,adit-chandra/tensorflow,renyi533/tensorflow,xodus7/tensorflow,jalexvig/tensorflow,paolodedios/tensorflow,Bismarrck/tensorflow,aam-at/tensorflow,ZhangXinNan/tensorflow,yongtang/tensorflow,lukeiwanski/tensorflow,Xeralux/tensorflow,drpngx/tensorflow,Xeralux/tensorflow,cxxgtxy/tensorflow,arborh/tensorflow,kevin-coder/tensorflow-fork,paolodedios/tensorflow,JingJunYin/tensorflow,apark263/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,theflofly/tensorflow,drpngx/tensorflow,ravindrapanda/tensorflow,meteorcloudy/tensorflow,petewarden/tensorflow,petewarden/tensorflow,gojira/tensorflow,rabipanda/tensorflow,gautam1858/tensorflow,arborh/tensorflow,Bismarrck/tensorflow,rabipanda/tensorflow,codrut3/tensorflow,allenlavoie/tensorflow,drpngx/tensorflow,ZhangXinNan/tensorflow,lakshayg/tensorflow,zasdfgbnm/tensorflow,yongtang/tensorflow,drpngx/tensorflow,AnishShah/tensorflow,codrut3/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,xzturn/tensorflow,ravindrapanda/tensorflow,jbedorf/tensorflow,aam-at/tensorflow,aldian/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,Bismarrck/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,renyi533/tensorflow,aam-at/tensorflow,benoitsteiner/tensorflow-xsmm,renyi533/tensorflow,dendisuhubdy/tensorflow,jbedorf/tensorflow,dancingdan/tensorflow,kevin-coder/tensorflow-fork,karllessard/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,zasdfgbnm/tensorflow,benoitsteiner/tensorflow-xsmm,gunan/tensorflow,eaplatanios/tensorflow,zasdfgbnm/tensorflow,xzturn/tensorflow,JingJunYin/tensorflow,av8ramit/tensorflow,caisq/tensorflow,snnn/tensorflow,lukeiwanski/tensorflow,AnishShah/tensorflow,alshedivat/tensorflow,ZhangXinNan/tensorflow,jwlawson/tensorflow,JingJunYin/tensorflow,tensorflow/tensorflow-pywrap_saved_model,alshedivat/tensorflow,paolodedios/tensorflow,jbedorf/tensorflow,rabipanda/tensorflow,ghchinoy/tensorflow,ghchinoy/tensorflow,jart/tensorflow,codrut3/tensorflow,theflofly/tensorflow,allenlavoie/tensorflow,renyi533/tensorflow,petewarden/tensorflow,nolanliou/tensorflow,snnn/tensorflow,JingJunYin/tensorflow,karllessard/tensorflow,rabipanda/tensorflow,jendap/tensorflow,xodus7/tensorflow,hfp/tensorflow-xsmm,cxxgtxy/tensorflow,annarev/tensorflow,brchiu/tensorflow,xodus7/tensorflow,aldian/tensorflow,eaplatanios/tensorflow,paolodedios/tensorflow,xzturn/tensorflow,jhseu/tensorflow,sarvex/tensorflow,sarvex/tensorflow,dongjoon-hyun/tensorflow,chemelnucfin/tensorflow,gunan/tensorflow,dongjoon-hyun/tensorflow,dancingdan/tensorflow,hehongliang/tensorflow,gautam1858/tensorflow,DavidNorman/tensorflow,theflofly/tensorflow,Bismarrck/tensorflow,jart/tensorflow,alshedivat/tensorflow,av8ramit/tensorflow,drpngx/tensorflow,DavidNorman/tensorflow,hfp/tensorflow-xsmm,freedomtan/tensorflow,chemelnucfin/tensorflow,alshedivat/tensorflow,dendisuhubdy/tensorflow,apark263/tensorflow,yongtang/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,dancingdan/tensorflow,snnn/tensorflow,meteorcloudy/tensorflow,asimshankar/tensorflow,aldian/tensorflow,jbedorf/tensorflow,ageron/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ageron/tensorflow,benoitsteiner/tensorflow-xsmm,gunan/tensorflow,eaplatanios/tensorflow,benoitsteiner/tensorflow-xsmm,hehongliang/tensorflow,hehongliang/tensorflow,codrut3/tensorflow,girving/tensorflow,jendap/tensorflow,dancingdan/tensorflow,aldian/tensorflow,apark263/tensorflow,ravindrapanda/tensorflow,annarev/tensorflow,gunan/tensorflow,lukeiwanski/tensorflow,davidzchen/tensorflow,seanli9jan/tensorflow,nburn42/tensorflow,Mistobaan/tensorflow,meteorcloudy/tensorflow,adit-chandra/tensorflow,drpngx/tensorflow,dancingdan/tensorflow,manipopopo/tensorflow,gautam1858/tensorflow,seanli9jan/tensorflow,hsaputra/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,gunan/tensorflow,jbedorf/tensorflow,renyi533/tensorflow,ppwwyyxx/tensorflow,gautam1858/tensorflow,annarev/tensorflow,xodus7/tensorflow,tensorflow/tensorflow-pywrap_saved_model,alshedivat/tensorflow,jalexvig/tensorflow,benoitsteiner/tensorflow-xsmm,yongtang/tensorflow,Intel-Corporation/tensorflow,xzturn/tensorflow,dendisuhubdy/tensorflow,yanchen036/tensorflow,Kongsea/tensorflow,Kongsea/tensorflow,chemelnucfin/tensorflow,ghchinoy/tensorflow,manipopopo/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow,manipopopo/tensorflow,ZhangXinNan/tensorflow,alsrgv/tensorflow,jbedorf/tensorflow,ZhangXinNan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,hsaputra/tensorflow,manipopopo/tensorflow,AnishShah/tensorflow,gautam1858/tensorflow,meteorcloudy/tensorflow,DavidNorman/tensorflow,brchiu/tensorflow,jalexvig/tensorflow,dancingdan/tensorflow,JingJunYin/tensorflow,Xeralux/tensorflow,yongtang/tensorflow,arborh/tensorflow,rabipanda/tensorflow,lukeiwanski/tensorflow,paolodedios/tensorflow,jendap/tensorflow,DavidNorman/tensorflow,dancingdan/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,jhseu/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,kobejean/tensorflow,gautam1858/tensorflow,brchiu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,allenlavoie/tensorflow,jalexvig/tensorflow,Intel-Corporation/tensorflow,allenlavoie/tensorflow,adit-chandra/tensorflow,alsrgv/tensorflow,arborh/tensorflow,brchiu/tensorflow,aam-at/tensorflow,asimshankar/tensorflow,theflofly/tensorflow,ravindrapanda/tensorflow,annarev/tensorflow,girving/tensorflow,hsaputra/tensorflow,codrut3/tensorflow,tensorflow/tensorflow-pywrap_saved_model,zasdfgbnm/tensorflow,xodus7/tensorflow,renyi533/tensorflow,ravindrapanda/tensorflow,jalexvig/tensorflow,ZhangXinNan/tensorflow,petewarden/tensorflow,xodus7/tensorflow,lukeiwanski/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,hfp/tensorflow-xsmm,Xeralux/tensorflow,eadgarchen/tensorflow,ZhangXinNan/tensorflow,alsrgv/tensorflow,dendisuhubdy/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,rabipanda/tensorflow,frreiss/tensorflow-fred,theflofly/tensorflow,ghchinoy/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Kongsea/tensorflow,apark263/tensorflow,meteorcloudy/tensorflow,dancingdan/tensorflow,zasdfgbnm/tensorflow,dongjoon-hyun/tensorflow,renyi533/tensorflow,ZhangXinNan/tensorflow,petewarden/tensorflow,asimshankar/tensorflow,caisq/tensorflow,jart/tensorflow,paolodedios/tensorflow,ageron/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yanchen036/tensorflow,hfp/tensorflow-xsmm,AnishShah/tensorflow,snnn/tensorflow,Intel-Corporation/tensorflow,theflofly/tensorflow,lukeiwanski/tensorflow,apark263/tensorflow,nburn42/tensorflow,adit-chandra/tensorflow,hfp/tensorflow-xsmm,snnn/tensorflow,sarvex/tensorflow,Intel-tensorflow/tensorflow,DavidNorman/tensorflow,ghchinoy/tensorflow,AnishShah/tensorflow,jendap/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jalexvig/tensorflow,ghchinoy/tensorflow,hehongliang/tensorflow,yanchen036/tensorflow,jendap/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,allenlavoie/tensorflow,freedomtan/tensorflow,av8ramit/tensorflow,benoitsteiner/tensorflow-xsmm,tensorflow/tensorflow,apark263/tensorflow,aselle/tensorflow,seanli9jan/tensorflow,Mistobaan/tensorflow,renyi533/tensorflow,aselle/tensorflow,seanli9jan/tensorflow,gojira/tensorflow,rabipanda/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jendap/tensorflow,aldian/tensorflow,meteorcloudy/tensorflow,sarvex/tensorflow,karllessard/tensorflow,kobejean/tensorflow,nolanliou/tensorflow,alsrgv/tensorflow,eadgarchen/tensorflow,AnishShah/tensorflow,jwlawson/tensorflow,allenlavoie/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,nolanliou/tensorflow,petewarden/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,nburn42/tensorflow,aldian/tensorflow,lakshayg/tensorflow,zasdfgbnm/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,alsrgv/tensorflow,jwlawson/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,snnn/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ppwwyyxx/tensorflow,lakshayg/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,aam-at/tensorflow,gojira/tensorflow,ppwwyyxx/tensorflow,codrut3/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,girving/tensorflow,jbedorf/tensorflow,tensorflow/tensorflow,manipopopo/tensorflow,arborh/tensorflow,dongjoon-hyun/tensorflow,hsaputra/tensorflow,eadgarchen/tensorflow,dendisuhubdy/tensorflow,ageron/tensorflow,hsaputra/tensorflow,aam-at/tensorflow,apark263/tensorflow,girving/tensorflow,lakshayg/tensorflow,ppwwyyxx/tensorflow,theflofly/tensorflow,jwlawson/tensorflow,cxxgtxy/tensorflow,allenlavoie/tensorflow,gojira/tensorflow,girving/tensorflow,tensorflow/tensorflow,seanli9jan/tensorflow,hsaputra/tensorflow,xodus7/tensorflow,ghchinoy/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,dendisuhubdy/tensorflow,jwlawson/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,lakshayg/tensorflow,girving/tensorflow,paolodedios/tensorflow,ravindrapanda/tensorflow,Intel-tensorflow/tensorflow,ageron/tensorflow,seanli9jan/tensorflow,nolanliou/tensorflow,caisq/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,yongtang/tensorflow,Xeralux/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,manipopopo/tensorflow,hfp/tensorflow-xsmm,caisq/tensorflow,rabipanda/tensorflow,chemelnucfin/tensorflow,ageron/tensorflow,davidzchen/tensorflow,apark263/tensorflow,Mistobaan/tensorflow,jwlawson/tensorflow,xodus7/tensorflow,kobejean/tensorflow,alsrgv/tensorflow,lakshayg/tensorflow,lakshayg/tensorflow,arborh/tensorflow,eaplatanios/tensorflow,jbedorf/tensorflow,allenlavoie/tensorflow,davidzchen/tensorflow,kevin-coder/tensorflow-fork,apark263/tensorflow,av8ramit/tensorflow,caisq/tensorflow,benoitsteiner/tensorflow-xsmm,Mistobaan/tensorflow,gautam1858/tensorflow,aselle/tensorflow,cxxgtxy/tensorflow,xzturn/tensorflow,ghchinoy/tensorflow,AnishShah/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,JingJunYin/tensorflow,Bismarrck/tensorflow,chemelnucfin/tensorflow,jhseu/tensorflow,kobejean/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,JingJunYin/tensorflow,Bismarrck/tensorflow,frreiss/tensorflow-fred,chemelnucfin/tensorflow,frreiss/tensorflow-fred,asimshankar/tensorflow,aselle/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,adit-chandra/tensorflow,jendap/tensorflow,jwlawson/tensorflow,dendisuhubdy/tensorflow,gunan/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,eadgarchen/tensorflow,yongtang/tensorflow,jalexvig/tensorflow,annarev/tensorflow,kevin-coder/tensorflow-fork,AnishShah/tensorflow,jendap/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,kobejean/tensorflow,asimshankar/tensorflow,cxxgtxy/tensorflow,yongtang/tensorflow,av8ramit/tensorflow,alsrgv/tensorflow,zasdfgbnm/tensorflow,gunan/tensorflow,Mistobaan/tensorflow,dongjoon-hyun/tensorflow,dongjoon-hyun/tensorflow,brchiu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,dancingdan/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ageron/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,paolodedios/tensorflow,brchiu/tensorflow,benoitsteiner/tensorflow-xsmm,ZhangXinNan/tensorflow,kevin-coder/tensorflow-fork,ghchinoy/tensorflow,gojira/tensorflow,chemelnucfin/tensorflow,JingJunYin/tensorflow,jart/tensorflow,aselle/tensorflow,xzturn/tensorflow,caisq/tensorflow,freedomtan/tensorflow,allenlavoie/tensorflow,brchiu/tensorflow,asimshankar/tensorflow,alsrgv/tensorflow,Mistobaan/tensorflow,petewarden/tensorflow,kobejean/tensorflow,ageron/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,yanchen036/tensorflow,asimshankar/tensorflow,xodus7/tensorflow,chemelnucfin/tensorflow,allenlavoie/tensorflow,eadgarchen/tensorflow,jwlawson/tensorflow,meteorcloudy/tensorflow,Intel-Corporation/tensorflow,hsaputra/tensorflow,dongjoon-hyun/tensorflow,arborh/tensorflow,caisq/tensorflow,av8ramit/tensorflow,alsrgv/tensorflow,nburn42/tensorflow,alshedivat/tensorflow,frreiss/tensorflow-fred,kobejean/tensorflow,jalexvig/tensorflow,hsaputra/tensorflow,cxxgtxy/tensorflow,xodus7/tensorflow,kevin-coder/tensorflow-fork,lukeiwanski/tensorflow,av8ramit/tensorflow,gautam1858/tensorflow,eaplatanios/tensorflow,benoitsteiner/tensorflow-xsmm,jhseu/tensorflow,theflofly/tensorflow,sarvex/tensorflow,brchiu/tensorflow,Bismarrck/tensorflow,jhseu/tensorflow,xzturn/tensorflow,ZhangXinNan/tensorflow,drpngx/tensorflow,theflofly/tensorflow,yanchen036/tensorflow,Intel-Corporation/tensorflow,zasdfgbnm/tensorflow,apark263/tensorflow,gojira/tensorflow,Mistobaan/tensorflow,eaplatanios/tensorflow,nolanliou/tensorflow,Kongsea/tensorflow,karllessard/tensorflow,jart/tensorflow,nolanliou/tensorflow,meteorcloudy/tensorflow,seanli9jan/tensorflow,tensorflow/tensorflow,eadgarchen/tensorflow,jendap/tensorflow,lukeiwanski/tensorflow,aam-at/tensorflow,asimshankar/tensorflow,dancingdan/tensorflow,lakshayg/tensorflow,gojira/tensorflow,eadgarchen/tensorflow,frreiss/tensorflow-fred,aselle/tensorflow,theflofly/tensorflow,ZhangXinNan/tensorflow,girving/tensorflow,snnn/tensorflow,eadgarchen/tensorflow,Intel-tensorflow/tensorflow,gojira/tensorflow,cxxgtxy/tensorflow,kevin-coder/tensorflow-fork,alshedivat/tensorflow,asimshankar/tensorflow,aselle/tensorflow,gunan/tensorflow,xzturn/tensorflow,snnn/tensorflow,nburn42/tensorflow,av8ramit/tensorflow,hfp/tensorflow-xsmm,DavidNorman/tensorflow,Kongsea/tensorflow,jendap/tensorflow,dancingdan/tensorflow,yanchen036/tensorflow,karllessard/tensorflow,alsrgv/tensorflow,rabipanda/tensorflow,hsaputra/tensorflow,jart/tensorflow,aselle/tensorflow,gautam1858/tensorflow,meteorcloudy/tensorflow,av8ramit/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,meteorcloudy/tensorflow,xzturn/tensorflow,jhseu/tensorflow,jalexvig/tensorflow,seanli9jan/tensorflow,theflofly/tensorflow,jendap/tensorflow,eaplatanios/tensorflow,hehongliang/tensorflow,aselle/tensorflow,Intel-tensorflow/tensorflow,nburn42/tensorflow,seanli9jan/tensorflow,karllessard/tensorflow,adit-chandra/tensorflow,jhseu/tensorflow,karllessard/tensorflow,seanli9jan/tensorflow,theflofly/tensorflow,davidzchen/tensorflow,annarev/tensorflow,gojira/tensorflow,nolanliou/tensorflow,renyi533/tensorflow,codrut3/tensorflow,eaplatanios/tensorflow,dongjoon-hyun/tensorflow,alshedivat/tensorflow,ravindrapanda/tensorflow,adit-chandra/tensorflow,sarvex/tensorflow,davidzchen/tensorflow,rabipanda/tensorflow,drpngx/tensorflow,benoitsteiner/tensorflow-xsmm,Xeralux/tensorflow,jhseu/tensorflow,Intel-tensorflow/tensorflow,dongjoon-hyun/tensorflow,hsaputra/tensorflow,jwlawson/tensorflow,DavidNorman/tensorflow,JingJunYin/tensorflow,av8ramit/tensorflow,nolanliou/tensorflow,nburn42/tensorflow,ageron/tensorflow,codrut3/tensorflow,freedomtan/tensorflow,jwlawson/tensorflow,Mistobaan/tensorflow,JingJunYin/tensorflow,AnishShah/tensorflow,davidzchen/tensorflow,hehongliang/tensorflow,sarvex/tensorflow,hfp/tensorflow-xsmm,zasdfgbnm/tensorflow,jbedorf/tensorflow,adit-chandra/tensorflow,Xeralux/tensorflow,seanli9jan/tensorflow,Bismarrck/tensorflow,chemelnucfin/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,ravindrapanda/tensorflow,snnn/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow,ghchinoy/tensorflow,drpngx/tensorflow,av8ramit/tensorflow,annarev/tensorflow,sarvex/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,DavidNorman/tensorflow,girving/tensorflow,aldian/tensorflow,arborh/tensorflow,nburn42/tensorflow,frreiss/tensorflow-fred,jart/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,kevin-coder/tensorflow-fork,petewarden/tensorflow,nolanliou/tensorflow,hfp/tensorflow-xsmm,asimshankar/tensorflow,lukeiwanski/tensorflow,nburn42/tensorflow,freedomtan/tensorflow,davidzchen/tensorflow,manipopopo/tensorflow,ppwwyyxx/tensorflow,nburn42/tensorflow,gunan/tensorflow,Kongsea/tensorflow,Bismarrck/tensorflow,Xeralux/tensorflow,Intel-tensorflow/tensorflow,xzturn/tensorflow,dongjoon-hyun/tensorflow,DavidNorman/tensorflow,Bismarrck/tensorflow,gunan/tensorflow,arborh/tensorflow,kevin-coder/tensorflow-fork,nburn42/tensorflow,chemelnucfin/tensorflow,codrut3/tensorflow,eadgarchen/tensorflow,petewarden/tensorflow,benoitsteiner/tensorflow-xsmm,aldian/tensorflow,Kongsea/tensorflow,alshedivat/tensorflow,tensorflow/tensorflow,yanchen036/tensorflow,alsrgv/tensorflow
cc1ffc6652e3ed42529037f9aaede4ac51d5e52f
lib/Analysis/IVUsers.cpp
lib/Analysis/IVUsers.cpp
//===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements bookkeeping for "interesting" users of expressions // computed from induction variables. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "iv-users" #include "llvm/Analysis/IVUsers.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/DerivedTypes.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetData.h" #include "llvm/Assembly/Writer.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace llvm; char IVUsers::ID = 0; INITIALIZE_PASS_BEGIN(IVUsers, "iv-users", "Induction Variable Users", false, true) INITIALIZE_PASS_DEPENDENCY(LoopInfo) INITIALIZE_PASS_DEPENDENCY(DominatorTree) INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) INITIALIZE_PASS_END(IVUsers, "iv-users", "Induction Variable Users", false, true) // IVUsers behavior currently depends on this temporary indvars mode. The // option must be defined upstream from its uses. namespace llvm { bool DisableIVRewrite = false; } cl::opt<bool, true> DisableIVRewriteOpt( "disable-iv-rewrite", cl::Hidden, cl::location(llvm::DisableIVRewrite), cl::desc("Disable canonical induction variable rewriting")); Pass *llvm::createIVUsersPass() { return new IVUsers(); } /// isInteresting - Test whether the given expression is "interesting" when /// used by the given expression, within the context of analyzing the /// given loop. static bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L, ScalarEvolution *SE) { // An addrec is interesting if it's affine or if it has an interesting start. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { // Keep things simple. Don't touch loop-variant strides. if (AR->getLoop() == L) return AR->isAffine() || !L->contains(I); // Otherwise recurse to see if the start value is interesting, and that // the step value is not interesting, since we don't yet know how to // do effective SCEV expansions for addrecs with interesting steps. return isInteresting(AR->getStart(), I, L, SE) && !isInteresting(AR->getStepRecurrence(*SE), I, L, SE); } // An add is interesting if exactly one of its operands is interesting. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { bool AnyInterestingYet = false; for (SCEVAddExpr::op_iterator OI = Add->op_begin(), OE = Add->op_end(); OI != OE; ++OI) if (isInteresting(*OI, I, L, SE)) { if (AnyInterestingYet) return false; AnyInterestingYet = true; } return AnyInterestingYet; } // Nothing else is interesting here. return false; } /// AddUsersIfInteresting - Inspect the specified instruction. If it is a /// reducible SCEV, recursively add its users to the IVUsesByStride set and /// return true. Otherwise, return false. bool IVUsers::AddUsersIfInteresting(Instruction *I, PHINode *Phi) { if (!SE->isSCEVable(I->getType())) return false; // Void and FP expressions cannot be reduced. // LSR is not APInt clean, do not touch integers bigger than 64-bits. // Also avoid creating IVs of non-native types. For example, we don't want a // 64-bit IV in 32-bit code just because the loop has one 64-bit cast. uint64_t Width = SE->getTypeSizeInBits(I->getType()); if (Width > 64 || (TD && !TD->isLegalInteger(Width))) return false; // We expect Sign/Zero extension to be eliminated from the IR before analyzing // any downstream uses. if (DisableIVRewrite && (isa<SExtInst>(I) || isa<ZExtInst>(I))) return false; if (!Processed.insert(I)) return true; // Instruction already handled. // Get the symbolic expression for this instruction. const SCEV *ISE = SE->getSCEV(I); // If we've come to an uninteresting expression, stop the traversal and // call this a user. if (!isInteresting(ISE, I, L, SE)) return false; SmallPtrSet<Instruction *, 4> UniqueUsers; for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { Instruction *User = cast<Instruction>(*UI); if (!UniqueUsers.insert(User)) continue; // Do not infinitely recurse on PHI nodes. if (isa<PHINode>(User) && Processed.count(User)) continue; // Descend recursively, but not into PHI nodes outside the current loop. // It's important to see the entire expression outside the loop to get // choices that depend on addressing mode use right, although we won't // consider references outside the loop in all cases. // If User is already in Processed, we don't want to recurse into it again, // but do want to record a second reference in the same instruction. bool AddUserToIVUsers = false; if (LI->getLoopFor(User->getParent()) != L) { if (isa<PHINode>(User) || Processed.count(User) || !AddUsersIfInteresting(User, Phi)) { DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n' << " OF SCEV: " << *ISE << '\n'); AddUserToIVUsers = true; } } else if (Processed.count(User) || !AddUsersIfInteresting(User, Phi)) { DEBUG(dbgs() << "FOUND USER: " << *User << '\n' << " OF SCEV: " << *ISE << '\n'); AddUserToIVUsers = true; } if (AddUserToIVUsers) { // Okay, we found a user that we cannot reduce. IVUses.push_back(new IVStrideUse(this, User, I, Phi)); IVStrideUse &NewUse = IVUses.back(); // Transform the expression into a normalized form. ISE = TransformForPostIncUse(NormalizeAutodetect, ISE, User, I, NewUse.PostIncLoops, *SE, *DT); DEBUG(dbgs() << " NORMALIZED TO: " << *ISE << '\n'); } } return true; } IVStrideUse &IVUsers::AddUser(Instruction *User, Value *Operand, PHINode *Phi) { IVUses.push_back(new IVStrideUse(this, User, Operand, Phi)); return IVUses.back(); } IVUsers::IVUsers() : LoopPass(ID) { initializeIVUsersPass(*PassRegistry::getPassRegistry()); } void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LoopInfo>(); AU.addRequired<DominatorTree>(); AU.addRequired<ScalarEvolution>(); AU.setPreservesAll(); } bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) { L = l; LI = &getAnalysis<LoopInfo>(); DT = &getAnalysis<DominatorTree>(); SE = &getAnalysis<ScalarEvolution>(); TD = getAnalysisIfAvailable<TargetData>(); // Find all uses of induction variables in this loop, and categorize // them by stride. Start by finding all of the PHI nodes in the header for // this loop. If they are induction variables, inspect their uses. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) (void)AddUsersIfInteresting(I, cast<PHINode>(I)); return false; } void IVUsers::print(raw_ostream &OS, const Module *M) const { OS << "IV Users for loop "; WriteAsOperand(OS, L->getHeader(), false); if (SE->hasLoopInvariantBackedgeTakenCount(L)) { OS << " with backedge-taken count " << *SE->getBackedgeTakenCount(L); } OS << ":\n"; for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(), E = IVUses.end(); UI != E; ++UI) { OS << " "; WriteAsOperand(OS, UI->getOperandValToReplace(), false); OS << " = " << *getReplacementExpr(*UI); for (PostIncLoopSet::const_iterator I = UI->PostIncLoops.begin(), E = UI->PostIncLoops.end(); I != E; ++I) { OS << " (post-inc with loop "; WriteAsOperand(OS, (*I)->getHeader(), false); OS << ")"; } OS << " in "; UI->getUser()->print(OS); OS << '\n'; } } void IVUsers::dump() const { print(dbgs()); } void IVUsers::releaseMemory() { Processed.clear(); IVUses.clear(); } /// getReplacementExpr - Return a SCEV expression which computes the /// value of the OperandValToReplace. const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &IU) const { return SE->getSCEV(IU.getOperandValToReplace()); } /// getExpr - Return the expression for the use. const SCEV *IVUsers::getExpr(const IVStrideUse &IU) const { return TransformForPostIncUse(Normalize, getReplacementExpr(IU), IU.getUser(), IU.getOperandValToReplace(), const_cast<PostIncLoopSet &>(IU.getPostIncLoops()), *SE, *DT); } static const SCEVAddRecExpr *findAddRecForLoop(const SCEV *S, const Loop *L) { if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { if (AR->getLoop() == L) return AR; return findAddRecForLoop(AR->getStart(), L); } if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end(); I != E; ++I) if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L)) return AR; return 0; } return 0; } const SCEV *IVUsers::getStride(const IVStrideUse &IU, const Loop *L) const { if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(IU), L)) return AR->getStepRecurrence(*SE); return 0; } void IVStrideUse::transformToPostInc(const Loop *L) { PostIncLoops.insert(L); } void IVStrideUse::deleted() { // Remove this user from the list. Parent->IVUses.erase(this); // this now dangles! }
//===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements bookkeeping for "interesting" users of expressions // computed from induction variables. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "iv-users" #include "llvm/Analysis/IVUsers.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/DerivedTypes.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetData.h" #include "llvm/Assembly/Writer.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace llvm; char IVUsers::ID = 0; INITIALIZE_PASS_BEGIN(IVUsers, "iv-users", "Induction Variable Users", false, true) INITIALIZE_PASS_DEPENDENCY(LoopInfo) INITIALIZE_PASS_DEPENDENCY(DominatorTree) INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) INITIALIZE_PASS_END(IVUsers, "iv-users", "Induction Variable Users", false, true) // IVUsers behavior currently depends on this temporary indvars mode. The // option must be defined upstream from its uses. namespace llvm { bool DisableIVRewrite = false; } cl::opt<bool, true> DisableIVRewriteOpt( "disable-iv-rewrite", cl::Hidden, cl::location(llvm::DisableIVRewrite), cl::desc("Disable canonical induction variable rewriting")); Pass *llvm::createIVUsersPass() { return new IVUsers(); } /// isInteresting - Test whether the given expression is "interesting" when /// used by the given expression, within the context of analyzing the /// given loop. static bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L, ScalarEvolution *SE) { // An addrec is interesting if it's affine or if it has an interesting start. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { // Keep things simple. Don't touch loop-variant strides. if (AR->getLoop() == L) return AR->isAffine() || !L->contains(I); // Otherwise recurse to see if the start value is interesting, and that // the step value is not interesting, since we don't yet know how to // do effective SCEV expansions for addrecs with interesting steps. return isInteresting(AR->getStart(), I, L, SE) && !isInteresting(AR->getStepRecurrence(*SE), I, L, SE); } // An add is interesting if exactly one of its operands is interesting. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { bool AnyInterestingYet = false; for (SCEVAddExpr::op_iterator OI = Add->op_begin(), OE = Add->op_end(); OI != OE; ++OI) if (isInteresting(*OI, I, L, SE)) { if (AnyInterestingYet) return false; AnyInterestingYet = true; } return AnyInterestingYet; } // Nothing else is interesting here. return false; } /// AddUsersIfInteresting - Inspect the specified instruction. If it is a /// reducible SCEV, recursively add its users to the IVUsesByStride set and /// return true. Otherwise, return false. bool IVUsers::AddUsersIfInteresting(Instruction *I, PHINode *Phi) { if (!SE->isSCEVable(I->getType())) return false; // Void and FP expressions cannot be reduced. // LSR is not APInt clean, do not touch integers bigger than 64-bits. // Also avoid creating IVs of non-native types. For example, we don't want a // 64-bit IV in 32-bit code just because the loop has one 64-bit cast. uint64_t Width = SE->getTypeSizeInBits(I->getType()); if (Width > 64 || (TD && !TD->isLegalInteger(Width))) return false; // We expect Sign/Zero extension to be eliminated from the IR before analyzing // any downstream uses. if (DisableIVRewrite && (isa<SExtInst>(I) || isa<ZExtInst>(I))) return false; if (!Processed.insert(I)) return true; // Instruction already handled. // Get the symbolic expression for this instruction. const SCEV *ISE = SE->getSCEV(I); // If we've come to an uninteresting expression, stop the traversal and // call this a user. if (!isInteresting(ISE, I, L, SE)) return false; SmallPtrSet<Instruction *, 4> UniqueUsers; for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { Instruction *User = cast<Instruction>(*UI); if (!UniqueUsers.insert(User)) continue; // Do not infinitely recurse on PHI nodes. if (isa<PHINode>(User) && Processed.count(User)) continue; // Descend recursively, but not into PHI nodes outside the current loop. // It's important to see the entire expression outside the loop to get // choices that depend on addressing mode use right, although we won't // consider references outside the loop in all cases. // If User is already in Processed, we don't want to recurse into it again, // but do want to record a second reference in the same instruction. bool AddUserToIVUsers = false; if (LI->getLoopFor(User->getParent()) != L) { if (isa<PHINode>(User) || Processed.count(User) || !AddUsersIfInteresting(User, Phi)) { DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n' << " OF SCEV: " << *ISE << '\n'); AddUserToIVUsers = true; } } else if (Processed.count(User) || !AddUsersIfInteresting(User, Phi)) { DEBUG(dbgs() << "FOUND USER: " << *User << '\n' << " OF SCEV: " << *ISE << '\n'); AddUserToIVUsers = true; } if (AddUserToIVUsers) { // Okay, we found a user that we cannot reduce. IVUses.push_back(new IVStrideUse(this, User, I, Phi)); IVStrideUse &NewUse = IVUses.back(); // Autodetect the post-inc loop set, populating NewUse.PostIncLoops. // The regular return value here is discarded; instead of recording // it, we just recompute it when we need it. ISE = TransformForPostIncUse(NormalizeAutodetect, ISE, User, I, NewUse.PostIncLoops, *SE, *DT); DEBUG(dbgs() << " NORMALIZED TO: " << *ISE << '\n'); } } return true; } IVStrideUse &IVUsers::AddUser(Instruction *User, Value *Operand, PHINode *Phi) { IVUses.push_back(new IVStrideUse(this, User, Operand, Phi)); return IVUses.back(); } IVUsers::IVUsers() : LoopPass(ID) { initializeIVUsersPass(*PassRegistry::getPassRegistry()); } void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LoopInfo>(); AU.addRequired<DominatorTree>(); AU.addRequired<ScalarEvolution>(); AU.setPreservesAll(); } bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) { L = l; LI = &getAnalysis<LoopInfo>(); DT = &getAnalysis<DominatorTree>(); SE = &getAnalysis<ScalarEvolution>(); TD = getAnalysisIfAvailable<TargetData>(); // Find all uses of induction variables in this loop, and categorize // them by stride. Start by finding all of the PHI nodes in the header for // this loop. If they are induction variables, inspect their uses. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) (void)AddUsersIfInteresting(I, cast<PHINode>(I)); return false; } void IVUsers::print(raw_ostream &OS, const Module *M) const { OS << "IV Users for loop "; WriteAsOperand(OS, L->getHeader(), false); if (SE->hasLoopInvariantBackedgeTakenCount(L)) { OS << " with backedge-taken count " << *SE->getBackedgeTakenCount(L); } OS << ":\n"; for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(), E = IVUses.end(); UI != E; ++UI) { OS << " "; WriteAsOperand(OS, UI->getOperandValToReplace(), false); OS << " = " << *getReplacementExpr(*UI); for (PostIncLoopSet::const_iterator I = UI->PostIncLoops.begin(), E = UI->PostIncLoops.end(); I != E; ++I) { OS << " (post-inc with loop "; WriteAsOperand(OS, (*I)->getHeader(), false); OS << ")"; } OS << " in "; UI->getUser()->print(OS); OS << '\n'; } } void IVUsers::dump() const { print(dbgs()); } void IVUsers::releaseMemory() { Processed.clear(); IVUses.clear(); } /// getReplacementExpr - Return a SCEV expression which computes the /// value of the OperandValToReplace. const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &IU) const { return SE->getSCEV(IU.getOperandValToReplace()); } /// getExpr - Return the expression for the use. const SCEV *IVUsers::getExpr(const IVStrideUse &IU) const { return TransformForPostIncUse(Normalize, getReplacementExpr(IU), IU.getUser(), IU.getOperandValToReplace(), const_cast<PostIncLoopSet &>(IU.getPostIncLoops()), *SE, *DT); } static const SCEVAddRecExpr *findAddRecForLoop(const SCEV *S, const Loop *L) { if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { if (AR->getLoop() == L) return AR; return findAddRecForLoop(AR->getStart(), L); } if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end(); I != E; ++I) if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L)) return AR; return 0; } return 0; } const SCEV *IVUsers::getStride(const IVStrideUse &IU, const Loop *L) const { if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(IU), L)) return AR->getStepRecurrence(*SE); return 0; } void IVStrideUse::transformToPostInc(const Loop *L) { PostIncLoops.insert(L); } void IVStrideUse::deleted() { // Remove this user from the list. Parent->IVUses.erase(this); // this now dangles! }
Update this comment.
Update this comment. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@132202 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap
0eff4e73d58cf28458470beec31b33bcb302377c
lib/Basic/TargetInfo.cpp
lib/Basic/TargetInfo.cpp
//===--- TargetInfo.cpp - Information about Target machine ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TargetInfo and TargetInfoImpl interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/TargetInfo.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include <cstdlib> using namespace clang; // TargetInfo Constructor. TargetInfo::TargetInfo(const std::string &T) : Triple(T) { // Set defaults. Defaults are set for a 32-bit RISC platform, like PPC or // SPARC. These should be overridden by concrete targets as needed. TLSSupported = true; NoAsmVariants = false; PointerWidth = PointerAlign = 32; IntWidth = IntAlign = 32; LongWidth = LongAlign = 32; LongLongWidth = LongLongAlign = 64; FloatWidth = 32; FloatAlign = 32; DoubleWidth = 64; DoubleAlign = 64; LongDoubleWidth = 64; LongDoubleAlign = 64; LargeArrayMinWidth = 0; LargeArrayAlign = 0; SizeType = UnsignedLong; PtrDiffType = SignedLong; IntMaxType = SignedLongLong; UIntMaxType = UnsignedLongLong; IntPtrType = SignedLong; WCharType = SignedInt; WIntType = SignedInt; Char16Type = UnsignedShort; Char32Type = UnsignedInt; Int64Type = SignedLongLong; SigAtomicType = SignedInt; UseBitFieldTypeAlignment = true; FloatFormat = &llvm::APFloat::IEEEsingle; DoubleFormat = &llvm::APFloat::IEEEdouble; LongDoubleFormat = &llvm::APFloat::IEEEdouble; DescriptionString = "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-n32"; UserLabelPrefix = "_"; HasAlignMac68kSupport = false; // Default to no types using fpret. RealTypeUsesObjCFPRet = 0; } // Out of line virtual dtor for TargetInfo. TargetInfo::~TargetInfo() {} /// getTypeName - Return the user string for the specified integer type enum. /// For example, SignedShort -> "short". const char *TargetInfo::getTypeName(IntType T) { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: return "short"; case UnsignedShort: return "unsigned short"; case SignedInt: return "int"; case UnsignedInt: return "unsigned int"; case SignedLong: return "long int"; case UnsignedLong: return "long unsigned int"; case SignedLongLong: return "long long int"; case UnsignedLongLong: return "long long unsigned int"; } } /// getTypeConstantSuffix - Return the constant suffix for the specified /// integer type enum. For example, SignedLong -> "L". const char *TargetInfo::getTypeConstantSuffix(IntType T) { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case SignedInt: return ""; case SignedLong: return "L"; case SignedLongLong: return "LL"; case UnsignedShort: case UnsignedInt: return "U"; case UnsignedLong: return "UL"; case UnsignedLongLong: return "ULL"; } } /// getTypeWidth - Return the width (in bits) of the specified integer type /// enum. For example, SignedInt -> getIntWidth(). unsigned TargetInfo::getTypeWidth(IntType T) const { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case UnsignedShort: return getShortWidth(); case SignedInt: case UnsignedInt: return getIntWidth(); case SignedLong: case UnsignedLong: return getLongWidth(); case SignedLongLong: case UnsignedLongLong: return getLongLongWidth(); }; } /// getTypeAlign - Return the alignment (in bits) of the specified integer type /// enum. For example, SignedInt -> getIntAlign(). unsigned TargetInfo::getTypeAlign(IntType T) const { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case UnsignedShort: return getShortAlign(); case SignedInt: case UnsignedInt: return getIntAlign(); case SignedLong: case UnsignedLong: return getLongAlign(); case SignedLongLong: case UnsignedLongLong: return getLongLongAlign(); }; } /// isTypeSigned - Return whether an integer types is signed. Returns true if /// the type is signed; false otherwise. bool TargetInfo::isTypeSigned(IntType T) const { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case SignedInt: case SignedLong: case SignedLongLong: return true; case UnsignedShort: case UnsignedInt: case UnsignedLong: case UnsignedLongLong: return false; }; } /// setForcedLangOptions - Set forced language options. /// Apply changes to the target information with respect to certain /// language options which change the target configuration. void TargetInfo::setForcedLangOptions(LangOptions &Opts) { if (Opts.NoBitFieldTypeAlign) UseBitFieldTypeAlignment = false; if (Opts.ShortWChar) WCharType = UnsignedShort; } //===----------------------------------------------------------------------===// static llvm::StringRef removeGCCRegisterPrefix(llvm::StringRef Name) { if (Name[0] == '%' || Name[0] == '#') Name = Name.substr(1); return Name; } /// isValidGCCRegisterName - Returns whether the passed in string /// is a valid register name according to GCC. This is used by Sema for /// inline asm statements. bool TargetInfo::isValidGCCRegisterName(llvm::StringRef Name) const { if (Name.empty()) return false; const char * const *Names; unsigned NumNames; // Get rid of any register prefix. Name = removeGCCRegisterPrefix(Name); if (Name == "memory" || Name == "cc") return true; getGCCRegNames(Names, NumNames); // If we have a number it maps to an entry in the register name array. if (isdigit(Name[0])) { int n; if (!Name.getAsInteger(0, n)) return n >= 0 && (unsigned)n < NumNames; } // Check register names. for (unsigned i = 0; i < NumNames; i++) { if (Name == Names[i]) return true; } // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { if (!Aliases[i].Aliases[j]) break; if (Aliases[i].Aliases[j] == Name) return true; } } return false; } llvm::StringRef TargetInfo::getNormalizedGCCRegisterName(llvm::StringRef Name) const { assert(isValidGCCRegisterName(Name) && "Invalid register passed in"); // Get rid of any register prefix. Name = removeGCCRegisterPrefix(Name); const char * const *Names; unsigned NumNames; getGCCRegNames(Names, NumNames); // First, check if we have a number. if (isdigit(Name[0])) { int n; if (!Name.getAsInteger(0, n)) { assert(n >= 0 && (unsigned)n < NumNames && "Out of bounds register number!"); return Names[n]; } } // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { if (!Aliases[i].Aliases[j]) break; if (Aliases[i].Aliases[j] == Name) return Aliases[i].Register; } } return Name; } bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const { const char *Name = Info.getConstraintStr().c_str(); // An output constraint must start with '=' or '+' if (*Name != '=' && *Name != '+') return false; if (*Name == '+') Info.setIsReadWrite(); Name++; while (*Name) { switch (*Name) { default: if (!validateAsmConstraint(Name, Info)) { // FIXME: We temporarily return false // so we can add more constraints as we hit it. // Eventually, an unknown constraint should just be treated as 'g'. return false; } case '&': // early clobber. break; case '%': // commutative. // FIXME: Check that there is a another register after this one. break; case 'r': // general register. Info.setAllowsRegister(); break; case 'm': // memory operand. Info.setAllowsMemory(); break; case 'g': // general register, memory operand or immediate integer. case 'X': // any operand. Info.setAllowsRegister(); Info.setAllowsMemory(); break; case ',': // multiple alternative constraint. Pass it. Name++; // Handle additional optional '=' or '+' modifiers. if (*Name == '=' || *Name == '+') Name++; break; case '?': // Disparage slightly code. case '!': // Disparage severly. break; // Pass them. } Name++; } return true; } bool TargetInfo::resolveSymbolicName(const char *&Name, ConstraintInfo *OutputConstraints, unsigned NumOutputs, unsigned &Index) const { assert(*Name == '[' && "Symbolic name did not start with '['"); Name++; const char *Start = Name; while (*Name && *Name != ']') Name++; if (!*Name) { // Missing ']' return false; } std::string SymbolicName(Start, Name - Start); for (Index = 0; Index != NumOutputs; ++Index) if (SymbolicName == OutputConstraints[Index].getName()) return true; return false; } bool TargetInfo::validateInputConstraint(ConstraintInfo *OutputConstraints, unsigned NumOutputs, ConstraintInfo &Info) const { const char *Name = Info.ConstraintStr.c_str(); while (*Name) { switch (*Name) { default: // Check if we have a matching constraint if (*Name >= '0' && *Name <= '9') { unsigned i = *Name - '0'; // Check if matching constraint is out of bounds. if (i >= NumOutputs) return false; // The constraint should have the same info as the respective // output constraint. Info.setTiedOperand(i, OutputConstraints[i]); } else if (!validateAsmConstraint(Name, Info)) { // FIXME: This error return is in place temporarily so we can // add more constraints as we hit it. Eventually, an unknown // constraint should just be treated as 'g'. return false; } break; case '[': { unsigned Index = 0; if (!resolveSymbolicName(Name, OutputConstraints, NumOutputs, Index)) return false; break; } case '%': // commutative // FIXME: Fail if % is used with the last operand. break; case 'i': // immediate integer. case 'n': // immediate integer with a known value. break; case 'I': // Various constant constraints with target-specific meanings. case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': break; case 'r': // general register. Info.setAllowsRegister(); break; case 'm': // memory operand. case 'o': // offsettable memory operand case 'V': // non-offsettable memory operand Info.setAllowsMemory(); break; case 'g': // general register, memory operand or immediate integer. case 'X': // any operand. Info.setAllowsRegister(); Info.setAllowsMemory(); break; case ',': // multiple alternative constraint. Ignore comma. break; case '?': // Disparage slightly code. case '!': // Disparage severly. break; // Pass them. } Name++; } return true; }
//===--- TargetInfo.cpp - Information about Target machine ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TargetInfo and TargetInfoImpl interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/TargetInfo.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include <cstdlib> using namespace clang; // TargetInfo Constructor. TargetInfo::TargetInfo(const std::string &T) : Triple(T) { // Set defaults. Defaults are set for a 32-bit RISC platform, like PPC or // SPARC. These should be overridden by concrete targets as needed. TLSSupported = true; NoAsmVariants = false; PointerWidth = PointerAlign = 32; IntWidth = IntAlign = 32; LongWidth = LongAlign = 32; LongLongWidth = LongLongAlign = 64; FloatWidth = 32; FloatAlign = 32; DoubleWidth = 64; DoubleAlign = 64; LongDoubleWidth = 64; LongDoubleAlign = 64; LargeArrayMinWidth = 0; LargeArrayAlign = 0; SizeType = UnsignedLong; PtrDiffType = SignedLong; IntMaxType = SignedLongLong; UIntMaxType = UnsignedLongLong; IntPtrType = SignedLong; WCharType = SignedInt; WIntType = SignedInt; Char16Type = UnsignedShort; Char32Type = UnsignedInt; Int64Type = SignedLongLong; SigAtomicType = SignedInt; UseBitFieldTypeAlignment = true; FloatFormat = &llvm::APFloat::IEEEsingle; DoubleFormat = &llvm::APFloat::IEEEdouble; LongDoubleFormat = &llvm::APFloat::IEEEdouble; DescriptionString = "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-n32"; UserLabelPrefix = "_"; HasAlignMac68kSupport = false; // Default to no types using fpret. RealTypeUsesObjCFPRet = 0; } // Out of line virtual dtor for TargetInfo. TargetInfo::~TargetInfo() {} /// getTypeName - Return the user string for the specified integer type enum. /// For example, SignedShort -> "short". const char *TargetInfo::getTypeName(IntType T) { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: return "short"; case UnsignedShort: return "unsigned short"; case SignedInt: return "int"; case UnsignedInt: return "unsigned int"; case SignedLong: return "long int"; case UnsignedLong: return "long unsigned int"; case SignedLongLong: return "long long int"; case UnsignedLongLong: return "long long unsigned int"; } } /// getTypeConstantSuffix - Return the constant suffix for the specified /// integer type enum. For example, SignedLong -> "L". const char *TargetInfo::getTypeConstantSuffix(IntType T) { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case SignedInt: return ""; case SignedLong: return "L"; case SignedLongLong: return "LL"; case UnsignedShort: case UnsignedInt: return "U"; case UnsignedLong: return "UL"; case UnsignedLongLong: return "ULL"; } } /// getTypeWidth - Return the width (in bits) of the specified integer type /// enum. For example, SignedInt -> getIntWidth(). unsigned TargetInfo::getTypeWidth(IntType T) const { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case UnsignedShort: return getShortWidth(); case SignedInt: case UnsignedInt: return getIntWidth(); case SignedLong: case UnsignedLong: return getLongWidth(); case SignedLongLong: case UnsignedLongLong: return getLongLongWidth(); }; } /// getTypeAlign - Return the alignment (in bits) of the specified integer type /// enum. For example, SignedInt -> getIntAlign(). unsigned TargetInfo::getTypeAlign(IntType T) const { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case UnsignedShort: return getShortAlign(); case SignedInt: case UnsignedInt: return getIntAlign(); case SignedLong: case UnsignedLong: return getLongAlign(); case SignedLongLong: case UnsignedLongLong: return getLongLongAlign(); }; } /// isTypeSigned - Return whether an integer types is signed. Returns true if /// the type is signed; false otherwise. bool TargetInfo::isTypeSigned(IntType T) const { switch (T) { default: assert(0 && "not an integer!"); case SignedShort: case SignedInt: case SignedLong: case SignedLongLong: return true; case UnsignedShort: case UnsignedInt: case UnsignedLong: case UnsignedLongLong: return false; }; } /// setForcedLangOptions - Set forced language options. /// Apply changes to the target information with respect to certain /// language options which change the target configuration. void TargetInfo::setForcedLangOptions(LangOptions &Opts) { if (Opts.NoBitFieldTypeAlign) UseBitFieldTypeAlignment = false; if (Opts.ShortWChar) WCharType = UnsignedShort; } //===----------------------------------------------------------------------===// static llvm::StringRef removeGCCRegisterPrefix(llvm::StringRef Name) { if (Name[0] == '%' || Name[0] == '#') Name = Name.substr(1); return Name; } /// isValidGCCRegisterName - Returns whether the passed in string /// is a valid register name according to GCC. This is used by Sema for /// inline asm statements. bool TargetInfo::isValidGCCRegisterName(llvm::StringRef Name) const { if (Name.empty()) return false; const char * const *Names; unsigned NumNames; // Get rid of any register prefix. Name = removeGCCRegisterPrefix(Name); if (Name == "memory" || Name == "cc") return true; getGCCRegNames(Names, NumNames); // If we have a number it maps to an entry in the register name array. if (isdigit(Name[0])) { int n; if (!Name.getAsInteger(0, n)) return n >= 0 && (unsigned)n < NumNames; } // Check register names. for (unsigned i = 0; i < NumNames; i++) { if (Name == Names[i]) return true; } // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { if (!Aliases[i].Aliases[j]) break; if (Aliases[i].Aliases[j] == Name) return true; } } return false; } llvm::StringRef TargetInfo::getNormalizedGCCRegisterName(llvm::StringRef Name) const { assert(isValidGCCRegisterName(Name) && "Invalid register passed in"); // Get rid of any register prefix. Name = removeGCCRegisterPrefix(Name); const char * const *Names; unsigned NumNames; getGCCRegNames(Names, NumNames); // First, check if we have a number. if (isdigit(Name[0])) { int n; if (!Name.getAsInteger(0, n)) { assert(n >= 0 && (unsigned)n < NumNames && "Out of bounds register number!"); return Names[n]; } } // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { if (!Aliases[i].Aliases[j]) break; if (Aliases[i].Aliases[j] == Name) return Aliases[i].Register; } } return Name; } bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const { const char *Name = Info.getConstraintStr().c_str(); // An output constraint must start with '=' or '+' if (*Name != '=' && *Name != '+') return false; if (*Name == '+') Info.setIsReadWrite(); Name++; while (*Name) { switch (*Name) { default: if (!validateAsmConstraint(Name, Info)) { // FIXME: We temporarily return false // so we can add more constraints as we hit it. // Eventually, an unknown constraint should just be treated as 'g'. return false; } case '&': // early clobber. break; case '%': // commutative. // FIXME: Check that there is a another register after this one. break; case 'r': // general register. Info.setAllowsRegister(); break; case 'm': // memory operand. Info.setAllowsMemory(); break; case 'g': // general register, memory operand or immediate integer. case 'X': // any operand. Info.setAllowsRegister(); Info.setAllowsMemory(); break; case ',': // multiple alternative constraint. Pass it. Name++; // Handle additional optional '=' or '+' modifiers. if (*Name == '=' || *Name == '+') Name++; break; case '?': // Disparage slightly code. case '!': // Disparage severly. break; // Pass them. } Name++; } return true; } bool TargetInfo::resolveSymbolicName(const char *&Name, ConstraintInfo *OutputConstraints, unsigned NumOutputs, unsigned &Index) const { assert(*Name == '[' && "Symbolic name did not start with '['"); Name++; const char *Start = Name; while (*Name && *Name != ']') Name++; if (!*Name) { // Missing ']' return false; } std::string SymbolicName(Start, Name - Start); for (Index = 0; Index != NumOutputs; ++Index) if (SymbolicName == OutputConstraints[Index].getName()) return true; return false; } bool TargetInfo::validateInputConstraint(ConstraintInfo *OutputConstraints, unsigned NumOutputs, ConstraintInfo &Info) const { const char *Name = Info.ConstraintStr.c_str(); while (*Name) { switch (*Name) { default: // Check if we have a matching constraint if (*Name >= '0' && *Name <= '9') { unsigned i = *Name - '0'; // Check if matching constraint is out of bounds. if (i >= NumOutputs) return false; // The constraint should have the same info as the respective // output constraint. Info.setTiedOperand(i, OutputConstraints[i]); } else if (!validateAsmConstraint(Name, Info)) { // FIXME: This error return is in place temporarily so we can // add more constraints as we hit it. Eventually, an unknown // constraint should just be treated as 'g'. return false; } break; case '[': { unsigned Index = 0; if (!resolveSymbolicName(Name, OutputConstraints, NumOutputs, Index)) return false; Info.setTiedOperand(Index, OutputConstraints[Index]); break; } case '%': // commutative // FIXME: Fail if % is used with the last operand. break; case 'i': // immediate integer. case 'n': // immediate integer with a known value. break; case 'I': // Various constant constraints with target-specific meanings. case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': break; case 'r': // general register. Info.setAllowsRegister(); break; case 'm': // memory operand. case 'o': // offsettable memory operand case 'V': // non-offsettable memory operand Info.setAllowsMemory(); break; case 'g': // general register, memory operand or immediate integer. case 'X': // any operand. Info.setAllowsRegister(); Info.setAllowsMemory(); break; case ',': // multiple alternative constraint. Ignore comma. break; case '?': // Disparage slightly code. case '!': // Disparage severly. break; // Pass them. } Name++; } return true; }
Fix oversight with symbolic names in TargetInfo::validateInputConstraint.
Fix oversight with symbolic names in TargetInfo::validateInputConstraint. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@110870 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang
dfaa35e22de1ce133083202c3b2c77edbe70c3bc
src/istream/istream_chunked.cxx
src/istream/istream_chunked.cxx
/* * This istream filter adds HTTP chunking. * * author: Max Kellermann <[email protected]> */ #include "istream_chunked.hxx" #include "istream_internal.hxx" #include "pool.hxx" #include "format.h" #include "util/Cast.hxx" #include <assert.h> #include <string.h> struct istream_chunked { struct istream output; struct istream *input; /** * This flag is true while writing the buffer inside * istream_chunked_read(). chunked_input_data() will check it, * and refuse to accept more data from the input. This avoids * writing the buffer recursively. */ bool writing_buffer; char buffer[7]; size_t buffer_sent; size_t missing_from_current_chunk; }; static inline int chunked_buffer_empty(const struct istream_chunked *chunked) { assert(chunked->buffer_sent <= sizeof(chunked->buffer)); return chunked->buffer_sent == sizeof(chunked->buffer); } /** set the buffer length and return a pointer to the first byte */ static inline char * chunked_buffer_set(struct istream_chunked *chunked, size_t length) { assert(chunked_buffer_empty(chunked)); assert(length <= sizeof(chunked->buffer)); chunked->buffer_sent = sizeof(chunked->buffer) - length; return chunked->buffer + chunked->buffer_sent; } /** append data to the buffer */ static void chunked_buffer_append(struct istream_chunked *chunked, const void *data, size_t length) { assert(data != nullptr); assert(length > 0); assert(length <= chunked->buffer_sent); const void *old = chunked->buffer + chunked->buffer_sent; size_t old_length = sizeof(chunked->buffer) - chunked->buffer_sent; #ifndef NDEBUG /* simulate a buffer reset; if we don't do this, an assertion in chunked_buffer_set() fails (which is invalid for this special case) */ chunked->buffer_sent = sizeof(chunked->buffer); #endif auto dest = chunked_buffer_set(chunked, old_length + length); memmove(dest, old, old_length); dest += old_length; memcpy(dest, data, length); } static void chunked_start_chunk(struct istream_chunked *chunked, size_t length) { assert(length > 0); assert(chunked_buffer_empty(chunked)); assert(chunked->missing_from_current_chunk == 0); if (length > 0x8000) /* maximum chunk size is 32kB for now */ length = 0x8000; chunked->missing_from_current_chunk = length; auto buffer = chunked_buffer_set(chunked, 6); format_uint16_hex_fixed(buffer, (uint16_t)length); buffer[4] = '\r'; buffer[5] = '\n'; } /** * Returns true if the buffer is consumed. */ static bool chunked_write_buffer(struct istream_chunked *chunked) { size_t length = sizeof(chunked->buffer) - chunked->buffer_sent; if (length == 0) return true; size_t nbytes = istream_invoke_data(&chunked->output, chunked->buffer + chunked->buffer_sent, length); if (nbytes > 0) chunked->buffer_sent += nbytes; return nbytes == length; } /** * Wrapper for chunked_write_buffer() that sets and clears the * writing_buffer flag. This requires acquiring a pool reference to * do that safely. * * @return true if the buffer is consumed. */ static bool chunked_write_buffer2(struct istream_chunked *chunked) { const ScopePoolRef ref(*chunked->output.pool TRACE_ARGS); assert(!chunked->writing_buffer); chunked->writing_buffer = true; const bool result = chunked_write_buffer(chunked); chunked->writing_buffer = false; return result; } static size_t chunked_feed(struct istream_chunked *chunked, const char *data, size_t length) { size_t total = 0, rest, nbytes; assert(chunked->input != nullptr); do { assert(!chunked->writing_buffer); if (chunked_buffer_empty(chunked) && chunked->missing_from_current_chunk == 0) chunked_start_chunk(chunked, length - total); if (!chunked_write_buffer(chunked)) return chunked->input == nullptr ? 0 : total; assert(chunked_buffer_empty(chunked)); if (chunked->missing_from_current_chunk == 0) { /* we have just written the previous chunk trailer; re-start this loop to start a new chunk */ nbytes = rest = 0; continue; } rest = length - total; if (rest > chunked->missing_from_current_chunk) rest = chunked->missing_from_current_chunk; nbytes = istream_invoke_data(&chunked->output, data + total, rest); if (nbytes == 0) return chunked->input == nullptr ? 0 : total; total += nbytes; chunked->missing_from_current_chunk -= nbytes; if (chunked->missing_from_current_chunk == 0) { /* a chunk ends with "\r\n" */ char *buffer = chunked_buffer_set(chunked, 2); buffer[0] = '\r'; buffer[1] = '\n'; } } while ((!chunked_buffer_empty(chunked) || total < length) && nbytes == rest); return total; } /* * istream handler * */ static size_t chunked_input_data(const void *data, size_t length, void *ctx) { auto *chunked = (struct istream_chunked *)ctx; if (chunked->writing_buffer) /* this is a recursive call from istream_chunked_read(): bail out */ return 0; const ScopePoolRef ref(*chunked->output.pool TRACE_ARGS); return chunked_feed(chunked, (const char*)data, length); } static void chunked_input_eof(void *ctx) { auto *chunked = (struct istream_chunked *)ctx; assert(chunked->input != nullptr); assert(chunked->missing_from_current_chunk == 0); chunked->input = nullptr; /* write EOF chunk (length 0) */ chunked_buffer_append(chunked, "0\r\n\r\n", 5); /* flush the buffer */ if (chunked_write_buffer(chunked)) istream_deinit_eof(&chunked->output); } static void chunked_input_abort(GError *error, void *ctx) { auto *chunked = (struct istream_chunked *)ctx; assert(chunked->input != nullptr); chunked->input = nullptr; istream_deinit_abort(&chunked->output, error); } static constexpr struct istream_handler chunked_input_handler = { .data = chunked_input_data, .eof = chunked_input_eof, .abort = chunked_input_abort, }; /* * istream implementation * */ static inline struct istream_chunked * istream_to_chunked(struct istream *istream) { return &ContainerCast2(*istream, &istream_chunked::output); } static void istream_chunked_read(struct istream *istream) { struct istream_chunked *chunked = istream_to_chunked(istream); if (!chunked_write_buffer2(chunked)) return; if (chunked->input == nullptr) { istream_deinit_eof(&chunked->output); return; } assert(chunked->input != nullptr); if (chunked_buffer_empty(chunked) && chunked->missing_from_current_chunk == 0) { off_t available = istream_available(chunked->input, true); if (available > 0) { chunked_start_chunk(chunked, available); if (!chunked_write_buffer2(chunked)) return; } } istream_read(chunked->input); } static void istream_chunked_close(struct istream *istream) { struct istream_chunked *chunked = istream_to_chunked(istream); if (chunked->input != nullptr) istream_free_handler(&chunked->input); istream_deinit(&chunked->output); } static constexpr struct istream_class istream_chunked = { .read = istream_chunked_read, .close = istream_chunked_close, }; /* * constructor * */ struct istream * istream_chunked_new(struct pool *pool, struct istream *input) { struct istream_chunked *chunked = istream_new_macro(pool, chunked); assert(input != nullptr); assert(!istream_has_handler(input)); chunked->writing_buffer = false; chunked->buffer_sent = sizeof(chunked->buffer); chunked->missing_from_current_chunk = 0; istream_assign_handler(&chunked->input, input, &chunked_input_handler, chunked, 0); return &chunked->output; }
/* * This istream filter adds HTTP chunking. * * author: Max Kellermann <[email protected]> */ #include "istream_chunked.hxx" #include "istream_internal.hxx" #include "pool.hxx" #include "format.h" #include "util/Cast.hxx" #include <assert.h> #include <string.h> struct istream_chunked { struct istream output; struct istream *input; /** * This flag is true while writing the buffer inside * istream_chunked_read(). chunked_input_data() will check it, * and refuse to accept more data from the input. This avoids * writing the buffer recursively. */ bool writing_buffer; char buffer[7]; size_t buffer_sent; size_t missing_from_current_chunk; }; static inline int chunked_buffer_empty(const struct istream_chunked *chunked) { assert(chunked->buffer_sent <= sizeof(chunked->buffer)); return chunked->buffer_sent == sizeof(chunked->buffer); } /** set the buffer length and return a pointer to the first byte */ static inline char * chunked_buffer_set(struct istream_chunked *chunked, size_t length) { assert(chunked_buffer_empty(chunked)); assert(length <= sizeof(chunked->buffer)); chunked->buffer_sent = sizeof(chunked->buffer) - length; return chunked->buffer + chunked->buffer_sent; } /** append data to the buffer */ static void chunked_buffer_append(struct istream_chunked *chunked, const void *data, size_t length) { assert(data != nullptr); assert(length > 0); assert(length <= chunked->buffer_sent); const void *old = chunked->buffer + chunked->buffer_sent; size_t old_length = sizeof(chunked->buffer) - chunked->buffer_sent; #ifndef NDEBUG /* simulate a buffer reset; if we don't do this, an assertion in chunked_buffer_set() fails (which is invalid for this special case) */ chunked->buffer_sent = sizeof(chunked->buffer); #endif auto dest = chunked_buffer_set(chunked, old_length + length); memmove(dest, old, old_length); dest += old_length; memcpy(dest, data, length); } static void chunked_start_chunk(struct istream_chunked *chunked, size_t length) { assert(length > 0); assert(chunked_buffer_empty(chunked)); assert(chunked->missing_from_current_chunk == 0); if (length > 0x8000) /* maximum chunk size is 32kB for now */ length = 0x8000; chunked->missing_from_current_chunk = length; auto buffer = chunked_buffer_set(chunked, 6); format_uint16_hex_fixed(buffer, (uint16_t)length); buffer[4] = '\r'; buffer[5] = '\n'; } /** * Returns true if the buffer is consumed. */ static bool chunked_write_buffer(struct istream_chunked *chunked) { size_t length = sizeof(chunked->buffer) - chunked->buffer_sent; if (length == 0) return true; size_t nbytes = istream_invoke_data(&chunked->output, chunked->buffer + chunked->buffer_sent, length); if (nbytes > 0) chunked->buffer_sent += nbytes; return nbytes == length; } /** * Wrapper for chunked_write_buffer() that sets and clears the * writing_buffer flag. This requires acquiring a pool reference to * do that safely. * * @return true if the buffer is consumed. */ static bool chunked_write_buffer2(struct istream_chunked *chunked) { const ScopePoolRef ref(*chunked->output.pool TRACE_ARGS); assert(!chunked->writing_buffer); chunked->writing_buffer = true; const bool result = chunked_write_buffer(chunked); chunked->writing_buffer = false; return result; } static size_t chunked_feed(struct istream_chunked *chunked, const char *data, size_t length) { size_t total = 0, rest, nbytes; assert(chunked->input != nullptr); do { assert(!chunked->writing_buffer); if (chunked_buffer_empty(chunked) && chunked->missing_from_current_chunk == 0) chunked_start_chunk(chunked, length - total); if (!chunked_write_buffer(chunked)) return chunked->input == nullptr ? 0 : total; assert(chunked_buffer_empty(chunked)); if (chunked->missing_from_current_chunk == 0) { /* we have just written the previous chunk trailer; re-start this loop to start a new chunk */ nbytes = rest = 0; continue; } rest = length - total; if (rest > chunked->missing_from_current_chunk) rest = chunked->missing_from_current_chunk; nbytes = istream_invoke_data(&chunked->output, data + total, rest); if (nbytes == 0) return chunked->input == nullptr ? 0 : total; total += nbytes; chunked->missing_from_current_chunk -= nbytes; if (chunked->missing_from_current_chunk == 0) { /* a chunk ends with "\r\n" */ char *buffer = chunked_buffer_set(chunked, 2); buffer[0] = '\r'; buffer[1] = '\n'; } } while ((!chunked_buffer_empty(chunked) || total < length) && nbytes == rest); return total; } /* * istream handler * */ static size_t chunked_input_data(const void *data, size_t length, void *ctx) { auto *chunked = (struct istream_chunked *)ctx; if (chunked->writing_buffer) /* this is a recursive call from istream_chunked_read(): bail out */ return 0; const ScopePoolRef ref(*chunked->output.pool TRACE_ARGS); return chunked_feed(chunked, (const char*)data, length); } static void chunked_input_eof(void *ctx) { auto *chunked = (struct istream_chunked *)ctx; assert(chunked->input != nullptr); assert(chunked->missing_from_current_chunk == 0); chunked->input = nullptr; /* write EOF chunk (length 0) */ chunked_buffer_append(chunked, "0\r\n\r\n", 5); /* flush the buffer */ if (chunked_write_buffer(chunked)) istream_deinit_eof(&chunked->output); } static void chunked_input_abort(GError *error, void *ctx) { auto *chunked = (struct istream_chunked *)ctx; assert(chunked->input != nullptr); chunked->input = nullptr; istream_deinit_abort(&chunked->output, error); } static constexpr struct istream_handler chunked_input_handler = { .data = chunked_input_data, .eof = chunked_input_eof, .abort = chunked_input_abort, }; /* * istream implementation * */ static inline struct istream_chunked * istream_to_chunked(struct istream *istream) { return &ContainerCast2(*istream, &istream_chunked::output); } static void istream_chunked_read(struct istream *istream) { struct istream_chunked *chunked = istream_to_chunked(istream); if (!chunked_write_buffer2(chunked)) return; if (chunked->input == nullptr) { istream_deinit_eof(&chunked->output); return; } assert(chunked->input != nullptr); if (chunked_buffer_empty(chunked) && chunked->missing_from_current_chunk == 0) { off_t available = istream_available(chunked->input, true); if (available > 0) { chunked_start_chunk(chunked, available); if (!chunked_write_buffer2(chunked)) return; } } istream_read(chunked->input); } static void istream_chunked_close(struct istream *istream) { struct istream_chunked *chunked = istream_to_chunked(istream); if (chunked->input != nullptr) istream_free_handler(&chunked->input); istream_deinit(&chunked->output); } static constexpr struct istream_class istream_chunked = { .read = istream_chunked_read, .close = istream_chunked_close, }; /* * constructor * */ struct istream * istream_chunked_new(struct pool *pool, struct istream *input) { assert(input != nullptr); assert(!istream_has_handler(input)); auto *chunked = NewFromPool<struct istream_chunked>(*pool); istream_init(&chunked->output, &istream_chunked, pool); chunked->writing_buffer = false; chunked->buffer_sent = sizeof(chunked->buffer); chunked->missing_from_current_chunk = 0; istream_assign_handler(&chunked->input, input, &chunked_input_handler, chunked, 0); return &chunked->output; }
use NewFromPool()
istream/chunked: use NewFromPool()
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
1767849f3d5f756c8e419549fd752161d59b358d
lib/Core/SymbolTable.cpp
lib/Core/SymbolTable.cpp
//===- Core/SymbolTable.cpp - Main Symbol Table ---------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/SymbolTable.h" #include "lld/Core/AbsoluteAtom.h" #include "lld/Core/Atom.h" #include "lld/Core/DefinedAtom.h" #include "lld/Core/File.h" #include "lld/Core/LLVM.h" #include "lld/Core/Resolver.h" #include "lld/Core/SharedLibraryAtom.h" #include "lld/Core/LinkingContext.h" #include "lld/Core/UndefinedAtom.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/Hashing.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstdlib> #include <vector> namespace lld { SymbolTable::SymbolTable(const LinkingContext &context) : _context(context) {} void SymbolTable::add(const UndefinedAtom &atom) { addByName(atom); } void SymbolTable::add(const SharedLibraryAtom &atom) { addByName(atom); } void SymbolTable::add(const AbsoluteAtom &atom) { addByName(atom); } void SymbolTable::add(const DefinedAtom &atom) { if (!atom.name().empty() && atom.scope() != DefinedAtom::scopeTranslationUnit) { // Named atoms cannot be merged by content. assert(atom.merge() != DefinedAtom::mergeByContent); // Track named atoms that are not scoped to file (static). addByName(atom); return; } if (atom.merge() == DefinedAtom::mergeByContent) { // Named atoms cannot be merged by content. assert(atom.name().empty()); addByContent(atom); } } const Atom *SymbolTable::findGroup(StringRef sym) { NameToAtom::iterator pos = _groupTable.find(sym); if (pos == _groupTable.end()) return nullptr; return pos->second; } bool SymbolTable::addGroup(const DefinedAtom &da) { StringRef name = da.name(); assert(!name.empty()); const Atom *existing = findGroup(name); if (existing == nullptr) { _groupTable[name] = &da; return true; } _replacedAtoms[&da] = existing; return false; } enum NameCollisionResolution { NCR_First, NCR_Second, NCR_DupDef, NCR_DupUndef, NCR_DupShLib, NCR_Error }; static NameCollisionResolution cases[4][4] = { //regular absolute undef sharedLib { // first is regular NCR_DupDef, NCR_Error, NCR_First, NCR_First }, { // first is absolute NCR_Error, NCR_Error, NCR_First, NCR_First }, { // first is undef NCR_Second, NCR_Second, NCR_DupUndef, NCR_Second }, { // first is sharedLib NCR_Second, NCR_Second, NCR_First, NCR_DupShLib } }; static NameCollisionResolution collide(Atom::Definition first, Atom::Definition second) { return cases[first][second]; } enum MergeResolution { MCR_First, MCR_Second, MCR_Largest, MCR_SameSize, MCR_Error }; static MergeResolution mergeCases[][6] = { // no tentative weak weakAddress sameNameAndSize largest {MCR_Error, MCR_First, MCR_First, MCR_First, MCR_SameSize, MCR_Largest}, // no {MCR_Second, MCR_Largest, MCR_Second, MCR_Second, MCR_SameSize, MCR_Largest}, // tentative {MCR_Second, MCR_First, MCR_First, MCR_Second, MCR_SameSize, MCR_Largest}, // weak {MCR_Second, MCR_First, MCR_First, MCR_First, MCR_SameSize, MCR_Largest}, // weakAddress {MCR_SameSize, MCR_SameSize, MCR_SameSize, MCR_SameSize, MCR_SameSize, MCR_SameSize}, // sameSize {MCR_Largest, MCR_Largest, MCR_Largest, MCR_Largest, MCR_SameSize, MCR_Largest}, // largest }; static MergeResolution mergeSelect(DefinedAtom::Merge first, DefinedAtom::Merge second) { assert(first != DefinedAtom::mergeByContent); assert(second != DefinedAtom::mergeByContent); return mergeCases[first][second]; } static uint64_t getSizeFollowReferences(const DefinedAtom *atom, uint32_t kind) { uint64_t size = 0; redo: while (atom) { for (const Reference *r : *atom) { if (r->kindNamespace() == Reference::KindNamespace::all && r->kindArch() == Reference::KindArch::all && r->kindValue() == kind) { atom = cast<DefinedAtom>(r->target()); size += atom->size(); goto redo; } } break; } return size; } // Returns the size of the section containing the given atom. Atoms in the same // section are connected by layout-before and layout-after edges, so this // function traverses them to get the total size of atoms in the same section. static uint64_t sectionSize(const DefinedAtom *atom) { return atom->size() + getSizeFollowReferences(atom, lld::Reference::kindLayoutBefore) + getSizeFollowReferences(atom, lld::Reference::kindLayoutAfter); } void SymbolTable::addByName(const Atom &newAtom) { StringRef name = newAtom.name(); assert(!name.empty()); const Atom *existing = findByName(name); if (existing == nullptr) { // Name is not in symbol table yet, add it associate with this atom. _nameTable[name] = &newAtom; return; } // Name is already in symbol table and associated with another atom. bool useNew = true; switch (collide(existing->definition(), newAtom.definition())) { case NCR_First: useNew = false; break; case NCR_Second: useNew = true; break; case NCR_DupDef: assert(existing->definition() == Atom::definitionRegular); assert(newAtom.definition() == Atom::definitionRegular); switch (mergeSelect(((DefinedAtom*)existing)->merge(), ((DefinedAtom*)&newAtom)->merge())) { case MCR_First: useNew = false; break; case MCR_Second: useNew = true; break; case MCR_Largest: { uint64_t existingSize = sectionSize((DefinedAtom*)existing); uint64_t newSize = sectionSize((DefinedAtom*)&newAtom); useNew = (newSize >= existingSize); break; } case MCR_SameSize: { uint64_t existingSize = sectionSize((DefinedAtom*)existing); uint64_t newSize = sectionSize((DefinedAtom*)&newAtom); if (existingSize == newSize) { useNew = true; break; } llvm::errs() << "Size mismatch: " << existing->name() << " (" << existingSize << ") " << newAtom.name() << " (" << newSize << ")\n"; // fallthrough } case MCR_Error: if (!_context.getAllowDuplicates()) { llvm::errs() << "Duplicate symbols: " << existing->name() << ":" << existing->file().path() << " and " << newAtom.name() << ":" << newAtom.file().path() << "\n"; llvm::report_fatal_error("duplicate symbol error"); } useNew = false; break; } break; case NCR_DupUndef: { const UndefinedAtom* existingUndef = cast<UndefinedAtom>(existing); const UndefinedAtom* newUndef = cast<UndefinedAtom>(&newAtom); bool sameCanBeNull = (existingUndef->canBeNull() == newUndef->canBeNull()); if (!sameCanBeNull && _context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) { llvm::errs() << "lld warning: undefined symbol " << existingUndef->name() << " has different weakness in " << existingUndef->file().path() << " and in " << newUndef->file().path() << "\n"; } const UndefinedAtom *existingFallback = existingUndef->fallback(); const UndefinedAtom *newFallback = newUndef->fallback(); bool hasDifferentFallback = (existingFallback && newFallback && existingFallback->name() != newFallback->name()); if (hasDifferentFallback) { llvm::errs() << "lld warning: undefined symbol " << existingUndef->name() << " has different fallback: " << existingFallback->name() << " in " << existingUndef->file().path() << " and " << newFallback->name() << " in " << newUndef->file().path() << "\n"; } bool hasNewFallback = newUndef->fallback(); if (sameCanBeNull) useNew = hasNewFallback; else useNew = (newUndef->canBeNull() < existingUndef->canBeNull()); break; } case NCR_DupShLib: { const SharedLibraryAtom *curShLib = cast<SharedLibraryAtom>(existing); const SharedLibraryAtom *newShLib = cast<SharedLibraryAtom>(&newAtom); bool sameNullness = (curShLib->canBeNullAtRuntime() == newShLib->canBeNullAtRuntime()); bool sameName = curShLib->loadName().equals(newShLib->loadName()); if (sameName && !sameNullness && _context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) { // FIXME: need diagonstics interface for writing warning messages llvm::errs() << "lld warning: shared library symbol " << curShLib->name() << " has different weakness in " << curShLib->file().path() << " and in " << newShLib->file().path(); } if (!sameName && _context.warnIfCoalesableAtomsHaveDifferentLoadName()) { // FIXME: need diagonstics interface for writing warning messages llvm::errs() << "lld warning: shared library symbol " << curShLib->name() << " has different load path in " << curShLib->file().path() << " and in " << newShLib->file().path(); } useNew = false; break; } case NCR_Error: llvm::errs() << "SymbolTable: error while merging " << name << "\n"; llvm::report_fatal_error("duplicate symbol error"); break; } if (useNew) { // Update name table to use new atom. _nameTable[name] = &newAtom; // Add existing atom to replacement table. _replacedAtoms[existing] = &newAtom; } else { // New atom is not being used. Add it to replacement table. _replacedAtoms[&newAtom] = existing; } } unsigned SymbolTable::AtomMappingInfo::getHashValue(const DefinedAtom *atom) { auto content = atom->rawContent(); return llvm::hash_combine(atom->size(), atom->contentType(), llvm::hash_combine_range(content.begin(), content.end())); } bool SymbolTable::AtomMappingInfo::isEqual(const DefinedAtom * const l, const DefinedAtom * const r) { if (l == r) return true; if (l == getEmptyKey()) return false; if (r == getEmptyKey()) return false; if (l == getTombstoneKey()) return false; if (r == getTombstoneKey()) return false; if (l->contentType() != r->contentType()) return false; if (l->size() != r->size()) return false; ArrayRef<uint8_t> lc = l->rawContent(); ArrayRef<uint8_t> rc = r->rawContent(); return memcmp(lc.data(), rc.data(), lc.size()) == 0; } void SymbolTable::addByContent(const DefinedAtom & newAtom) { // Currently only read-only constants can be merged. assert(newAtom.permissions() == DefinedAtom::permR__); AtomContentSet::iterator pos = _contentTable.find(&newAtom); if (pos == _contentTable.end()) { _contentTable.insert(&newAtom); return; } const Atom* existing = *pos; // New atom is not being used. Add it to replacement table. _replacedAtoms[&newAtom] = existing; } const Atom *SymbolTable::findByName(StringRef sym) { NameToAtom::iterator pos = _nameTable.find(sym); if (pos == _nameTable.end()) return nullptr; return pos->second; } bool SymbolTable::isDefined(StringRef sym) { if (const Atom *atom = findByName(sym)) return atom->definition() != Atom::definitionUndefined; return false; } void SymbolTable::addReplacement(const Atom *replaced, const Atom *replacement) { _replacedAtoms[replaced] = replacement; } const Atom *SymbolTable::replacement(const Atom *atom) { // Find the replacement for a given atom. Atoms in _replacedAtoms // may be chained, so find the last one. for (;;) { AtomToAtom::iterator pos = _replacedAtoms.find(atom); if (pos == _replacedAtoms.end()) return atom; atom = pos->second; } } unsigned int SymbolTable::size() { return _nameTable.size(); } std::vector<const UndefinedAtom *> SymbolTable::undefines() { std::vector<const UndefinedAtom *> ret; for (auto it : _nameTable) { const Atom *atom = it.second; assert(atom != nullptr); if (const auto undef = dyn_cast<const UndefinedAtom>(atom)) { AtomToAtom::iterator pos = _replacedAtoms.find(undef); if (pos != _replacedAtoms.end()) continue; ret.push_back(undef); } } return ret; } std::vector<StringRef> SymbolTable::tentativeDefinitions() { std::vector<StringRef> ret; for (auto entry : _nameTable) { const Atom *atom = entry.second; StringRef name = entry.first; assert(atom != nullptr); if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom)) if (defAtom->merge() == DefinedAtom::mergeAsTentative) ret.push_back(name); } return ret; } } // namespace lld
//===- Core/SymbolTable.cpp - Main Symbol Table ---------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/SymbolTable.h" #include "lld/Core/AbsoluteAtom.h" #include "lld/Core/Atom.h" #include "lld/Core/DefinedAtom.h" #include "lld/Core/File.h" #include "lld/Core/LLVM.h" #include "lld/Core/Resolver.h" #include "lld/Core/SharedLibraryAtom.h" #include "lld/Core/LinkingContext.h" #include "lld/Core/UndefinedAtom.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/Hashing.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstdlib> #include <vector> namespace lld { SymbolTable::SymbolTable(const LinkingContext &context) : _context(context) {} void SymbolTable::add(const UndefinedAtom &atom) { addByName(atom); } void SymbolTable::add(const SharedLibraryAtom &atom) { addByName(atom); } void SymbolTable::add(const AbsoluteAtom &atom) { addByName(atom); } void SymbolTable::add(const DefinedAtom &atom) { if (!atom.name().empty() && atom.scope() != DefinedAtom::scopeTranslationUnit) { // Named atoms cannot be merged by content. assert(atom.merge() != DefinedAtom::mergeByContent); // Track named atoms that are not scoped to file (static). addByName(atom); return; } if (atom.merge() == DefinedAtom::mergeByContent) { // Named atoms cannot be merged by content. assert(atom.name().empty()); addByContent(atom); } } const Atom *SymbolTable::findGroup(StringRef sym) { NameToAtom::iterator pos = _groupTable.find(sym); if (pos == _groupTable.end()) return nullptr; return pos->second; } bool SymbolTable::addGroup(const DefinedAtom &da) { StringRef name = da.name(); assert(!name.empty()); const Atom *existing = findGroup(name); if (existing == nullptr) { _groupTable[name] = &da; return true; } _replacedAtoms[&da] = existing; return false; } enum NameCollisionResolution { NCR_First, NCR_Second, NCR_DupDef, NCR_DupUndef, NCR_DupShLib, NCR_Error }; static NameCollisionResolution cases[4][4] = { //regular absolute undef sharedLib { // first is regular NCR_DupDef, NCR_Error, NCR_First, NCR_First }, { // first is absolute NCR_Error, NCR_Error, NCR_First, NCR_First }, { // first is undef NCR_Second, NCR_Second, NCR_DupUndef, NCR_Second }, { // first is sharedLib NCR_Second, NCR_Second, NCR_First, NCR_DupShLib } }; static NameCollisionResolution collide(Atom::Definition first, Atom::Definition second) { return cases[first][second]; } enum MergeResolution { MCR_First, MCR_Second, MCR_Largest, MCR_SameSize, MCR_Error }; static MergeResolution mergeCases[][6] = { // no tentative weak weakAddress sameNameAndSize largest {MCR_Error, MCR_First, MCR_First, MCR_First, MCR_SameSize, MCR_Largest}, // no {MCR_Second, MCR_Largest, MCR_Second, MCR_Second, MCR_SameSize, MCR_Largest}, // tentative {MCR_Second, MCR_First, MCR_First, MCR_Second, MCR_SameSize, MCR_Largest}, // weak {MCR_Second, MCR_First, MCR_First, MCR_First, MCR_SameSize, MCR_Largest}, // weakAddress {MCR_SameSize, MCR_SameSize, MCR_SameSize, MCR_SameSize, MCR_SameSize, MCR_SameSize}, // sameSize {MCR_Largest, MCR_Largest, MCR_Largest, MCR_Largest, MCR_SameSize, MCR_Largest}, // largest }; static MergeResolution mergeSelect(DefinedAtom::Merge first, DefinedAtom::Merge second) { assert(first != DefinedAtom::mergeByContent); assert(second != DefinedAtom::mergeByContent); return mergeCases[first][second]; } static const DefinedAtom *followReference(const DefinedAtom *atom, uint32_t kind) { for (const Reference *r : *atom) if (r->kindNamespace() == Reference::KindNamespace::all && r->kindArch() == Reference::KindArch::all && r->kindValue() == kind) return cast<const DefinedAtom>(r->target()); return nullptr; } static uint64_t getSizeFollowReferences(const DefinedAtom *atom, uint32_t kind) { uint64_t size = 0; for (;;) { atom = followReference(atom, kind); if (!atom) return size; size += atom->size(); } } // Returns the size of the section containing the given atom. Atoms in the same // section are connected by layout-before and layout-after edges, so this // function traverses them to get the total size of atoms in the same section. static uint64_t sectionSize(const DefinedAtom *atom) { return atom->size() + getSizeFollowReferences(atom, lld::Reference::kindLayoutBefore) + getSizeFollowReferences(atom, lld::Reference::kindLayoutAfter); } void SymbolTable::addByName(const Atom &newAtom) { StringRef name = newAtom.name(); assert(!name.empty()); const Atom *existing = findByName(name); if (existing == nullptr) { // Name is not in symbol table yet, add it associate with this atom. _nameTable[name] = &newAtom; return; } // Name is already in symbol table and associated with another atom. bool useNew = true; switch (collide(existing->definition(), newAtom.definition())) { case NCR_First: useNew = false; break; case NCR_Second: useNew = true; break; case NCR_DupDef: assert(existing->definition() == Atom::definitionRegular); assert(newAtom.definition() == Atom::definitionRegular); switch (mergeSelect(((DefinedAtom*)existing)->merge(), ((DefinedAtom*)&newAtom)->merge())) { case MCR_First: useNew = false; break; case MCR_Second: useNew = true; break; case MCR_Largest: { uint64_t existingSize = sectionSize((DefinedAtom*)existing); uint64_t newSize = sectionSize((DefinedAtom*)&newAtom); useNew = (newSize >= existingSize); break; } case MCR_SameSize: { uint64_t existingSize = sectionSize((DefinedAtom*)existing); uint64_t newSize = sectionSize((DefinedAtom*)&newAtom); if (existingSize == newSize) { useNew = true; break; } llvm::errs() << "Size mismatch: " << existing->name() << " (" << existingSize << ") " << newAtom.name() << " (" << newSize << ")\n"; // fallthrough } case MCR_Error: if (!_context.getAllowDuplicates()) { llvm::errs() << "Duplicate symbols: " << existing->name() << ":" << existing->file().path() << " and " << newAtom.name() << ":" << newAtom.file().path() << "\n"; llvm::report_fatal_error("duplicate symbol error"); } useNew = false; break; } break; case NCR_DupUndef: { const UndefinedAtom* existingUndef = cast<UndefinedAtom>(existing); const UndefinedAtom* newUndef = cast<UndefinedAtom>(&newAtom); bool sameCanBeNull = (existingUndef->canBeNull() == newUndef->canBeNull()); if (!sameCanBeNull && _context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) { llvm::errs() << "lld warning: undefined symbol " << existingUndef->name() << " has different weakness in " << existingUndef->file().path() << " and in " << newUndef->file().path() << "\n"; } const UndefinedAtom *existingFallback = existingUndef->fallback(); const UndefinedAtom *newFallback = newUndef->fallback(); bool hasDifferentFallback = (existingFallback && newFallback && existingFallback->name() != newFallback->name()); if (hasDifferentFallback) { llvm::errs() << "lld warning: undefined symbol " << existingUndef->name() << " has different fallback: " << existingFallback->name() << " in " << existingUndef->file().path() << " and " << newFallback->name() << " in " << newUndef->file().path() << "\n"; } bool hasNewFallback = newUndef->fallback(); if (sameCanBeNull) useNew = hasNewFallback; else useNew = (newUndef->canBeNull() < existingUndef->canBeNull()); break; } case NCR_DupShLib: { const SharedLibraryAtom *curShLib = cast<SharedLibraryAtom>(existing); const SharedLibraryAtom *newShLib = cast<SharedLibraryAtom>(&newAtom); bool sameNullness = (curShLib->canBeNullAtRuntime() == newShLib->canBeNullAtRuntime()); bool sameName = curShLib->loadName().equals(newShLib->loadName()); if (sameName && !sameNullness && _context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) { // FIXME: need diagonstics interface for writing warning messages llvm::errs() << "lld warning: shared library symbol " << curShLib->name() << " has different weakness in " << curShLib->file().path() << " and in " << newShLib->file().path(); } if (!sameName && _context.warnIfCoalesableAtomsHaveDifferentLoadName()) { // FIXME: need diagonstics interface for writing warning messages llvm::errs() << "lld warning: shared library symbol " << curShLib->name() << " has different load path in " << curShLib->file().path() << " and in " << newShLib->file().path(); } useNew = false; break; } case NCR_Error: llvm::errs() << "SymbolTable: error while merging " << name << "\n"; llvm::report_fatal_error("duplicate symbol error"); break; } if (useNew) { // Update name table to use new atom. _nameTable[name] = &newAtom; // Add existing atom to replacement table. _replacedAtoms[existing] = &newAtom; } else { // New atom is not being used. Add it to replacement table. _replacedAtoms[&newAtom] = existing; } } unsigned SymbolTable::AtomMappingInfo::getHashValue(const DefinedAtom *atom) { auto content = atom->rawContent(); return llvm::hash_combine(atom->size(), atom->contentType(), llvm::hash_combine_range(content.begin(), content.end())); } bool SymbolTable::AtomMappingInfo::isEqual(const DefinedAtom * const l, const DefinedAtom * const r) { if (l == r) return true; if (l == getEmptyKey()) return false; if (r == getEmptyKey()) return false; if (l == getTombstoneKey()) return false; if (r == getTombstoneKey()) return false; if (l->contentType() != r->contentType()) return false; if (l->size() != r->size()) return false; ArrayRef<uint8_t> lc = l->rawContent(); ArrayRef<uint8_t> rc = r->rawContent(); return memcmp(lc.data(), rc.data(), lc.size()) == 0; } void SymbolTable::addByContent(const DefinedAtom & newAtom) { // Currently only read-only constants can be merged. assert(newAtom.permissions() == DefinedAtom::permR__); AtomContentSet::iterator pos = _contentTable.find(&newAtom); if (pos == _contentTable.end()) { _contentTable.insert(&newAtom); return; } const Atom* existing = *pos; // New atom is not being used. Add it to replacement table. _replacedAtoms[&newAtom] = existing; } const Atom *SymbolTable::findByName(StringRef sym) { NameToAtom::iterator pos = _nameTable.find(sym); if (pos == _nameTable.end()) return nullptr; return pos->second; } bool SymbolTable::isDefined(StringRef sym) { if (const Atom *atom = findByName(sym)) return atom->definition() != Atom::definitionUndefined; return false; } void SymbolTable::addReplacement(const Atom *replaced, const Atom *replacement) { _replacedAtoms[replaced] = replacement; } const Atom *SymbolTable::replacement(const Atom *atom) { // Find the replacement for a given atom. Atoms in _replacedAtoms // may be chained, so find the last one. for (;;) { AtomToAtom::iterator pos = _replacedAtoms.find(atom); if (pos == _replacedAtoms.end()) return atom; atom = pos->second; } } unsigned int SymbolTable::size() { return _nameTable.size(); } std::vector<const UndefinedAtom *> SymbolTable::undefines() { std::vector<const UndefinedAtom *> ret; for (auto it : _nameTable) { const Atom *atom = it.second; assert(atom != nullptr); if (const auto undef = dyn_cast<const UndefinedAtom>(atom)) { AtomToAtom::iterator pos = _replacedAtoms.find(undef); if (pos != _replacedAtoms.end()) continue; ret.push_back(undef); } } return ret; } std::vector<StringRef> SymbolTable::tentativeDefinitions() { std::vector<StringRef> ret; for (auto entry : _nameTable) { const Atom *atom = entry.second; StringRef name = entry.first; assert(atom != nullptr); if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom)) if (defAtom->merge() == DefinedAtom::mergeAsTentative) ret.push_back(name); } return ret; } } // namespace lld
Split a utility function not to use goto statement.
Split a utility function not to use goto statement. git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@205643 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lld,llvm-mirror/lld
e5a1509d94d14c6660e6b3078990f2724cc7a099
src/core/ext/filters/http/message_decompress/message_decompress_filter.cc
src/core/ext/filters/http/message_decompress/message_decompress_filter.cc
/* * * Copyright 2015 gRPC 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 <grpc/support/port_platform.h> #include <assert.h> #include <string.h> #include <grpc/compression.h> #include <grpc/slice_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/http/message_decompress/message_decompress_filter.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/compression/algorithm_metadata.h" #include "src/core/lib/compression/compression_args.h" #include "src/core/lib/compression/compression_internal.h" #include "src/core/lib/compression/message_compress.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" namespace { class ChannelData {}; class CallData { public: CallData(const grpc_call_element_args& args) : call_combiner_(args.call_combiner) { // Initialize state for recv_initial_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_initial_metadata_ready_, OnRecvInitialMetadataReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_message_ready callback GRPC_CLOSURE_INIT(&on_recv_message_next_done_, OnRecvMessageNextDone, this, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&on_recv_message_ready_, OnRecvMessageReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_trailing_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_trailing_metadata_ready_, OnRecvTrailingMetadataReady, this, grpc_schedule_on_exec_ctx); } static void DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch); static void OnRecvInitialMetadataReady(void* arg, grpc_error* error); // Methods for processing a receive message event void MaybeResumeOnRecvMessageReady(); static void OnRecvMessageReady(void* arg, grpc_error* error); static void OnRecvMessageNextDone(void* arg, grpc_error* error); grpc_error* PullSliceFromRecvMessage(); void ContinueReadingRecvMessage(); void FinishRecvMessage(); void ContinueRecvMessageReadyCallback(grpc_error* error); // Methods for processing a recv_trailing_metadata event void MaybeResumeOnRecvTrailingMetadataReady(); static void OnRecvTrailingMetadataReady(void* arg, grpc_error* error); private: grpc_core::CallCombiner* call_combiner_ = nullptr; // Overall error for the call grpc_error* error_ = GRPC_ERROR_NONE; // Fields for handling recv_initial_metadata_ready callback grpc_closure on_recv_initial_metadata_ready_; grpc_closure* original_recv_initial_metadata_ready_ = nullptr; grpc_metadata_batch* recv_initial_metadata_ = nullptr; // Fields for handling recv_message_ready callback bool seen_recv_message_ready_ = false; grpc_message_compression_algorithm algorithm_ = GRPC_MESSAGE_COMPRESS_NONE; grpc_closure on_recv_message_ready_; grpc_closure* original_recv_message_ready_ = nullptr; grpc_closure on_recv_message_next_done_; grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message_ = nullptr; // recv_slices_ holds the slices read from the original recv_message stream. // It is initialized during construction and reset when a new stream is // created using it. grpc_slice_buffer recv_slices_; grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> recv_replacement_stream_; // Fields for handling recv_trailing_metadata_ready callback bool seen_recv_trailing_metadata_ready_ = false; grpc_closure on_recv_trailing_metadata_ready_; grpc_closure* original_recv_trailing_metadata_ready_ = nullptr; grpc_error* on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; }; grpc_message_compression_algorithm DecodeMessageCompressionAlgorithm( grpc_mdelem md) { grpc_message_compression_algorithm algorithm = grpc_message_compression_algorithm_from_slice(GRPC_MDVALUE(md)); if (algorithm == GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) { char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid incoming message compression algorithm: '%s'. " "Interpreting incoming data as uncompressed.", md_c_str); gpr_free(md_c_str); return GRPC_MESSAGE_COMPRESS_NONE; } return algorithm; } void CallData::OnRecvInitialMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { grpc_linked_mdelem* grpc_encoding = calld->recv_initial_metadata_->idx.named.grpc_encoding; if (grpc_encoding != nullptr) { calld->algorithm_ = DecodeMessageCompressionAlgorithm(grpc_encoding->md); } } calld->MaybeResumeOnRecvMessageReady(); calld->MaybeResumeOnRecvTrailingMetadataReady(); grpc_closure* closure = calld->original_recv_initial_metadata_ready_; calld->original_recv_initial_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error)); } void CallData::MaybeResumeOnRecvMessageReady() { if (seen_recv_message_ready_) { seen_recv_message_ready_ = false; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_message_ready_, GRPC_ERROR_NONE, "continue recv_message_ready callback"); } } void CallData::OnRecvMessageReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { if (calld->original_recv_initial_metadata_ready_ != nullptr) { calld->seen_recv_message_ready_ = true; GRPC_CALL_COMBINER_STOP(calld->call_combiner_, "Deferring OnRecvMessageReady until after " "OnRecvInitialMetadataReady"); return; } if (calld->algorithm_ != GRPC_MESSAGE_COMPRESS_NONE) { // recv_message can be NULL if trailing metadata is received instead of // message, or it's possible that the message was not compressed. if (*calld->recv_message_ == nullptr || (*calld->recv_message_)->length() == 0 || ((*calld->recv_message_)->flags() & GRPC_WRITE_INTERNAL_COMPRESS) == 0) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_NONE); } grpc_slice_buffer_init(&calld->recv_slices_); return calld->ContinueReadingRecvMessage(); } } calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } void CallData::ContinueReadingRecvMessage() { while ((*recv_message_) ->Next(~static_cast<size_t>(0), &on_recv_message_next_done_)) { grpc_error* error = PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return ContinueRecvMessageReadyCallback(error); } // We have read the entire message. if (recv_slices_.length == (*recv_message_)->length()) { return FinishRecvMessage(); } } } grpc_error* CallData::PullSliceFromRecvMessage() { grpc_slice incoming_slice; grpc_error* error = (*recv_message_)->Pull(&incoming_slice); if (error == GRPC_ERROR_NONE) { grpc_slice_buffer_add(&recv_slices_, incoming_slice); } return error; } void CallData::OnRecvMessageNextDone(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } error = calld->PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(error); } if (calld->recv_slices_.length == (*calld->recv_message_)->length()) { calld->FinishRecvMessage(); } else { calld->ContinueReadingRecvMessage(); } } void CallData::FinishRecvMessage() { grpc_slice_buffer decompressed_slices; grpc_slice_buffer_init(&decompressed_slices); if (grpc_msg_decompress(algorithm_, &recv_slices_, &decompressed_slices) == 0) { char* msg; gpr_asprintf( &msg, "Unexpected error decompressing data for algorithm with enum value %d", algorithm_); GPR_DEBUG_ASSERT(error_ == GRPC_ERROR_NONE); error_ = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); grpc_slice_buffer_destroy_internal(&decompressed_slices); } else { uint32_t recv_flags = ((*recv_message_)->flags() & (~GRPC_WRITE_INTERNAL_COMPRESS)) | GRPC_WRITE_INTERNAL_TEST_ONLY_WAS_COMPRESSED; // Swap out the original receive byte stream with our new one and send the // batch down. // Initializing recv_replacement_stream_ with decompressed_slices removes // all the slices from decompressed_slices leaving it empty. recv_replacement_stream_.Init(&decompressed_slices, recv_flags); recv_message_->reset(recv_replacement_stream_.get()); recv_message_ = nullptr; } grpc_slice_buffer_destroy_internal(&recv_slices_); ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error_)); } void CallData::ContinueRecvMessageReadyCallback(grpc_error* error) { MaybeResumeOnRecvTrailingMetadataReady(); // The surface will clean up the receiving stream if there is an error. grpc_closure* closure = original_recv_message_ready_; original_recv_message_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::MaybeResumeOnRecvTrailingMetadataReady() { if (seen_recv_trailing_metadata_ready_) { seen_recv_trailing_metadata_ready_ = false; grpc_error* error = on_recv_trailing_metadata_ready_error_; on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_trailing_metadata_ready_, error, "Continuing OnRecvTrailingMetadataReady"); } } void CallData::OnRecvTrailingMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (calld->original_recv_initial_metadata_ready_ != nullptr || calld->original_recv_message_ready_ != nullptr) { calld->seen_recv_trailing_metadata_ready_ = true; calld->on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_REF(error); GRPC_CALL_COMBINER_STOP( calld->call_combiner_, "Deferring OnRecvTrailingMetadataReady until after " "OnRecvInitialMetadataReady and OnRecvMessageReady"); return; } error = grpc_error_add_child(GRPC_ERROR_REF(error), calld->error_); calld->error_ = GRPC_ERROR_NONE; grpc_closure* closure = calld->original_recv_trailing_metadata_ready_; calld->original_recv_trailing_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { GPR_TIMER_SCOPE("compress_start_transport_stream_op_batch", 0); CallData* calld = static_cast<CallData*>(elem->call_data); // Handle recv_initial_metadata. if (batch->recv_initial_metadata) { calld->recv_initial_metadata_ = batch->payload->recv_initial_metadata.recv_initial_metadata; calld->original_recv_initial_metadata_ready_ = batch->payload->recv_initial_metadata.recv_initial_metadata_ready; batch->payload->recv_initial_metadata.recv_initial_metadata_ready = &calld->on_recv_initial_metadata_ready_; } // Handle recv_message if (batch->recv_message) { calld->recv_message_ = batch->payload->recv_message.recv_message; calld->original_recv_message_ready_ = batch->payload->recv_message.recv_message_ready; batch->payload->recv_message.recv_message_ready = &calld->on_recv_message_ready_; } // Handle recv_trailing_metadata if (batch->recv_trailing_metadata) { calld->original_recv_trailing_metadata_ready_ = batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = &calld->on_recv_trailing_metadata_ready_; } // Pass control down the stack. grpc_call_next_op(elem, batch); } static grpc_error* DecompressInitCallElem(grpc_call_element* elem, const grpc_call_element_args* args) { new (elem->call_data) CallData(*args); return GRPC_ERROR_NONE; } static void DecompressDestroyCallElem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { CallData* calld = static_cast<CallData*>(elem->call_data); calld->~CallData(); } static grpc_error* DecompressInitChannelElem( grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) { return GRPC_ERROR_NONE; } void DecompressDestroyChannelElem(grpc_channel_element* /*elem*/) { return; } } // namespace const grpc_channel_filter grpc_message_decompress_filter = { CallData::DecompressStartTransportStreamOpBatch, grpc_channel_next_op, sizeof(CallData), DecompressInitCallElem, grpc_call_stack_ignore_set_pollset_or_pollset_set, DecompressDestroyCallElem, 0, // sizeof(ChannelData) DecompressInitChannelElem, DecompressDestroyChannelElem, grpc_channel_next_get_info, "message_decompress"};
/* * * Copyright 2015 gRPC 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 <grpc/support/port_platform.h> #include <assert.h> #include <string.h> #include <grpc/compression.h> #include <grpc/slice_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/http/message_decompress/message_decompress_filter.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/compression/algorithm_metadata.h" #include "src/core/lib/compression/compression_args.h" #include "src/core/lib/compression/compression_internal.h" #include "src/core/lib/compression/message_compress.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" namespace { class ChannelData {}; class CallData { public: CallData(const grpc_call_element_args& args) : call_combiner_(args.call_combiner) { // Initialize state for recv_initial_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_initial_metadata_ready_, OnRecvInitialMetadataReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_message_ready callback grpc_slice_buffer_init(&recv_slices_); GRPC_CLOSURE_INIT(&on_recv_message_next_done_, OnRecvMessageNextDone, this, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&on_recv_message_ready_, OnRecvMessageReady, this, grpc_schedule_on_exec_ctx); // Initialize state for recv_trailing_metadata_ready callback GRPC_CLOSURE_INIT(&on_recv_trailing_metadata_ready_, OnRecvTrailingMetadataReady, this, grpc_schedule_on_exec_ctx); } ~CallData() { grpc_slice_buffer_destroy_internal(&recv_slices_); } static void DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch); static void OnRecvInitialMetadataReady(void* arg, grpc_error* error); // Methods for processing a receive message event void MaybeResumeOnRecvMessageReady(); static void OnRecvMessageReady(void* arg, grpc_error* error); static void OnRecvMessageNextDone(void* arg, grpc_error* error); grpc_error* PullSliceFromRecvMessage(); void ContinueReadingRecvMessage(); void FinishRecvMessage(); void ContinueRecvMessageReadyCallback(grpc_error* error); // Methods for processing a recv_trailing_metadata event void MaybeResumeOnRecvTrailingMetadataReady(); static void OnRecvTrailingMetadataReady(void* arg, grpc_error* error); private: grpc_core::CallCombiner* call_combiner_ = nullptr; // Overall error for the call grpc_error* error_ = GRPC_ERROR_NONE; // Fields for handling recv_initial_metadata_ready callback grpc_closure on_recv_initial_metadata_ready_; grpc_closure* original_recv_initial_metadata_ready_ = nullptr; grpc_metadata_batch* recv_initial_metadata_ = nullptr; // Fields for handling recv_message_ready callback bool seen_recv_message_ready_ = false; grpc_message_compression_algorithm algorithm_ = GRPC_MESSAGE_COMPRESS_NONE; grpc_closure on_recv_message_ready_; grpc_closure* original_recv_message_ready_ = nullptr; grpc_closure on_recv_message_next_done_; grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message_ = nullptr; // recv_slices_ holds the slices read from the original recv_message stream. // It is initialized during construction and reset when a new stream is // created using it. grpc_slice_buffer recv_slices_; grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> recv_replacement_stream_; // Fields for handling recv_trailing_metadata_ready callback bool seen_recv_trailing_metadata_ready_ = false; grpc_closure on_recv_trailing_metadata_ready_; grpc_closure* original_recv_trailing_metadata_ready_ = nullptr; grpc_error* on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; }; grpc_message_compression_algorithm DecodeMessageCompressionAlgorithm( grpc_mdelem md) { grpc_message_compression_algorithm algorithm = grpc_message_compression_algorithm_from_slice(GRPC_MDVALUE(md)); if (algorithm == GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) { char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid incoming message compression algorithm: '%s'. " "Interpreting incoming data as uncompressed.", md_c_str); gpr_free(md_c_str); return GRPC_MESSAGE_COMPRESS_NONE; } return algorithm; } void CallData::OnRecvInitialMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { grpc_linked_mdelem* grpc_encoding = calld->recv_initial_metadata_->idx.named.grpc_encoding; if (grpc_encoding != nullptr) { calld->algorithm_ = DecodeMessageCompressionAlgorithm(grpc_encoding->md); } } calld->MaybeResumeOnRecvMessageReady(); calld->MaybeResumeOnRecvTrailingMetadataReady(); grpc_closure* closure = calld->original_recv_initial_metadata_ready_; calld->original_recv_initial_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error)); } void CallData::MaybeResumeOnRecvMessageReady() { if (seen_recv_message_ready_) { seen_recv_message_ready_ = false; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_message_ready_, GRPC_ERROR_NONE, "continue recv_message_ready callback"); } } void CallData::OnRecvMessageReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error == GRPC_ERROR_NONE) { if (calld->original_recv_initial_metadata_ready_ != nullptr) { calld->seen_recv_message_ready_ = true; GRPC_CALL_COMBINER_STOP(calld->call_combiner_, "Deferring OnRecvMessageReady until after " "OnRecvInitialMetadataReady"); return; } if (calld->algorithm_ != GRPC_MESSAGE_COMPRESS_NONE) { // recv_message can be NULL if trailing metadata is received instead of // message, or it's possible that the message was not compressed. if (*calld->recv_message_ == nullptr || (*calld->recv_message_)->length() == 0 || ((*calld->recv_message_)->flags() & GRPC_WRITE_INTERNAL_COMPRESS) == 0) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_NONE); } grpc_slice_buffer_destroy_internal(&calld->recv_slices_); grpc_slice_buffer_init(&calld->recv_slices_); return calld->ContinueReadingRecvMessage(); } } calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } void CallData::ContinueReadingRecvMessage() { while ((*recv_message_) ->Next(~static_cast<size_t>(0), &on_recv_message_next_done_)) { grpc_error* error = PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return ContinueRecvMessageReadyCallback(error); } // We have read the entire message. if (recv_slices_.length == (*recv_message_)->length()) { return FinishRecvMessage(); } } } grpc_error* CallData::PullSliceFromRecvMessage() { grpc_slice incoming_slice; grpc_error* error = (*recv_message_)->Pull(&incoming_slice); if (error == GRPC_ERROR_NONE) { grpc_slice_buffer_add(&recv_slices_, incoming_slice); } return error; } void CallData::OnRecvMessageNextDone(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error)); } error = calld->PullSliceFromRecvMessage(); if (error != GRPC_ERROR_NONE) { return calld->ContinueRecvMessageReadyCallback(error); } if (calld->recv_slices_.length == (*calld->recv_message_)->length()) { calld->FinishRecvMessage(); } else { calld->ContinueReadingRecvMessage(); } } void CallData::FinishRecvMessage() { grpc_slice_buffer decompressed_slices; grpc_slice_buffer_init(&decompressed_slices); if (grpc_msg_decompress(algorithm_, &recv_slices_, &decompressed_slices) == 0) { char* msg; gpr_asprintf( &msg, "Unexpected error decompressing data for algorithm with enum value %d", algorithm_); GPR_DEBUG_ASSERT(error_ == GRPC_ERROR_NONE); error_ = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); grpc_slice_buffer_destroy_internal(&decompressed_slices); } else { uint32_t recv_flags = ((*recv_message_)->flags() & (~GRPC_WRITE_INTERNAL_COMPRESS)) | GRPC_WRITE_INTERNAL_TEST_ONLY_WAS_COMPRESSED; // Swap out the original receive byte stream with our new one and send the // batch down. // Initializing recv_replacement_stream_ with decompressed_slices removes // all the slices from decompressed_slices leaving it empty. recv_replacement_stream_.Init(&decompressed_slices, recv_flags); recv_message_->reset(recv_replacement_stream_.get()); recv_message_ = nullptr; } ContinueRecvMessageReadyCallback(GRPC_ERROR_REF(error_)); } void CallData::ContinueRecvMessageReadyCallback(grpc_error* error) { MaybeResumeOnRecvTrailingMetadataReady(); // The surface will clean up the receiving stream if there is an error. grpc_closure* closure = original_recv_message_ready_; original_recv_message_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::MaybeResumeOnRecvTrailingMetadataReady() { if (seen_recv_trailing_metadata_ready_) { seen_recv_trailing_metadata_ready_ = false; grpc_error* error = on_recv_trailing_metadata_ready_error_; on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; GRPC_CALL_COMBINER_START(call_combiner_, &on_recv_trailing_metadata_ready_, error, "Continuing OnRecvTrailingMetadataReady"); } } void CallData::OnRecvTrailingMetadataReady(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); if (calld->original_recv_initial_metadata_ready_ != nullptr || calld->original_recv_message_ready_ != nullptr) { calld->seen_recv_trailing_metadata_ready_ = true; calld->on_recv_trailing_metadata_ready_error_ = GRPC_ERROR_REF(error); GRPC_CALL_COMBINER_STOP( calld->call_combiner_, "Deferring OnRecvTrailingMetadataReady until after " "OnRecvInitialMetadataReady and OnRecvMessageReady"); return; } error = grpc_error_add_child(GRPC_ERROR_REF(error), calld->error_); calld->error_ = GRPC_ERROR_NONE; grpc_closure* closure = calld->original_recv_trailing_metadata_ready_; calld->original_recv_trailing_metadata_ready_ = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } void CallData::DecompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { GPR_TIMER_SCOPE("compress_start_transport_stream_op_batch", 0); CallData* calld = static_cast<CallData*>(elem->call_data); // Handle recv_initial_metadata. if (batch->recv_initial_metadata) { calld->recv_initial_metadata_ = batch->payload->recv_initial_metadata.recv_initial_metadata; calld->original_recv_initial_metadata_ready_ = batch->payload->recv_initial_metadata.recv_initial_metadata_ready; batch->payload->recv_initial_metadata.recv_initial_metadata_ready = &calld->on_recv_initial_metadata_ready_; } // Handle recv_message if (batch->recv_message) { calld->recv_message_ = batch->payload->recv_message.recv_message; calld->original_recv_message_ready_ = batch->payload->recv_message.recv_message_ready; batch->payload->recv_message.recv_message_ready = &calld->on_recv_message_ready_; } // Handle recv_trailing_metadata if (batch->recv_trailing_metadata) { calld->original_recv_trailing_metadata_ready_ = batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = &calld->on_recv_trailing_metadata_ready_; } // Pass control down the stack. grpc_call_next_op(elem, batch); } static grpc_error* DecompressInitCallElem(grpc_call_element* elem, const grpc_call_element_args* args) { new (elem->call_data) CallData(*args); return GRPC_ERROR_NONE; } static void DecompressDestroyCallElem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { CallData* calld = static_cast<CallData*>(elem->call_data); calld->~CallData(); } static grpc_error* DecompressInitChannelElem( grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) { return GRPC_ERROR_NONE; } void DecompressDestroyChannelElem(grpc_channel_element* /*elem*/) { return; } } // namespace const grpc_channel_filter grpc_message_decompress_filter = { CallData::DecompressStartTransportStreamOpBatch, grpc_channel_next_op, sizeof(CallData), DecompressInitCallElem, grpc_call_stack_ignore_set_pollset_or_pollset_set, DecompressDestroyCallElem, 0, // sizeof(ChannelData) DecompressInitChannelElem, DecompressDestroyChannelElem, grpc_channel_next_get_info, "message_decompress"};
Move around slice buffer initialization and destruction
Move around slice buffer initialization and destruction
C++
apache-2.0
ejona86/grpc,nicolasnoble/grpc,nicolasnoble/grpc,nicolasnoble/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jboeuf/grpc,ctiller/grpc,donnadionne/grpc,grpc/grpc,jboeuf/grpc,vjpai/grpc,nicolasnoble/grpc,ejona86/grpc,jtattermusch/grpc,firebase/grpc,grpc/grpc,ejona86/grpc,jtattermusch/grpc,jboeuf/grpc,firebase/grpc,donnadionne/grpc,grpc/grpc,ctiller/grpc,vjpai/grpc,ctiller/grpc,jtattermusch/grpc,jboeuf/grpc,donnadionne/grpc,jboeuf/grpc,ejona86/grpc,grpc/grpc,jboeuf/grpc,jboeuf/grpc,vjpai/grpc,donnadionne/grpc,nicolasnoble/grpc,jboeuf/grpc,nicolasnoble/grpc,jtattermusch/grpc,jtattermusch/grpc,stanley-cheung/grpc,donnadionne/grpc,firebase/grpc,firebase/grpc,jtattermusch/grpc,ctiller/grpc,vjpai/grpc,grpc/grpc,ejona86/grpc,ctiller/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,jtattermusch/grpc,firebase/grpc,stanley-cheung/grpc,grpc/grpc,ctiller/grpc,vjpai/grpc,jtattermusch/grpc,jboeuf/grpc,jtattermusch/grpc,grpc/grpc,nicolasnoble/grpc,grpc/grpc,ctiller/grpc,ctiller/grpc,stanley-cheung/grpc,stanley-cheung/grpc,firebase/grpc,nicolasnoble/grpc,firebase/grpc,vjpai/grpc,stanley-cheung/grpc,donnadionne/grpc,jboeuf/grpc,ejona86/grpc,jtattermusch/grpc,ctiller/grpc,jtattermusch/grpc,ctiller/grpc,firebase/grpc,donnadionne/grpc,stanley-cheung/grpc,ctiller/grpc,ejona86/grpc,grpc/grpc,firebase/grpc,ctiller/grpc,ejona86/grpc,vjpai/grpc,vjpai/grpc,ejona86/grpc,grpc/grpc,grpc/grpc,vjpai/grpc,donnadionne/grpc,nicolasnoble/grpc,jtattermusch/grpc,nicolasnoble/grpc,donnadionne/grpc,stanley-cheung/grpc,jboeuf/grpc,ejona86/grpc,donnadionne/grpc,jboeuf/grpc,stanley-cheung/grpc,nicolasnoble/grpc,firebase/grpc,firebase/grpc,stanley-cheung/grpc,stanley-cheung/grpc,donnadionne/grpc,ejona86/grpc,firebase/grpc,vjpai/grpc,donnadionne/grpc,vjpai/grpc,ejona86/grpc
49e27a5375b20e3f422730fd77425baf5abd4e68
lib/Linker/LinkItems.cpp
lib/Linker/LinkItems.cpp
//===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains routines to handle linking together LLVM bitcode files, // and to handle annoying things like static libraries. // //===----------------------------------------------------------------------===// #include "llvm/Linker.h" #include "llvm/Module.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/System/Path.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" using namespace llvm; // LinkItems - This function is the main entry point into linking. It takes a // list of LinkItem which indicates the order the files should be linked and // how each file should be treated (plain file or with library search). The // function only links bitcode and produces a result list of items that are // native objects. bool Linker::LinkInItems(const ItemList& Items, ItemList& NativeItems) { // Clear the NativeItems just in case NativeItems.clear(); // For each linkage item ... for (ItemList::const_iterator I = Items.begin(), E = Items.end(); I != E; ++I) { if (I->second) { // Link in the library suggested. bool is_native = false; if (LinkInLibrary(I->first, is_native)) return true; if (is_native) NativeItems.push_back(*I); } else { // Link in the file suggested bool is_native = false; if (LinkInFile(sys::Path(I->first), is_native)) return true; if (is_native) NativeItems.push_back(*I); } } // At this point we have processed all the link items provided to us. Since // we have an aggregated module at this point, the dependent libraries in // that module should also be aggregated with duplicates eliminated. This is // now the time to process the dependent libraries to resolve any remaining // symbols. bool is_native; for (Module::lib_iterator I = Composite->lib_begin(), E = Composite->lib_end(); I != E; ++I) { if(LinkInLibrary(*I, is_native)) return true; if (is_native) NativeItems.push_back(std::make_pair(*I, true)); } return false; } /// LinkInLibrary - links one library into the HeadModule. /// bool Linker::LinkInLibrary(StringRef Lib, bool& is_native) { is_native = false; // Determine where this library lives. sys::Path Pathname = FindLib(Lib); if (Pathname.isEmpty()) return error("Cannot find library '" + Lib.str() + "'"); // If its an archive, try to link it in std::string Magic; Pathname.getMagicNumber(Magic, 64); switch (sys::IdentifyFileType(Magic.c_str(), 64)) { default: llvm_unreachable("Bad file type identification"); case sys::Unknown_FileType: return warning("Supposed library '" + Lib.str() + "' isn't a library."); case sys::Bitcode_FileType: // LLVM ".so" file. if (LinkInFile(Pathname, is_native)) return true; break; case sys::Archive_FileType: if (LinkInArchive(Pathname, is_native)) return error("Cannot link archive '" + Pathname.str() + "'"); break; case sys::ELF_Relocatable_FileType: case sys::ELF_SharedObject_FileType: case sys::Mach_O_Object_FileType: case sys::Mach_O_FixedVirtualMemorySharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType: case sys::COFF_FileType: is_native = true; break; } return false; } /// LinkLibraries - takes the specified library files and links them into the /// main bitcode object file. /// /// Inputs: /// Libraries - The list of libraries to link into the module. /// /// Return value: /// FALSE - No error. /// TRUE - Error. /// bool Linker::LinkInLibraries(const std::vector<std::string> &Libraries) { // Process the set of libraries we've been provided. bool is_native = false; for (unsigned i = 0; i < Libraries.size(); ++i) if (LinkInLibrary(Libraries[i], is_native)) return true; // At this point we have processed all the libraries provided to us. Since // we have an aggregated module at this point, the dependent libraries in // that module should also be aggregated with duplicates eliminated. This is // now the time to process the dependent libraries to resolve any remaining // symbols. const Module::LibraryListType& DepLibs = Composite->getLibraries(); for (Module::LibraryListType::const_iterator I = DepLibs.begin(), E = DepLibs.end(); I != E; ++I) if (LinkInLibrary(*I, is_native)) return true; return false; } /// LinkInFile - opens a bitcode file and links in all objects which /// provide symbols that are currently undefined. /// /// Inputs: /// File - The pathname of the bitcode file. /// /// Outputs: /// ErrorMessage - A C++ string detailing what error occurred, if any. /// /// Return Value: /// TRUE - An error occurred. /// FALSE - No errors. /// bool Linker::LinkInFile(const sys::Path &File, bool &is_native) { is_native = false; // Check for a file of name "-", which means "read standard input" if (File.str() == "-") { std::auto_ptr<Module> M; if (MemoryBuffer *Buffer = MemoryBuffer::getSTDIN()) { M.reset(ParseBitcodeFile(Buffer, Context, &Error)); delete Buffer; if (M.get()) if (!LinkInModule(M.get(), &Error)) return false; } else Error = "standard input is empty"; return error("Cannot link stdin: " + Error); } // Make sure we can at least read the file if (!File.canRead()) return error("Cannot find linker input '" + File.str() + "'"); // If its an archive, try to link it in std::string Magic; File.getMagicNumber(Magic, 64); switch (sys::IdentifyFileType(Magic.c_str(), 64)) { default: llvm_unreachable("Bad file type identification"); case sys::Unknown_FileType: return warning("Ignoring file '" + File.str() + "' because does not contain bitcode."); case sys::Archive_FileType: // A user may specify an ar archive without -l, perhaps because it // is not installed as a library. Detect that and link the archive. verbose("Linking archive file '" + File.str() + "'"); if (LinkInArchive(File, is_native)) return true; break; case sys::Bitcode_FileType: { verbose("Linking bitcode file '" + File.str() + "'"); std::auto_ptr<Module> M(LoadObject(File)); if (M.get() == 0) return error("Cannot load file '" + File.str() + "': " + Error); if (LinkInModule(M.get(), &Error)) return error("Cannot link file '" + File.str() + "': " + Error); verbose("Linked in file '" + File.str() + "'"); break; } case sys::ELF_Relocatable_FileType: case sys::ELF_SharedObject_FileType: case sys::Mach_O_Object_FileType: case sys::Mach_O_FixedVirtualMemorySharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType: case sys::COFF_FileType: is_native = true; break; } return false; } /// LinkFiles - takes a module and a list of files and links them all together. /// It locates the file either in the current directory, as its absolute /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH. /// /// Inputs: /// Files - A vector of sys::Path indicating the LLVM bitcode filenames /// to be linked. The names can refer to a mixture of pure LLVM /// bitcode files and archive (ar) formatted files. /// /// Return value: /// FALSE - No errors. /// TRUE - Some error occurred. /// bool Linker::LinkInFiles(const std::vector<sys::Path> &Files) { bool is_native; for (unsigned i = 0; i < Files.size(); ++i) if (LinkInFile(Files[i], is_native)) return true; return false; }
//===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains routines to handle linking together LLVM bitcode files, // and to handle annoying things like static libraries. // //===----------------------------------------------------------------------===// #include "llvm/Linker.h" #include "llvm/Module.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/System/Path.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" using namespace llvm; // LinkItems - This function is the main entry point into linking. It takes a // list of LinkItem which indicates the order the files should be linked and // how each file should be treated (plain file or with library search). The // function only links bitcode and produces a result list of items that are // native objects. bool Linker::LinkInItems(const ItemList& Items, ItemList& NativeItems) { // Clear the NativeItems just in case NativeItems.clear(); // For each linkage item ... for (ItemList::const_iterator I = Items.begin(), E = Items.end(); I != E; ++I) { if (I->second) { // Link in the library suggested. bool is_native = false; if (LinkInLibrary(I->first, is_native)) return true; if (is_native) NativeItems.push_back(*I); } else { // Link in the file suggested bool is_native = false; if (LinkInFile(sys::Path(I->first), is_native)) return true; if (is_native) NativeItems.push_back(*I); } } // At this point we have processed all the link items provided to us. Since // we have an aggregated module at this point, the dependent libraries in // that module should also be aggregated with duplicates eliminated. This is // now the time to process the dependent libraries to resolve any remaining // symbols. bool is_native; for (Module::lib_iterator I = Composite->lib_begin(), E = Composite->lib_end(); I != E; ++I) { if(LinkInLibrary(*I, is_native)) return true; if (is_native) NativeItems.push_back(std::make_pair(*I, true)); } return false; } /// LinkInLibrary - links one library into the HeadModule. /// bool Linker::LinkInLibrary(StringRef Lib, bool& is_native) { is_native = false; // Determine where this library lives. sys::Path Pathname = FindLib(Lib); if (Pathname.isEmpty()) return error("Cannot find library '" + Lib.str() + "'"); // If its an archive, try to link it in std::string Magic; Pathname.getMagicNumber(Magic, 64); switch (sys::IdentifyFileType(Magic.c_str(), 64)) { default: llvm_unreachable("Bad file type identification"); case sys::Unknown_FileType: return warning("Supposed library '" + Lib.str() + "' isn't a library."); case sys::Bitcode_FileType: // LLVM ".so" file. if (LinkInFile(Pathname, is_native)) return true; break; case sys::Archive_FileType: if (LinkInArchive(Pathname, is_native)) return error("Cannot link archive '" + Pathname.str() + "'"); break; case sys::ELF_Relocatable_FileType: case sys::ELF_SharedObject_FileType: case sys::Mach_O_Object_FileType: case sys::Mach_O_FixedVirtualMemorySharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType: case sys::COFF_FileType: is_native = true; break; } return false; } /// LinkLibraries - takes the specified library files and links them into the /// main bitcode object file. /// /// Inputs: /// Libraries - The list of libraries to link into the module. /// /// Return value: /// FALSE - No error. /// TRUE - Error. /// bool Linker::LinkInLibraries(const std::vector<std::string> &Libraries) { // Process the set of libraries we've been provided. bool is_native = false; for (unsigned i = 0; i < Libraries.size(); ++i) if (LinkInLibrary(Libraries[i], is_native)) return true; // At this point we have processed all the libraries provided to us. Since // we have an aggregated module at this point, the dependent libraries in // that module should also be aggregated with duplicates eliminated. This is // now the time to process the dependent libraries to resolve any remaining // symbols. const Module::LibraryListType& DepLibs = Composite->getLibraries(); for (Module::LibraryListType::const_iterator I = DepLibs.begin(), E = DepLibs.end(); I != E; ++I) if (LinkInLibrary(*I, is_native)) return true; return false; } /// LinkInFile - opens a bitcode file and links in all objects which /// provide symbols that are currently undefined. /// /// Inputs: /// File - The pathname of the bitcode file. /// /// Outputs: /// ErrorMessage - A C++ string detailing what error occurred, if any. /// /// Return Value: /// TRUE - An error occurred. /// FALSE - No errors. /// bool Linker::LinkInFile(const sys::Path &File, bool &is_native) { is_native = false; // Check for a file of name "-", which means "read standard input" if (File.str() == "-") { std::auto_ptr<Module> M; if (MemoryBuffer *Buffer = MemoryBuffer::getSTDIN()) { M.reset(ParseBitcodeFile(Buffer, Context, &Error)); delete Buffer; if (M.get()) if (!LinkInModule(M.get(), &Error)) return false; } else Error = "standard input is empty"; return error("Cannot link stdin: " + Error); } // Make sure we can at least read the file if (!File.canRead()) return error("Cannot find linker input '" + File.str() + "'"); // If its an archive, try to link it in std::string Magic; File.getMagicNumber(Magic, 64); switch (sys::IdentifyFileType(Magic.c_str(), 64)) { default: llvm_unreachable("Bad file type identification"); case sys::Unknown_FileType: return warning("Ignoring file '" + File.str() + "' because does not contain bitcode."); case sys::Archive_FileType: // A user may specify an ar archive without -l, perhaps because it // is not installed as a library. Detect that and link the archive. if (LinkInArchive(File, is_native)) return true; break; case sys::Bitcode_FileType: { verbose("Linking bitcode file '" + File.str() + "'"); std::auto_ptr<Module> M(LoadObject(File)); if (M.get() == 0) return error("Cannot load file '" + File.str() + "': " + Error); if (LinkInModule(M.get(), &Error)) return error("Cannot link file '" + File.str() + "': " + Error); verbose("Linked in file '" + File.str() + "'"); break; } case sys::ELF_Relocatable_FileType: case sys::ELF_SharedObject_FileType: case sys::Mach_O_Object_FileType: case sys::Mach_O_FixedVirtualMemorySharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLib_FileType: case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType: case sys::COFF_FileType: is_native = true; break; } return false; } /// LinkFiles - takes a module and a list of files and links them all together. /// It locates the file either in the current directory, as its absolute /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH. /// /// Inputs: /// Files - A vector of sys::Path indicating the LLVM bitcode filenames /// to be linked. The names can refer to a mixture of pure LLVM /// bitcode files and archive (ar) formatted files. /// /// Return value: /// FALSE - No errors. /// TRUE - Some error occurred. /// bool Linker::LinkInFiles(const std::vector<sys::Path> &Files) { bool is_native; for (unsigned i = 0; i < Files.size(); ++i) if (LinkInFile(Files[i], is_native)) return true; return false; }
remove a redundant printout, LinkInArchive prints this as well.
remove a redundant printout, LinkInArchive prints this as well. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@86510 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap
a15be9ade46980644e3e58f21c7b06ba4fef98b4
tests/test_member_iterator2.cpp
tests/test_member_iterator2.cpp
#include "catch.hpp" #include <utility> #include <type_traits> #include <iterator> #include <algorithm> #include <member_iterator.hpp> #include <forward_list> TEST_CASE("member_iterator based on ForwardIterator", "[member_iterator]") { struct mock { char c; int i; }; std::forward_list<mock> mocklist{{'a', 1}, {'b', 2}, {'c', 3}}; typedef helene:: member_iterator<int, mock, std::forward_list<mock>::iterator, &mock::i> mocklist_iterator_type; mocklist_iterator_type beg_it = mocklist.begin(); mocklist_iterator_type end_it = mocklist.end(); //////////////////////////////////////////////////////////////////////////// // Iterator concept SECTION("construction") { auto elem = *beg_it; mocklist_iterator_type cop_it = beg_it; mocklist_iterator_type mov_it = std::move(beg_it); REQUIRE(*mov_it == elem); REQUIRE(cop_it == mov_it); } SECTION("assignment") { mocklist_iterator_type cop_it = beg_it; cop_it = end_it; REQUIRE(cop_it == end_it); } SECTION("move assignment") { mocklist_iterator_type an_it = beg_it; mocklist_iterator_type another_it = end_it; another_it = std::move(an_it); REQUIRE(another_it == beg_it); REQUIRE(*another_it == *beg_it); } SECTION("swappable") { using std::swap; mocklist_iterator_type beg_it2 = beg_it; mocklist_iterator_type end_it2 = end_it; swap(beg_it2, end_it2); REQUIRE(beg_it2 == end_it); REQUIRE(end_it2 == beg_it); } SECTION("traits") { std::iterator_traits<mocklist_iterator_type>::value_type i = 20; std::iterator_traits<mocklist_iterator_type>::difference_type j = -2; std::iterator_traits<mocklist_iterator_type>::reference k = i; std::iterator_traits<mocklist_iterator_type>::pointer l = &i; bool is_forward_iterator = std::is_same< std::iterator_traits<mocklist_iterator_type>::iterator_category, std::forward_iterator_tag>::value; REQUIRE(is_forward_iterator == true); } SECTION("dereference") { auto is_reference = std::is_same<decltype(*beg_it), int&>::value; REQUIRE(is_reference == true); REQUIRE(*beg_it == 1); } SECTION("preincrement") { auto ref_it = ++beg_it; bool is_iterator_reference = std::is_same<decltype(++beg_it), mocklist_iterator_type&>::value; REQUIRE(ref_it == beg_it); REQUIRE(*beg_it == 2); REQUIRE(is_iterator_reference == true); } SECTION("EqualityComparable") { bool equal = beg_it == end_it; REQUIRE(equal == false); REQUIRE(beg_it == mocklist.begin()); } //////////////////////////////////////////////////////////////////////////// // InputIterator SECTION("!=") { bool not_equal = beg_it != mocklist.begin(); REQUIRE(beg_it != end_it); REQUIRE(not_equal == false); } SECTION("postincrement") { bool is_conv_to_const_ref = std::is_convertible<decltype(beg_it++), const mocklist_iterator_type&>::value; (void)beg_it++; REQUIRE(is_conv_to_const_ref == true); REQUIRE(*beg_it == 2); } SECTION("postincrement and dereference") { bool is_conv_to_value_type = std::is_convertible<decltype(*beg_it++), int>::value; auto val = *beg_it++; REQUIRE(is_conv_to_value_type == true); REQUIRE(val == 1); REQUIRE(*beg_it == 2); } //////////////////////////////////////////////////////////////////////////// // OutputIterator SECTION("assignment through iterator") { *beg_it = 10; REQUIRE(*beg_it == 10); REQUIRE(mocklist.front().i == 10); REQUIRE(mocklist.front().c == 'a'); } //////////////////////////////////////////////////////////////////////////// // ForwardIterator SECTION("DefaultConstructible") { mocklist_iterator_type it; mocklist_iterator_type it2{}; mocklist_iterator_type(); mocklist_iterator_type{}; } SECTION("multipass guarantee") { auto beg_it_copy = beg_it; ++beg_it; ++beg_it; auto val0 = *beg_it_copy++; auto val1 = *beg_it_copy++; auto val2 = *beg_it_copy; REQUIRE(val0 == 1); REQUIRE(val1 == 2); REQUIRE(val2 == 3); } //////////////////////////////////////////////////////////////////////////// // Test std algorithms SECTION("std::equal") { std::forward_list<mock> mocklist_copy = mocklist; mocklist_iterator_type beg_it_copy(mocklist_copy.begin()); REQUIRE(std::equal(beg_it, end_it, beg_it_copy) == true); } SECTION("std::find") { auto found = std::find(beg_it, end_it, 2); REQUIRE(found != end_it); } SECTION("std::for_each") { int sum = 0; std::for_each(beg_it, end_it, [&sum](int i) { sum += i; }); REQUIRE(sum == 6); } SECTION("std::search") // requires ForwardIterator { std::vector<int> subsequence; subsequence.push_back(2); subsequence.push_back(3); auto found = std::search(beg_it, end_it, subsequence.begin(), subsequence.end()); REQUIRE(found != end_it); } SECTION("std::remove") // requires ForwardIterator { auto past_end = std::remove(beg_it, end_it, 2); auto native_iter = mocklist.begin(); REQUIRE(*beg_it == 1); REQUIRE(native_iter->i == 1); REQUIRE(native_iter->c == 'a'); SECTION("increment to second element") { ++beg_it; ++native_iter; REQUIRE(*beg_it == 3); REQUIRE(native_iter->i == 3); REQUIRE(native_iter->c == 'b'); } } } TEST_CASE("member_iterator based on std::vector::iterator", "[member_iterator]") { struct payload { int i; int get_i() const { return i; } bool operator==(const payload& other) const { return i == other.i; } }; struct mock { double weight; payload value; }; typedef helene::member_iterator<payload, mock, std::vector<mock>::iterator, &mock::value> mockveck_iterator_type; std::vector<mock> mockvec{{0.3, {1}}, {0.4, {2}}, {0.3, {3}}}; mockveck_iterator_type beg_it(mockvec.begin()); mockveck_iterator_type end_it(mockvec.end()); SECTION("category should be random_access_iterator_tag") { bool is_rai = std::is_same< std::iterator_traits<mockveck_iterator_type>::iterator_category, std::random_access_iterator_tag>::value; REQUIRE(is_rai == true); } //////////////////////////////////////////////////////////////////////////// // BidirectionalIterator SECTION("predecrement") { --end_it; REQUIRE(end_it->i == 3); REQUIRE(end_it->get_i() == 3); } SECTION("postdecrement") { end_it--; REQUIRE(end_it->i == 3); REQUIRE(end_it->get_i() == 3); } SECTION("postdecrement and dereference statement") { ++beg_it; auto old = *beg_it--; REQUIRE(old.i == 2); REQUIRE(beg_it->i == 1); } //////////////////////////////////////////////////////////////////////////// // RandomAccesIterator SECTION("+=") { bool is_iter_ref = std::is_same<decltype(beg_it += 2), mockveck_iterator_type&>::value; beg_it += 2; REQUIRE(is_iter_ref == true); REQUIRE(beg_it->i == 3); } SECTION("adding number") { bool is_iter_type = std::is_same<decltype(beg_it + 2), mockveck_iterator_type>::value; bool is_iter_type2 = std::is_same<decltype(2 + beg_it), mockveck_iterator_type>::value; auto res1 = beg_it + 2; auto res2 = 2 + beg_it; REQUIRE(is_iter_type == true); REQUIRE(is_iter_type2 == true); REQUIRE(res1 == res2); REQUIRE(res1->i == 3); REQUIRE(res2->i == 3); } SECTION("-=") { bool is_iter_ref = std::is_same<decltype(end_it -= 2), mockveck_iterator_type&>::value; end_it -= 2; REQUIRE(is_iter_ref == true); REQUIRE(end_it->i == 2); } SECTION("subtracting number") { bool is_iter_type = std::is_same<decltype(end_it - 2), mockveck_iterator_type>::value; auto res1 = end_it - 3; REQUIRE(is_iter_type == true); REQUIRE(res1->i == 1); } }
#include "catch.hpp" #include <utility> #include <type_traits> #include <iterator> #include <algorithm> #include <member_iterator.hpp> #include <forward_list> TEST_CASE("member_iterator based on ForwardIterator", "[member_iterator]") { struct mock { char c; int i; }; std::forward_list<mock> mocklist{{'a', 1}, {'b', 2}, {'c', 3}}; typedef helene:: member_iterator<int, mock, std::forward_list<mock>::iterator, &mock::i> mocklist_iterator_type; mocklist_iterator_type beg_it = mocklist.begin(); mocklist_iterator_type end_it = mocklist.end(); //////////////////////////////////////////////////////////////////////////// // Iterator concept SECTION("construction") { auto elem = *beg_it; mocklist_iterator_type cop_it = beg_it; mocklist_iterator_type mov_it = std::move(beg_it); REQUIRE(*mov_it == elem); REQUIRE(cop_it == mov_it); } SECTION("assignment") { mocklist_iterator_type cop_it = beg_it; cop_it = end_it; REQUIRE(cop_it == end_it); } SECTION("move assignment") { mocklist_iterator_type an_it = beg_it; mocklist_iterator_type another_it = end_it; another_it = std::move(an_it); REQUIRE(another_it == beg_it); REQUIRE(*another_it == *beg_it); } SECTION("swappable") { using std::swap; mocklist_iterator_type beg_it2 = beg_it; mocklist_iterator_type end_it2 = end_it; swap(beg_it2, end_it2); REQUIRE(beg_it2 == end_it); REQUIRE(end_it2 == beg_it); } SECTION("traits") { std::iterator_traits<mocklist_iterator_type>::value_type i = 20; std::iterator_traits<mocklist_iterator_type>::difference_type j = -2; std::iterator_traits<mocklist_iterator_type>::reference k = i; std::iterator_traits<mocklist_iterator_type>::pointer l = &i; bool is_forward_iterator = std::is_same< std::iterator_traits<mocklist_iterator_type>::iterator_category, std::forward_iterator_tag>::value; REQUIRE(is_forward_iterator == true); } SECTION("dereference") { auto is_reference = std::is_same<decltype(*beg_it), int&>::value; REQUIRE(is_reference == true); REQUIRE(*beg_it == 1); } SECTION("preincrement") { auto ref_it = ++beg_it; bool is_iterator_reference = std::is_same<decltype(++beg_it), mocklist_iterator_type&>::value; REQUIRE(ref_it == beg_it); REQUIRE(*beg_it == 2); REQUIRE(is_iterator_reference == true); } SECTION("EqualityComparable") { bool equal = beg_it == end_it; REQUIRE(equal == false); REQUIRE(beg_it == mocklist.begin()); } //////////////////////////////////////////////////////////////////////////// // InputIterator SECTION("!=") { bool not_equal = beg_it != mocklist.begin(); REQUIRE(beg_it != end_it); REQUIRE(not_equal == false); } SECTION("postincrement") { bool is_conv_to_const_ref = std::is_convertible<decltype(beg_it++), const mocklist_iterator_type&>::value; (void)beg_it++; REQUIRE(is_conv_to_const_ref == true); REQUIRE(*beg_it == 2); } SECTION("postincrement and dereference") { bool is_conv_to_value_type = std::is_convertible<decltype(*beg_it++), int>::value; auto val = *beg_it++; REQUIRE(is_conv_to_value_type == true); REQUIRE(val == 1); REQUIRE(*beg_it == 2); } //////////////////////////////////////////////////////////////////////////// // OutputIterator SECTION("assignment through iterator") { *beg_it = 10; REQUIRE(*beg_it == 10); REQUIRE(mocklist.front().i == 10); REQUIRE(mocklist.front().c == 'a'); } //////////////////////////////////////////////////////////////////////////// // ForwardIterator SECTION("DefaultConstructible") { mocklist_iterator_type it; mocklist_iterator_type it2{}; mocklist_iterator_type(); mocklist_iterator_type{}; } SECTION("multipass guarantee") { auto beg_it_copy = beg_it; ++beg_it; ++beg_it; auto val0 = *beg_it_copy++; auto val1 = *beg_it_copy++; auto val2 = *beg_it_copy; REQUIRE(val0 == 1); REQUIRE(val1 == 2); REQUIRE(val2 == 3); } //////////////////////////////////////////////////////////////////////////// // Test std algorithms SECTION("std::equal") { std::forward_list<mock> mocklist_copy = mocklist; mocklist_iterator_type beg_it_copy(mocklist_copy.begin()); REQUIRE(std::equal(beg_it, end_it, beg_it_copy) == true); } SECTION("std::find") { auto found = std::find(beg_it, end_it, 2); REQUIRE(found != end_it); } SECTION("std::for_each") { int sum = 0; std::for_each(beg_it, end_it, [&sum](int i) { sum += i; }); REQUIRE(sum == 6); } SECTION("std::search") // requires ForwardIterator { std::vector<int> subsequence; subsequence.push_back(2); subsequence.push_back(3); auto found = std::search(beg_it, end_it, subsequence.begin(), subsequence.end()); REQUIRE(found != end_it); } SECTION("std::remove") // requires ForwardIterator { auto past_end = std::remove(beg_it, end_it, 2); auto native_iter = mocklist.begin(); REQUIRE(*beg_it == 1); REQUIRE(native_iter->i == 1); REQUIRE(native_iter->c == 'a'); SECTION("increment to second element") { ++beg_it; ++native_iter; REQUIRE(*beg_it == 3); REQUIRE(native_iter->i == 3); REQUIRE(native_iter->c == 'b'); } } } TEST_CASE("member_iterator based on std::vector::iterator", "[member_iterator]") { struct payload { int i; int get_i() const { return i; } bool operator==(const payload& other) const { return i == other.i; } }; struct mock { double weight; payload value; }; typedef helene::member_iterator<payload, mock, std::vector<mock>::iterator, &mock::value> mockveck_iterator_type; std::vector<mock> mockvec{{0.3, {1}}, {0.4, {2}}, {0.3, {3}}}; mockveck_iterator_type beg_it(mockvec.begin()); mockveck_iterator_type end_it(mockvec.end()); SECTION("category should be random_access_iterator_tag") { bool is_rai = std::is_same< std::iterator_traits<mockveck_iterator_type>::iterator_category, std::random_access_iterator_tag>::value; REQUIRE(is_rai == true); } //////////////////////////////////////////////////////////////////////////// // BidirectionalIterator SECTION("predecrement") { --end_it; REQUIRE(end_it->i == 3); REQUIRE(end_it->get_i() == 3); } SECTION("postdecrement") { end_it--; REQUIRE(end_it->i == 3); REQUIRE(end_it->get_i() == 3); } SECTION("postdecrement and dereference statement") { ++beg_it; auto old = *beg_it--; REQUIRE(old.i == 2); REQUIRE(beg_it->i == 1); } //////////////////////////////////////////////////////////////////////////// // RandomAccesIterator SECTION("+=") { bool is_iter_ref = std::is_same<decltype(beg_it += 2), mockveck_iterator_type&>::value; beg_it += 2; REQUIRE(is_iter_ref == true); REQUIRE(beg_it->i == 3); } SECTION("adding number") { bool is_iter_type = std::is_same<decltype(beg_it + 2), mockveck_iterator_type>::value; bool is_iter_type2 = std::is_same<decltype(2 + beg_it), mockveck_iterator_type>::value; auto res1 = beg_it + 2; auto res2 = 2 + beg_it; REQUIRE(is_iter_type == true); REQUIRE(is_iter_type2 == true); REQUIRE(res1 == res2); REQUIRE(res1->i == 3); REQUIRE(res2->i == 3); } SECTION("-=") { bool is_iter_ref = std::is_same<decltype(end_it -= 2), mockveck_iterator_type&>::value; end_it -= 2; REQUIRE(is_iter_ref == true); REQUIRE(end_it->i == 2); } SECTION("subtracting number") { bool is_iter_type = std::is_same<decltype(end_it - 2), mockveck_iterator_type>::value; auto res1 = end_it - 3; REQUIRE(is_iter_type == true); REQUIRE(res1->i == 1); } SECTION("subtracting two iterators") { bool is_difference_type = std::is_same<decltype(end_it - beg_it), std::iterator_traits< mockveck_iterator_type>::difference_type>::value; REQUIRE(end_it - beg_it == mockvec.size()); } }
Test subtracting two member_iterators. modified: tests/test_member_iterator2.cpp
Test subtracting two member_iterators. modified: tests/test_member_iterator2.cpp
C++
mit
bergesenha/helene
bca24b2e71933385f77771c9668dd64cc227fd4e
chrome/browser/renderer_host/audio_renderer_host_unittest.cc
chrome/browser/renderer_host/audio_renderer_host_unittest.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/process.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "chrome/browser/renderer_host/audio_renderer_host.h" #include "chrome/common/render_messages.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Return; using ::testing::SetArgumentPointee; namespace { const int kInvalidId = -1; const int kProcessId = 100; const int kRouteId = 200; const int kBufferCapacity = 65536; const int kPacketSize = 16384; } // namespace class MockAudioRendererHost : public AudioRendererHost { public: MockAudioRendererHost(MessageLoop* loop) : AudioRendererHost(loop) { } // A list of mock methods. MOCK_METHOD4(OnRequestPacket, void(int routing_id, int stream_id, size_t bytes_in_buffer, int64 message_timestamp)); MOCK_METHOD3(OnStreamCreated, void(int routing_id, int stream_id, int length)); MOCK_METHOD4(OnStreamStateChanged, void(int routing_id, int stream_id, AudioOutputStream::State state, int info)); MOCK_METHOD4(OnStreamVolume, void(int routing_id, int stream_id, double left, double right)); base::SharedMemory* shared_memory() { return shared_memory_.get(); } protected: // This method is used to dispatch IPC messages to the renderer. We intercept // these messages here and dispatch to our mock methods to verify the // conversation between this object and the renderer. virtual void Send(IPC::Message* message) { CHECK(message); // In this method we dispatch the messages to the according handlers as if // we are the renderer. bool handled = true; IPC_BEGIN_MESSAGE_MAP(MockAudioRendererHost, *message) IPC_MESSAGE_HANDLER(ViewMsg_RequestAudioPacket, OnRequestPacket) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamCreated, OnStreamCreated) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamStateChanged, OnStreamStateChanged) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamVolume, OnStreamVolume) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() EXPECT_TRUE(handled); delete message; } private: // These handler methods do minimal things and delegate to the mock methods. void OnRequestPacket(const IPC::Message& msg, int stream_id, size_t bytes_in_buffer, int64 message_timestamp) { OnRequestPacket(msg.routing_id(), stream_id, bytes_in_buffer, message_timestamp); } void OnStreamCreated(const IPC::Message& msg, int stream_id, base::SharedMemoryHandle handle, int length) { // Maps the shared memory. shared_memory_.reset(new base::SharedMemory(handle, true)); CHECK(shared_memory_->Map(length)); CHECK(shared_memory_->memory()); // And then delegate the call to the mock method. OnStreamCreated(msg.routing_id(), stream_id, length); } void OnStreamStateChanged(const IPC::Message& msg, int stream_id, AudioOutputStream::State state, int info) { OnStreamStateChanged(msg.routing_id(), stream_id, state, info); } void OnStreamVolume(const IPC::Message& msg, int stream_id, double left, double right) { OnStreamVolume(msg.routing_id(), stream_id, left, right); } scoped_ptr<base::SharedMemory> shared_memory_; DISALLOW_COPY_AND_ASSIGN(MockAudioRendererHost); }; class AudioRendererHostTest : public testing::Test { public: AudioRendererHostTest() : current_stream_id_(0) { } protected: virtual void SetUp() { // Create a message loop so AudioRendererHost can use it. message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO)); host_ = new MockAudioRendererHost(message_loop_.get()); CHECK(host_); } virtual void TearDown() { // This task post a task to message_loop_ to do internal destruction on // message_loop_. host_->Destroy(); // We need to continue running message_loop_ to complete all destructions. message_loop_->RunAllPending(); } AudioRendererHost::IPCAudioSource* CreateAudioStream( AudioManager::Format format) { InSequence s; // 1. We will first receive a OnStreamCreated() signal. EXPECT_CALL(*host_, OnStreamCreated(kRouteId, current_stream_id_, kPacketSize)); // 2. First packet request will arrive. This request is sent by // IPCAudioSource::CreateIPCAudioSource to start buffering. EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, 0, _)); AudioRendererHost::IPCAudioSource* source = AudioRendererHost::IPCAudioSource::CreateIPCAudioSource( host_, kProcessId, kRouteId, current_stream_id_, base::GetCurrentProcessHandle(), format, 2, AudioManager::kAudioCDSampleRate, 16, kPacketSize, kBufferCapacity); EXPECT_TRUE(source); EXPECT_EQ(kProcessId, source->process_id()); EXPECT_EQ(kRouteId, source->route_id()); EXPECT_EQ(current_stream_id_, source->stream_id()); return source; } AudioRendererHost::IPCAudioSource* CreateRealStream() { return CreateAudioStream(AudioManager::AUDIO_PCM_LINEAR); } AudioRendererHost::IPCAudioSource* CreateMockStream() { return CreateAudioStream(AudioManager::AUDIO_MOCK); } int current_stream_id_; scoped_refptr<MockAudioRendererHost> host_; scoped_ptr<MessageLoop> message_loop_; private: DISALLOW_COPY_AND_ASSIGN(AudioRendererHostTest); }; // Audio output stream only works stably on windows. Also there's no mock // audio output streams for mac and linux. // TODO(hclam): make these tests work on mac and linux. #if defined(OS_WIN) TEST_F(AudioRendererHostTest, CreateMockStream) { scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream()); } TEST_F(AudioRendererHostTest, MockStreamDataConversation) { scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream()); // We will receive packet requests until the buffer is full. We first send // three packets of 16KB, then we send packets of 1KB until the buffer is // full. Then there will no more packet requests. EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, kPacketSize, _)); EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, 2 * kPacketSize, _)); for (int size = 3 * kPacketSize; size < kBufferCapacity; size += 1024) { EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, size, _)); } source->NotifyPacketReady(kPacketSize); source->NotifyPacketReady(kPacketSize); source->NotifyPacketReady(kPacketSize); for (int size = 0; size < kPacketSize; size += 1024) { source->NotifyPacketReady(1024); } } #endif
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/process.h" #include "base/scoped_ptr.h" #include "chrome/browser/renderer_host/audio_renderer_host.h" #include "testing/gtest/include/gtest/gtest.h" class AudioRendererHostTest : public testing::Test { protected: virtual void SetUp() { // Create a message loop so AudioRendererHost can use it. message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO)); host_ = new AudioRendererHost(message_loop_.get()); } virtual void TearDown() { // This task post a task to message_loop_ to do internal destruction on // message_loop_. host_->Destroy(); // We need to continue running message_loop_ to complete all destructions. message_loop_->RunAllPending(); } scoped_refptr<AudioRendererHost> host_; scoped_ptr<MessageLoop> message_loop_; }; TEST_F(AudioRendererHostTest, NoTest) { // TODO(hclam): come up with useful tests. }
Revert "Unit tests for AudioRendererHost"
Revert "Unit tests for AudioRendererHost" TBR=hclam BUG=none TEST=none Review URL: http://codereview.chromium.org/149485 git-svn-id: http://src.chromium.org/svn/trunk/src@20425 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: f68c59b387b5f9c807d31e9119f8307a65f4ff38
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
c173b196d66430d96cd52402707bd874fc2931db
test/cpp/util/cli_credentials.cc
test/cpp/util/cli_credentials.cc
/* * * Copyright 2016 gRPC 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 "test/cpp/util/cli_credentials.h" #include <gflags/gflags.h> DEFINE_bool( enable_ssl, false, "Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl."); DEFINE_bool(use_auth, false, "Whether to create default google credentials. Deprecated. Use " "--channel_creds_type=gdc."); DEFINE_string( access_token, "", "The access token that will be sent to the server to authenticate RPCs."); DEFINE_string( ssl_target, "", "If not empty, treat the server host name as this for ssl/tls certificate " "validation."); DEFINE_string( channel_creds_type, "", "The channel creds type: insecure, ssl, gdc (Google Default Credentials) " "or alts."); namespace grpc { namespace testing { grpc::string CliCredentials::GetDefaultChannelCredsType() const { // Compatibility logic for --enable_ssl. if (FLAGS_enable_ssl) { fprintf(stderr, "warning: --enable_ssl is deprecated. Use " "--channel_creds_type=ssl.\n"); return "ssl"; } // Compatibility logic for --use_auth. if (FLAGS_access_token.empty() && FLAGS_use_auth) { fprintf(stderr, "warning: --use_auth is deprecated. Use " "--channel_creds_type=gdc.\n"); return "gdc"; } return "insecure"; } std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetChannelCredentials() const { if (FLAGS_channel_creds_type.compare("insecure") == 0) { return grpc::InsecureChannelCredentials(); } else if (FLAGS_channel_creds_type.compare("ssl") == 0) { return grpc::SslCredentials(grpc::SslCredentialsOptions()); } else if (FLAGS_channel_creds_type.compare("gdc") == 0) { return grpc::GoogleDefaultCredentials(); } else if (FLAGS_channel_creds_type.compare("alts") == 0) { return grpc::experimental::AltsCredentials( grpc::experimental::AltsCredentialsOptions()); } fprintf(stderr, "--channel_creds_type=%s invalid; must be insecure, ssl, gdc or " "alts.\n", FLAGS_channel_creds_type.c_str()); return std::shared_ptr<grpc::ChannelCredentials>(); } std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials() const { if (!FLAGS_access_token.empty()) { if (FLAGS_use_auth) { fprintf(stderr, "warning: use_auth is ignored when access_token is provided."); } return grpc::AccessTokenCredentials(FLAGS_access_token); } return std::shared_ptr<grpc::CallCredentials>(); } std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials() const { if (FLAGS_channel_creds_type.empty()) { FLAGS_channel_creds_type = GetDefaultChannelCredsType(); } else if (FLAGS_enable_ssl && FLAGS_channel_creds_type.compare("ssl") != 0) { fprintf(stderr, "warning: ignoring --enable_ssl because " "--channel_creds_type already set to %s.\n", FLAGS_channel_creds_type.c_str()); } else if (FLAGS_use_auth && FLAGS_channel_creds_type.compare("gdc") != 0) { fprintf(stderr, "warning: ignoring --use_auth because " "--channel_creds_type already set to %s.\n", FLAGS_channel_creds_type.c_str()); } // Legacy transport upgrade logic for insecure requests. if (!FLAGS_access_token.empty() && FLAGS_channel_creds_type.compare("insecure") == 0) { fprintf(stderr, "warning: --channel_creds_type=insecure upgraded to ssl because " "an access token was provided.\n"); FLAGS_channel_creds_type = "ssl"; } std::shared_ptr<grpc::ChannelCredentials> channel_creds = GetChannelCredentials(); // Composite any call-type credentials on top of the base channel. std::shared_ptr<grpc::CallCredentials> call_creds = GetCallCredentials(); return (channel_creds == nullptr || call_creds == nullptr) ? channel_creds : grpc::CompositeChannelCredentials(channel_creds, call_creds); } const grpc::string CliCredentials::GetCredentialUsage() const { return " --enable_ssl ; Set whether to use ssl (deprecated)\n" " --use_auth ; Set whether to create default google" " credentials\n" " --access_token ; Set the access token in metadata," " overrides --use_auth\n" " --ssl_target ; Set server host for ssl validation\n" " --channel_creds_type ; Set to insecure, ssl, gdc, or alts\n"; } const grpc::string CliCredentials::GetSslTargetNameOverride() const { bool use_ssl = FLAGS_channel_creds_type.compare("ssl") == 0 || FLAGS_channel_creds_type.compare("gdc") == 0; return use_ssl ? FLAGS_ssl_target : ""; } } // namespace testing } // namespace grpc
/* * * Copyright 2016 gRPC 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 "test/cpp/util/cli_credentials.h" #include <gflags/gflags.h> #include <grpc/slice.h> #include <grpc/support/log.h> #include <grpcpp/impl/codegen/slice.h> #include "src/core/lib/iomgr/load_file.h" DEFINE_bool( enable_ssl, false, "Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl."); DEFINE_bool(use_auth, false, "Whether to create default google credentials. Deprecated. Use " "--channel_creds_type=gdc."); DEFINE_string( access_token, "", "The access token that will be sent to the server to authenticate RPCs."); DEFINE_string( ssl_target, "", "If not empty, treat the server host name as this for ssl/tls certificate " "validation."); DEFINE_string( ssl_client_cert, "", "If not empty, load this PEM formated client certificate file. Requires " "use of --ssl_client_key."); DEFINE_string( ssl_client_key, "", "If not empty, load this PEM formated private key. Requires use of " "--ssl_client_cert"); DEFINE_string( channel_creds_type, "", "The channel creds type: insecure, ssl, gdc (Google Default Credentials) " "or alts."); namespace grpc { namespace testing { grpc::string CliCredentials::GetDefaultChannelCredsType() const { // Compatibility logic for --enable_ssl. if (FLAGS_enable_ssl) { fprintf(stderr, "warning: --enable_ssl is deprecated. Use " "--channel_creds_type=ssl.\n"); return "ssl"; } // Compatibility logic for --use_auth. if (FLAGS_access_token.empty() && FLAGS_use_auth) { fprintf(stderr, "warning: --use_auth is deprecated. Use " "--channel_creds_type=gdc.\n"); return "gdc"; } return "insecure"; } std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetChannelCredentials() const { if (FLAGS_channel_creds_type.compare("insecure") == 0) { return grpc::InsecureChannelCredentials(); } else if (FLAGS_channel_creds_type.compare("ssl") == 0) { grpc::SslCredentialsOptions ssl_creds_options; // TODO(@Capstan): This won't affect Google Default Credentials using SSL. if (!FLAGS_ssl_client_cert.empty()) { grpc_slice cert_slice = grpc_empty_slice(); GRPC_LOG_IF_ERROR( "load_file", grpc_load_file(FLAGS_ssl_client_cert.c_str(), 1, &cert_slice)); ssl_creds_options.pem_cert_chain = grpc::StringFromCopiedSlice(cert_slice); grpc_slice_unref(cert_slice); } if (!FLAGS_ssl_client_key.empty()) { grpc_slice key_slice = grpc_empty_slice(); GRPC_LOG_IF_ERROR( "load_file", grpc_load_file(FLAGS_ssl_client_key.c_str(), 1, &key_slice)); ssl_creds_options.pem_private_key = grpc::StringFromCopiedSlice(key_slice); grpc_slice_unref(key_slice); } return grpc::SslCredentials(ssl_creds_options); } else if (FLAGS_channel_creds_type.compare("gdc") == 0) { return grpc::GoogleDefaultCredentials(); } else if (FLAGS_channel_creds_type.compare("alts") == 0) { return grpc::experimental::AltsCredentials( grpc::experimental::AltsCredentialsOptions()); } fprintf(stderr, "--channel_creds_type=%s invalid; must be insecure, ssl, gdc or " "alts.\n", FLAGS_channel_creds_type.c_str()); return std::shared_ptr<grpc::ChannelCredentials>(); } std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials() const { if (!FLAGS_access_token.empty()) { if (FLAGS_use_auth) { fprintf(stderr, "warning: use_auth is ignored when access_token is provided."); } return grpc::AccessTokenCredentials(FLAGS_access_token); } return std::shared_ptr<grpc::CallCredentials>(); } std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials() const { if (FLAGS_channel_creds_type.empty()) { FLAGS_channel_creds_type = GetDefaultChannelCredsType(); } else if (FLAGS_enable_ssl && FLAGS_channel_creds_type.compare("ssl") != 0) { fprintf(stderr, "warning: ignoring --enable_ssl because " "--channel_creds_type already set to %s.\n", FLAGS_channel_creds_type.c_str()); } else if (FLAGS_use_auth && FLAGS_channel_creds_type.compare("gdc") != 0) { fprintf(stderr, "warning: ignoring --use_auth because " "--channel_creds_type already set to %s.\n", FLAGS_channel_creds_type.c_str()); } // Legacy transport upgrade logic for insecure requests. if (!FLAGS_access_token.empty() && FLAGS_channel_creds_type.compare("insecure") == 0) { fprintf(stderr, "warning: --channel_creds_type=insecure upgraded to ssl because " "an access token was provided.\n"); FLAGS_channel_creds_type = "ssl"; } std::shared_ptr<grpc::ChannelCredentials> channel_creds = GetChannelCredentials(); // Composite any call-type credentials on top of the base channel. std::shared_ptr<grpc::CallCredentials> call_creds = GetCallCredentials(); return (channel_creds == nullptr || call_creds == nullptr) ? channel_creds : grpc::CompositeChannelCredentials(channel_creds, call_creds); } const grpc::string CliCredentials::GetCredentialUsage() const { return " --enable_ssl ; Set whether to use ssl (deprecated)\n" " --use_auth ; Set whether to create default google" " credentials\n" " --access_token ; Set the access token in metadata," " overrides --use_auth\n" " --ssl_target ; Set server host for ssl validation\n" " --ssl_client_cert ; Client cert for ssl\n" " --ssl_client_key ; Client private key for ssl\n" " --channel_creds_type ; Set to insecure, ssl, gdc, or alts\n"; } const grpc::string CliCredentials::GetSslTargetNameOverride() const { bool use_ssl = FLAGS_channel_creds_type.compare("ssl") == 0 || FLAGS_channel_creds_type.compare("gdc") == 0; return use_ssl ? FLAGS_ssl_target : ""; } } // namespace testing } // namespace grpc
Add flags to use client certs for cli.
Add flags to use client certs for cli. This allows `grpc_cli` to act with the specific client identity when using SSL. It does _not_ however set the cert when using Google Default Credentials, as it does not have the necessary options to provide a client cert and key.
C++
apache-2.0
vjpai/grpc,ejona86/grpc,firebase/grpc,grpc/grpc,donnadionne/grpc,grpc/grpc,donnadionne/grpc,donnadionne/grpc,stanley-cheung/grpc,pszemus/grpc,ctiller/grpc,stanley-cheung/grpc,vjpai/grpc,pszemus/grpc,nicolasnoble/grpc,sreecha/grpc,jtattermusch/grpc,donnadionne/grpc,jboeuf/grpc,muxi/grpc,carl-mastrangelo/grpc,firebase/grpc,sreecha/grpc,ctiller/grpc,firebase/grpc,mehrdada/grpc,mehrdada/grpc,pszemus/grpc,carl-mastrangelo/grpc,muxi/grpc,grpc/grpc,jboeuf/grpc,ejona86/grpc,pszemus/grpc,nicolasnoble/grpc,nicolasnoble/grpc,ejona86/grpc,ejona86/grpc,jboeuf/grpc,jtattermusch/grpc,pszemus/grpc,ctiller/grpc,vjpai/grpc,ejona86/grpc,donnadionne/grpc,jtattermusch/grpc,pszemus/grpc,carl-mastrangelo/grpc,sreecha/grpc,carl-mastrangelo/grpc,firebase/grpc,grpc/grpc,jtattermusch/grpc,ctiller/grpc,sreecha/grpc,carl-mastrangelo/grpc,muxi/grpc,grpc/grpc,nicolasnoble/grpc,grpc/grpc,vjpai/grpc,nicolasnoble/grpc,carl-mastrangelo/grpc,ctiller/grpc,mehrdada/grpc,firebase/grpc,jtattermusch/grpc,pszemus/grpc,pszemus/grpc,nicolasnoble/grpc,muxi/grpc,sreecha/grpc,ejona86/grpc,pszemus/grpc,ctiller/grpc,ejona86/grpc,sreecha/grpc,donnadionne/grpc,sreecha/grpc,jboeuf/grpc,jboeuf/grpc,jtattermusch/grpc,vjpai/grpc,ctiller/grpc,sreecha/grpc,vjpai/grpc,stanley-cheung/grpc,sreecha/grpc,vjpai/grpc,carl-mastrangelo/grpc,jtattermusch/grpc,pszemus/grpc,donnadionne/grpc,firebase/grpc,sreecha/grpc,mehrdada/grpc,sreecha/grpc,muxi/grpc,jboeuf/grpc,vjpai/grpc,jtattermusch/grpc,ctiller/grpc,jtattermusch/grpc,pszemus/grpc,nicolasnoble/grpc,muxi/grpc,grpc/grpc,jtattermusch/grpc,mehrdada/grpc,stanley-cheung/grpc,muxi/grpc,jboeuf/grpc,jtattermusch/grpc,ejona86/grpc,ejona86/grpc,stanley-cheung/grpc,grpc/grpc,stanley-cheung/grpc,stanley-cheung/grpc,donnadionne/grpc,nicolasnoble/grpc,muxi/grpc,nicolasnoble/grpc,ctiller/grpc,mehrdada/grpc,grpc/grpc,mehrdada/grpc,ctiller/grpc,jboeuf/grpc,firebase/grpc,jtattermusch/grpc,vjpai/grpc,grpc/grpc,nicolasnoble/grpc,carl-mastrangelo/grpc,mehrdada/grpc,firebase/grpc,ctiller/grpc,carl-mastrangelo/grpc,stanley-cheung/grpc,mehrdada/grpc,firebase/grpc,firebase/grpc,donnadionne/grpc,jboeuf/grpc,mehrdada/grpc,pszemus/grpc,jboeuf/grpc,sreecha/grpc,stanley-cheung/grpc,vjpai/grpc,jboeuf/grpc,stanley-cheung/grpc,firebase/grpc,donnadionne/grpc,vjpai/grpc,muxi/grpc,muxi/grpc,stanley-cheung/grpc,donnadionne/grpc,carl-mastrangelo/grpc,firebase/grpc,carl-mastrangelo/grpc,ejona86/grpc,nicolasnoble/grpc,nicolasnoble/grpc,vjpai/grpc,grpc/grpc,mehrdada/grpc,mehrdada/grpc,muxi/grpc,jboeuf/grpc,grpc/grpc,carl-mastrangelo/grpc,ctiller/grpc,ejona86/grpc,ejona86/grpc,stanley-cheung/grpc,muxi/grpc,donnadionne/grpc
7838c9c24f10c03f7b79caf012e86ea39c3258f1
test/data/custombasetype/ref.cpp
test/data/custombasetype/ref.cpp
// Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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. #pragma once #include <string> #include <tixi.h> #include "tigl_internal.h" namespace tigl { class CTiglUIDManager; namespace generated { // This class is used in: // generated from /xsd:schema/xsd:complexType[1] class CPACSBase { public: TIGL_EXPORT CPACSBase(CTiglUIDManager* uidMgr); TIGL_EXPORT virtual ~CPACSBase(); TIGL_EXPORT CTiglUIDManager& GetUIDManager(); TIGL_EXPORT const CTiglUIDManager& GetUIDManager() const; TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath); TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const; TIGL_EXPORT virtual const std::string& GetUID() const; TIGL_EXPORT virtual void SetUID(const std::string& value); protected: CTiglUIDManager* m_uidMgr; std::string m_uID; private: CPACSBase(const CPACSBase&) = delete; CPACSBase& operator=(const CPACSBase&) = delete; CPACSBase(CPACSBase&&) = delete; CPACSBase& operator=(CPACSBase&&) = delete; }; } // namespace generated // CPACSBase is customized, use type CustomCPACSBase directly } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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 "CPACSBase.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglUIDManager.h" #include "TixiHelper.h" namespace tigl { namespace generated { CPACSBase::CPACSBase(CTiglUIDManager* uidMgr) : m_uidMgr(uidMgr) { } CPACSBase::~CPACSBase() { if (m_uidMgr) m_uidMgr->TryUnregisterObject(m_uID); } CTiglUIDManager& CPACSBase::GetUIDManager() { return *m_uidMgr; } const CTiglUIDManager& CPACSBase::GetUIDManager() const { return *m_uidMgr; } void CPACSBase::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { // read attribute uID if (tixi::TixiCheckAttribute(tixiHandle, xpath, "uID")) { m_uID = tixi::TixiGetAttribute<std::string>(tixiHandle, xpath, "uID"); if (m_uID.empty()) { LOG(WARNING) << "Required attribute uID is empty at xpath " << xpath; } } else { LOG(ERROR) << "Required attribute uID is missing at xpath " << xpath; } if (m_uidMgr && !m_uID.empty()) m_uidMgr->RegisterObject(m_uID, *this); } void CPACSBase::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { // write attribute uID tixi::TixiSaveAttribute(tixiHandle, xpath, "uID", m_uID); } const std::string& CPACSBase::GetUID() const { return m_uID; } void CPACSBase::SetUID(const std::string& value) { if (m_uidMgr) { m_uidMgr->TryUnregisterObject(m_uID); m_uidMgr->RegisterObject(value, *this); } m_uID = value; } } // namespace generated } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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. #pragma once #include <boost/optional.hpp> #include <boost/utility/in_place_factory.hpp> #include <CustomCPACSBase.h> #include <string> #include <tixi.h> #include "tigl_internal.h" namespace tigl { class CTiglUIDManager; namespace generated { // This class is used in: // CPACSRoot // generated from /xsd:schema/xsd:complexType[2] class CPACSDerived : public CustomCPACSBase { public: TIGL_EXPORT CPACSDerived(CTiglUIDManager* uidMgr); TIGL_EXPORT virtual ~CPACSDerived(); TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath); TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const; TIGL_EXPORT virtual const boost::optional<std::string>& GetName() const; TIGL_EXPORT virtual void SetName(const boost::optional<std::string>& value); protected: boost::optional<std::string> m_name; private: CPACSDerived(const CPACSDerived&) = delete; CPACSDerived& operator=(const CPACSDerived&) = delete; CPACSDerived(CPACSDerived&&) = delete; CPACSDerived& operator=(CPACSDerived&&) = delete; }; } // namespace generated // CPACSDerived is customized, use type CustomCPACSDerived directly } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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 "CPACSDerived.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglUIDManager.h" #include "TixiHelper.h" namespace tigl { namespace generated { CPACSDerived::CPACSDerived(CTiglUIDManager* uidMgr) : CPACSBase(uidMgr) { } CPACSDerived::~CPACSDerived() { } void CPACSDerived::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { // read base CustomCPACSBase::ReadCPACS(tixiHandle, xpath); // read element name if (tixi::TixiCheckElement(tixiHandle, xpath + "/name")) { m_name = tixi::TixiGetElement<std::string>(tixiHandle, xpath + "/name"); if (m_name->empty()) { LOG(WARNING) << "Optional element name is present but empty at xpath " << xpath; } } } void CPACSDerived::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { // write base CPACSBase::WriteCPACS(tixiHandle, xpath); // write element name if (m_name) { tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/name"); tixi::TixiSaveElement(tixiHandle, xpath + "/name", *m_name); } else { if (tixi::TixiCheckElement(tixiHandle, xpath + "/name")) { tixi::TixiRemoveElement(tixiHandle, xpath + "/name"); } } } const boost::optional<std::string>& CPACSDerived::GetName() const { return m_name; } void CPACSDerived::SetName(const boost::optional<std::string>& value) { m_name = value; } } // namespace generated } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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. #pragma once #include <CustomCPACSDerived.h> #include <string> #include <tixi.h> #include "tigl_internal.h" namespace tigl { class CTiglUIDManager; namespace generated { // This class is used in: // generated from /xsd:schema/xsd:complexType[3] class CPACSRoot { public: TIGL_EXPORT CPACSRoot(CTiglUIDManager* uidMgr); TIGL_EXPORT virtual ~CPACSRoot(); TIGL_EXPORT CTiglUIDManager& GetUIDManager(); TIGL_EXPORT const CTiglUIDManager& GetUIDManager() const; TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath); TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const; TIGL_EXPORT virtual const CustomCPACSDerived& GetA() const; TIGL_EXPORT virtual CustomCPACSDerived& GetA(); protected: CTiglUIDManager* m_uidMgr; CustomCPACSDerived m_a; private: CPACSRoot(const CPACSRoot&) = delete; CPACSRoot& operator=(const CPACSRoot&) = delete; CPACSRoot(CPACSRoot&&) = delete; CPACSRoot& operator=(CPACSRoot&&) = delete; }; } // namespace generated // Aliases in tigl namespace using CCPACSRoot = generated::CPACSRoot; } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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 "CPACSRoot.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglUIDManager.h" #include "TixiHelper.h" namespace tigl { namespace generated { CPACSRoot::CPACSRoot(CTiglUIDManager* uidMgr) : m_uidMgr(uidMgr) , m_a(m_uidMgr) { } CPACSRoot::~CPACSRoot() { } CTiglUIDManager& CPACSRoot::GetUIDManager() { return *m_uidMgr; } const CTiglUIDManager& CPACSRoot::GetUIDManager() const { return *m_uidMgr; } void CPACSRoot::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { // read element a if (tixi::TixiCheckElement(tixiHandle, xpath + "/a")) { m_a.ReadCPACS(tixiHandle, xpath + "/a"); } else { LOG(ERROR) << "Required element a is missing at xpath " << xpath; } } void CPACSRoot::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { // write element a tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/a"); m_a.WriteCPACS(tixiHandle, xpath + "/a"); } const CustomCPACSDerived& CPACSRoot::GetA() const { return m_a; } CustomCPACSDerived& CPACSRoot::GetA() { return m_a; } } // namespace generated } // namespace tigl
// Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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. #pragma once #include <string> #include <tixi.h> #include "tigl_internal.h" namespace tigl { class CTiglUIDManager; namespace generated { // This class is used in: // generated from /xsd:schema/xsd:complexType[1] class CPACSBase { public: TIGL_EXPORT CPACSBase(CTiglUIDManager* uidMgr); TIGL_EXPORT virtual ~CPACSBase(); TIGL_EXPORT CTiglUIDManager& GetUIDManager(); TIGL_EXPORT const CTiglUIDManager& GetUIDManager() const; TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath); TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const; TIGL_EXPORT virtual const std::string& GetUID() const; TIGL_EXPORT virtual void SetUID(const std::string& value); protected: CTiglUIDManager* m_uidMgr; std::string m_uID; private: CPACSBase(const CPACSBase&) = delete; CPACSBase& operator=(const CPACSBase&) = delete; CPACSBase(CPACSBase&&) = delete; CPACSBase& operator=(CPACSBase&&) = delete; }; } // namespace generated // CPACSBase is customized, use type CustomCPACSBase directly } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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 "CPACSBase.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglUIDManager.h" #include "TixiHelper.h" namespace tigl { namespace generated { CPACSBase::CPACSBase(CTiglUIDManager* uidMgr) : m_uidMgr(uidMgr) { } CPACSBase::~CPACSBase() { if (m_uidMgr) m_uidMgr->TryUnregisterObject(m_uID); } CTiglUIDManager& CPACSBase::GetUIDManager() { return *m_uidMgr; } const CTiglUIDManager& CPACSBase::GetUIDManager() const { return *m_uidMgr; } void CPACSBase::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { // read attribute uID if (tixi::TixiCheckAttribute(tixiHandle, xpath, "uID")) { m_uID = tixi::TixiGetAttribute<std::string>(tixiHandle, xpath, "uID"); if (m_uID.empty()) { LOG(WARNING) << "Required attribute uID is empty at xpath " << xpath; } } else { LOG(ERROR) << "Required attribute uID is missing at xpath " << xpath; } if (m_uidMgr && !m_uID.empty()) m_uidMgr->RegisterObject(m_uID, *this); } void CPACSBase::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { // write attribute uID tixi::TixiSaveAttribute(tixiHandle, xpath, "uID", m_uID); } const std::string& CPACSBase::GetUID() const { return m_uID; } void CPACSBase::SetUID(const std::string& value) { if (m_uidMgr) { m_uidMgr->TryUnregisterObject(m_uID); m_uidMgr->RegisterObject(value, *this); } m_uID = value; } } // namespace generated } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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. #pragma once #include <boost/optional.hpp> #include <boost/utility/in_place_factory.hpp> #include <CustomCPACSBase.h> #include <string> #include <tixi.h> #include "tigl_internal.h" namespace tigl { class CTiglUIDManager; namespace generated { // This class is used in: // CPACSRoot // generated from /xsd:schema/xsd:complexType[2] class CPACSDerived : public CustomCPACSBase { public: TIGL_EXPORT CPACSDerived(CTiglUIDManager* uidMgr); TIGL_EXPORT virtual ~CPACSDerived(); TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath); TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const; TIGL_EXPORT virtual const boost::optional<std::string>& GetName() const; TIGL_EXPORT virtual void SetName(const boost::optional<std::string>& value); protected: boost::optional<std::string> m_name; private: CPACSDerived(const CPACSDerived&) = delete; CPACSDerived& operator=(const CPACSDerived&) = delete; CPACSDerived(CPACSDerived&&) = delete; CPACSDerived& operator=(CPACSDerived&&) = delete; }; } // namespace generated // CPACSDerived is customized, use type CustomCPACSDerived directly } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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 "CPACSDerived.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglUIDManager.h" #include "TixiHelper.h" namespace tigl { namespace generated { CPACSDerived::CPACSDerived(CTiglUIDManager* uidMgr) : CPACSBase(uidMgr) { } CPACSDerived::~CPACSDerived() { } void CPACSDerived::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { // read base CustomCPACSBase::ReadCPACS(tixiHandle, xpath); // read element name if (tixi::TixiCheckElement(tixiHandle, xpath + "/name")) { m_name = tixi::TixiGetElement<std::string>(tixiHandle, xpath + "/name"); if (m_name->empty()) { LOG(WARNING) << "Optional element name is present but empty at xpath " << xpath; } } } void CPACSDerived::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { // write base CustomCPACSBase::WriteCPACS(tixiHandle, xpath); // write element name if (m_name) { tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/name"); tixi::TixiSaveElement(tixiHandle, xpath + "/name", *m_name); } else { if (tixi::TixiCheckElement(tixiHandle, xpath + "/name")) { tixi::TixiRemoveElement(tixiHandle, xpath + "/name"); } } } const boost::optional<std::string>& CPACSDerived::GetName() const { return m_name; } void CPACSDerived::SetName(const boost::optional<std::string>& value) { m_name = value; } } // namespace generated } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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. #pragma once #include <CustomCPACSDerived.h> #include <string> #include <tixi.h> #include "tigl_internal.h" namespace tigl { class CTiglUIDManager; namespace generated { // This class is used in: // generated from /xsd:schema/xsd:complexType[3] class CPACSRoot { public: TIGL_EXPORT CPACSRoot(CTiglUIDManager* uidMgr); TIGL_EXPORT virtual ~CPACSRoot(); TIGL_EXPORT CTiglUIDManager& GetUIDManager(); TIGL_EXPORT const CTiglUIDManager& GetUIDManager() const; TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath); TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const; TIGL_EXPORT virtual const CustomCPACSDerived& GetA() const; TIGL_EXPORT virtual CustomCPACSDerived& GetA(); protected: CTiglUIDManager* m_uidMgr; CustomCPACSDerived m_a; private: CPACSRoot(const CPACSRoot&) = delete; CPACSRoot& operator=(const CPACSRoot&) = delete; CPACSRoot(CPACSRoot&&) = delete; CPACSRoot& operator=(CPACSRoot&&) = delete; }; } // namespace generated // Aliases in tigl namespace using CCPACSRoot = generated::CPACSRoot; } // namespace tigl // Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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 "CPACSRoot.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglUIDManager.h" #include "TixiHelper.h" namespace tigl { namespace generated { CPACSRoot::CPACSRoot(CTiglUIDManager* uidMgr) : m_uidMgr(uidMgr) , m_a(m_uidMgr) { } CPACSRoot::~CPACSRoot() { } CTiglUIDManager& CPACSRoot::GetUIDManager() { return *m_uidMgr; } const CTiglUIDManager& CPACSRoot::GetUIDManager() const { return *m_uidMgr; } void CPACSRoot::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { // read element a if (tixi::TixiCheckElement(tixiHandle, xpath + "/a")) { m_a.ReadCPACS(tixiHandle, xpath + "/a"); } else { LOG(ERROR) << "Required element a is missing at xpath " << xpath; } } void CPACSRoot::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { // write element a tixi::TixiCreateElementIfNotExists(tixiHandle, xpath + "/a"); m_a.WriteCPACS(tixiHandle, xpath + "/a"); } const CustomCPACSDerived& CPACSRoot::GetA() const { return m_a; } CustomCPACSDerived& CPACSRoot::GetA() { return m_a; } } // namespace generated } // namespace tigl
fix for incorrect test reference result for #32
fix for incorrect test reference result for #32
C++
apache-2.0
RlanderRISCSW/cpacs_tigl_gen
65ac0eab1823560c60ff29d5b413aa571fd612c8
lib/Sema/NameBinding.cpp
lib/Sema/NameBinding.cpp
//===--- NameBinding.cpp - Name Binding -----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements name binding for Swift. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTWalker.h" #include "swift/AST/DiagnosticsSema.h" #include "swift/AST/ModuleLoader.h" #include "swift/AST/NameLookup.h" #include "swift/ClangImporter/ClangModule.h" #include "swift/Parse/Parser.h" #include "swift/Subsystems.h" #include "clang/Basic/Module.h" #include "clang/Basic/Statistics.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" #include <algorithm> #include <system_error> using namespace swift; //===----------------------------------------------------------------------===// // NameBinder //===----------------------------------------------------------------------===// using ImportedModule = ModuleDecl::ImportedModule; using ImportOptions = SourceFile::ImportOptions; namespace { class NameBinder { public: SourceFile &SF; ASTContext &Context; NameBinder(SourceFile &SF) : SF(SF), Context(SF.getASTContext()) {} template<typename ...ArgTypes> InFlightDiagnostic diagnose(ArgTypes &&...Args) { return Context.Diags.diagnose(std::forward<ArgTypes>(Args)...); } void addImport( SmallVectorImpl<std::pair<ImportedModule, ImportOptions>> &imports, ImportDecl *ID); /// Load a module referenced by an import statement. /// /// Returns null if no module can be loaded. ModuleDecl *getModule(ArrayRef<std::pair<Identifier,SourceLoc>> ModuleID); }; } // end anonymous namespace ModuleDecl * NameBinder::getModule(ArrayRef<std::pair<Identifier, SourceLoc>> modulePath) { assert(!modulePath.empty()); auto moduleID = modulePath[0]; // The Builtin module cannot be explicitly imported unless we're a .sil file // or in the REPL. if ((SF.Kind == SourceFileKind::SIL || SF.Kind == SourceFileKind::REPL) && moduleID.first == Context.TheBuiltinModule->getName()) return Context.TheBuiltinModule; // If the imported module name is the same as the current module, // skip the Swift module loader and use the Clang module loader instead. // This allows a Swift module to extend a Clang module of the same name. // // FIXME: We'd like to only use this in SIL mode, but unfortunately we use it // for our fake overlays as well. if (moduleID.first == SF.getParentModule()->getName() && modulePath.size() == 1) { if (auto importer = Context.getClangModuleLoader()) return importer->loadModule(moduleID.second, modulePath); return nullptr; } return Context.getModule(modulePath); } /// Returns true if a decl with the given \p actual kind can legally be /// imported via the given \p expected kind. static bool isCompatibleImportKind(ImportKind expected, ImportKind actual) { if (expected == actual) return true; if (expected != ImportKind::Type) return false; switch (actual) { case ImportKind::Module: llvm_unreachable("module imports do not bring in decls"); case ImportKind::Type: llvm_unreachable("individual decls cannot have abstract import kind"); case ImportKind::Struct: case ImportKind::Class: case ImportKind::Enum: return true; case ImportKind::Protocol: case ImportKind::Var: case ImportKind::Func: return false; } llvm_unreachable("Unhandled ImportKind in switch."); } static const char *getImportKindString(ImportKind kind) { switch (kind) { case ImportKind::Module: llvm_unreachable("module imports do not bring in decls"); case ImportKind::Type: return "typealias"; case ImportKind::Struct: return "struct"; case ImportKind::Class: return "class"; case ImportKind::Enum: return "enum"; case ImportKind::Protocol: return "protocol"; case ImportKind::Var: return "var"; case ImportKind::Func: return "func"; } llvm_unreachable("Unhandled ImportKind in switch."); } static bool shouldImportSelfImportClang(const ImportDecl *ID, const SourceFile &SF) { // FIXME: We use '@_exported' for fake overlays in testing. if (ID->isExported()) return true; if (SF.Kind == SourceFileKind::SIL) return true; return false; } void NameBinder::addImport( SmallVectorImpl<std::pair<ImportedModule, ImportOptions>> &imports, ImportDecl *ID) { if (ID->getModulePath().front().first == SF.getParentModule()->getName() && ID->getModulePath().size() == 1 && !shouldImportSelfImportClang(ID, SF)) { // If the imported module name is the same as the current module, // produce a diagnostic. StringRef filename = llvm::sys::path::filename(SF.getFilename()); if (filename.empty()) Context.Diags.diagnose(ID, diag::sema_import_current_module, ID->getModulePath().front().first); else Context.Diags.diagnose(ID, diag::sema_import_current_module_with_file, filename, ID->getModulePath().front().first); ID->setModule(SF.getParentModule()); return; } ModuleDecl *M = getModule(ID->getModulePath()); if (!M) { SmallString<64> modulePathStr; interleave(ID->getModulePath(), [&](ImportDecl::AccessPathElement elem) { modulePathStr += elem.first.str(); }, [&] { modulePathStr += "."; }); auto diagKind = diag::sema_no_import; if (SF.Kind == SourceFileKind::REPL || Context.LangOpts.DebuggerSupport) diagKind = diag::sema_no_import_repl; diagnose(ID->getLoc(), diagKind, modulePathStr); if (Context.SearchPathOpts.SDKPath.empty() && llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) { diagnose(SourceLoc(), diag::sema_no_import_no_sdk); diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun); } return; } ID->setModule(M); ModuleDecl *topLevelModule; if (ID->getModulePath().size() == 1) { topLevelModule = M; } else { // If we imported a submodule, import the top-level module as well. Identifier topLevelName = ID->getModulePath().front().first; topLevelModule = Context.getLoadedModule(topLevelName); assert(topLevelModule && "top-level module missing"); } auto *testableAttr = ID->getAttrs().getAttribute<TestableAttr>(); if (testableAttr && !topLevelModule->isTestingEnabled() && Context.LangOpts.EnableTestableAttrRequiresTestableModule) { diagnose(ID->getModulePath().front().second, diag::module_not_testable, topLevelModule->getName()); testableAttr->setInvalid(); } ImportOptions options; if (ID->isExported()) options |= SourceFile::ImportFlags::Exported; if (testableAttr) options |= SourceFile::ImportFlags::Testable; imports.push_back({ { ID->getDeclPath(), M }, options }); if (topLevelModule != M) imports.push_back({ { ID->getDeclPath(), topLevelModule }, options }); if (ID->getImportKind() != ImportKind::Module) { // If we're importing a specific decl, validate the import kind. using namespace namelookup; auto declPath = ID->getDeclPath(); // FIXME: Doesn't handle scoped testable imports correctly. assert(declPath.size() == 1 && "can't handle sub-decl imports"); SmallVector<ValueDecl *, 8> decls; lookupInModule(topLevelModule, declPath, declPath.front().first, decls, NLKind::QualifiedLookup, ResolutionKind::Overloadable, /*resolver*/nullptr, &SF); if (decls.empty()) { diagnose(ID, diag::decl_does_not_exist_in_module, static_cast<unsigned>(ID->getImportKind()), declPath.front().first, ID->getModulePath().front().first) .highlight(SourceRange(declPath.front().second, declPath.back().second)); return; } ID->setDecls(Context.AllocateCopy(decls)); Optional<ImportKind> actualKind = ImportDecl::findBestImportKind(decls); if (!actualKind.hasValue()) { // FIXME: print entire module name? diagnose(ID, diag::ambiguous_decl_in_module, declPath.front().first, M->getName()); for (auto next : decls) diagnose(next, diag::found_candidate); } else if (!isCompatibleImportKind(ID->getImportKind(), *actualKind)) { diagnose(ID, diag::imported_decl_is_wrong_kind, declPath.front().first, getImportKindString(ID->getImportKind()), static_cast<unsigned>(*actualKind)) .fixItReplace(SourceRange(ID->getKindLoc()), getImportKindString(*actualKind)); if (decls.size() == 1) diagnose(decls.front(), diag::decl_declared_here, decls.front()->getFullName()); } } } //===----------------------------------------------------------------------===// // performNameBinding //===----------------------------------------------------------------------===// template<typename OP_DECL> static void insertOperatorDecl(NameBinder &Binder, SourceFile::OperatorMap<OP_DECL*> &Operators, OP_DECL *OpDecl) { auto previousDecl = Operators.find(OpDecl->getName()); if (previousDecl != Operators.end()) { Binder.diagnose(OpDecl->getLoc(), diag::operator_redeclared); Binder.diagnose(previousDecl->second.getPointer(), diag::previous_operator_decl); return; } // FIXME: The second argument indicates whether the given operator is visible // outside the current file. Operators[OpDecl->getName()] = { OpDecl, true }; } static void insertPrecedenceGroupDecl(NameBinder &binder, SourceFile &SF, PrecedenceGroupDecl *group) { auto previousDecl = SF.PrecedenceGroups.find(group->getName()); if (previousDecl != SF.PrecedenceGroups.end()) { binder.diagnose(group->getLoc(), diag::precedence_group_redeclared); binder.diagnose(previousDecl->second.getPointer(), diag::previous_precedence_group_decl); return; } // FIXME: The second argument indicates whether the given precedence // group is visible outside the current file. SF.PrecedenceGroups[group->getName()] = { group, true }; } /// performNameBinding - Once parsing is complete, this walks the AST to /// resolve names and do other top-level validation. /// /// At this parsing has been performed, but we still have UnresolvedDeclRefExpr /// nodes for unresolved value names, and we may have unresolved type names as /// well. This handles import directives and forward references. void swift::performNameBinding(SourceFile &SF, unsigned StartElem) { SharedTimer timer("Name binding"); // Make sure we skip adding the standard library imports if the // source file is empty. if (SF.ASTStage == SourceFile::NameBound || SF.Decls.empty()) { SF.ASTStage = SourceFile::NameBound; return; } // Reset the name lookup cache so we find new decls. // FIXME: This is inefficient. SF.clearLookupCache(); NameBinder Binder(SF); SmallVector<std::pair<ImportedModule, ImportOptions>, 8> ImportedModules; // Do a prepass over the declarations to find and load the imported modules // and map operator decls. for (auto D : llvm::makeArrayRef(SF.Decls).slice(StartElem)) { if (auto *ID = dyn_cast<ImportDecl>(D)) { Binder.addImport(ImportedModules, ID); } else if (auto *OD = dyn_cast<PrefixOperatorDecl>(D)) { insertOperatorDecl(Binder, SF.PrefixOperators, OD); } else if (auto *OD = dyn_cast<PostfixOperatorDecl>(D)) { insertOperatorDecl(Binder, SF.PostfixOperators, OD); } else if (auto *OD = dyn_cast<InfixOperatorDecl>(D)) { insertOperatorDecl(Binder, SF.InfixOperators, OD); } else if (auto *PGD = dyn_cast<PrecedenceGroupDecl>(D)) { insertPrecedenceGroupDecl(Binder, SF, PGD); } } SF.addImports(ImportedModules); SF.ASTStage = SourceFile::NameBound; verify(SF); }
//===--- NameBinding.cpp - Name Binding -----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements name binding for Swift. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTWalker.h" #include "swift/AST/DiagnosticsSema.h" #include "swift/AST/ModuleLoader.h" #include "swift/AST/NameLookup.h" #include "swift/Basic/Statistic.h" #include "swift/ClangImporter/ClangModule.h" #include "swift/Parse/Parser.h" #include "swift/Subsystems.h" #include "clang/Basic/Module.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" #include <algorithm> #include <system_error> using namespace swift; //===----------------------------------------------------------------------===// // NameBinder //===----------------------------------------------------------------------===// using ImportedModule = ModuleDecl::ImportedModule; using ImportOptions = SourceFile::ImportOptions; namespace { class NameBinder { public: SourceFile &SF; ASTContext &Context; NameBinder(SourceFile &SF) : SF(SF), Context(SF.getASTContext()) {} template<typename ...ArgTypes> InFlightDiagnostic diagnose(ArgTypes &&...Args) { return Context.Diags.diagnose(std::forward<ArgTypes>(Args)...); } void addImport( SmallVectorImpl<std::pair<ImportedModule, ImportOptions>> &imports, ImportDecl *ID); /// Load a module referenced by an import statement. /// /// Returns null if no module can be loaded. ModuleDecl *getModule(ArrayRef<std::pair<Identifier,SourceLoc>> ModuleID); }; } // end anonymous namespace ModuleDecl * NameBinder::getModule(ArrayRef<std::pair<Identifier, SourceLoc>> modulePath) { assert(!modulePath.empty()); auto moduleID = modulePath[0]; // The Builtin module cannot be explicitly imported unless we're a .sil file // or in the REPL. if ((SF.Kind == SourceFileKind::SIL || SF.Kind == SourceFileKind::REPL) && moduleID.first == Context.TheBuiltinModule->getName()) return Context.TheBuiltinModule; // If the imported module name is the same as the current module, // skip the Swift module loader and use the Clang module loader instead. // This allows a Swift module to extend a Clang module of the same name. // // FIXME: We'd like to only use this in SIL mode, but unfortunately we use it // for our fake overlays as well. if (moduleID.first == SF.getParentModule()->getName() && modulePath.size() == 1) { if (auto importer = Context.getClangModuleLoader()) return importer->loadModule(moduleID.second, modulePath); return nullptr; } return Context.getModule(modulePath); } /// Returns true if a decl with the given \p actual kind can legally be /// imported via the given \p expected kind. static bool isCompatibleImportKind(ImportKind expected, ImportKind actual) { if (expected == actual) return true; if (expected != ImportKind::Type) return false; switch (actual) { case ImportKind::Module: llvm_unreachable("module imports do not bring in decls"); case ImportKind::Type: llvm_unreachable("individual decls cannot have abstract import kind"); case ImportKind::Struct: case ImportKind::Class: case ImportKind::Enum: return true; case ImportKind::Protocol: case ImportKind::Var: case ImportKind::Func: return false; } llvm_unreachable("Unhandled ImportKind in switch."); } static const char *getImportKindString(ImportKind kind) { switch (kind) { case ImportKind::Module: llvm_unreachable("module imports do not bring in decls"); case ImportKind::Type: return "typealias"; case ImportKind::Struct: return "struct"; case ImportKind::Class: return "class"; case ImportKind::Enum: return "enum"; case ImportKind::Protocol: return "protocol"; case ImportKind::Var: return "var"; case ImportKind::Func: return "func"; } llvm_unreachable("Unhandled ImportKind in switch."); } static bool shouldImportSelfImportClang(const ImportDecl *ID, const SourceFile &SF) { // FIXME: We use '@_exported' for fake overlays in testing. if (ID->isExported()) return true; if (SF.Kind == SourceFileKind::SIL) return true; return false; } void NameBinder::addImport( SmallVectorImpl<std::pair<ImportedModule, ImportOptions>> &imports, ImportDecl *ID) { if (ID->getModulePath().front().first == SF.getParentModule()->getName() && ID->getModulePath().size() == 1 && !shouldImportSelfImportClang(ID, SF)) { // If the imported module name is the same as the current module, // produce a diagnostic. StringRef filename = llvm::sys::path::filename(SF.getFilename()); if (filename.empty()) Context.Diags.diagnose(ID, diag::sema_import_current_module, ID->getModulePath().front().first); else Context.Diags.diagnose(ID, diag::sema_import_current_module_with_file, filename, ID->getModulePath().front().first); ID->setModule(SF.getParentModule()); return; } ModuleDecl *M = getModule(ID->getModulePath()); if (!M) { SmallString<64> modulePathStr; interleave(ID->getModulePath(), [&](ImportDecl::AccessPathElement elem) { modulePathStr += elem.first.str(); }, [&] { modulePathStr += "."; }); auto diagKind = diag::sema_no_import; if (SF.Kind == SourceFileKind::REPL || Context.LangOpts.DebuggerSupport) diagKind = diag::sema_no_import_repl; diagnose(ID->getLoc(), diagKind, modulePathStr); if (Context.SearchPathOpts.SDKPath.empty() && llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) { diagnose(SourceLoc(), diag::sema_no_import_no_sdk); diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun); } return; } ID->setModule(M); ModuleDecl *topLevelModule; if (ID->getModulePath().size() == 1) { topLevelModule = M; } else { // If we imported a submodule, import the top-level module as well. Identifier topLevelName = ID->getModulePath().front().first; topLevelModule = Context.getLoadedModule(topLevelName); assert(topLevelModule && "top-level module missing"); } auto *testableAttr = ID->getAttrs().getAttribute<TestableAttr>(); if (testableAttr && !topLevelModule->isTestingEnabled() && Context.LangOpts.EnableTestableAttrRequiresTestableModule) { diagnose(ID->getModulePath().front().second, diag::module_not_testable, topLevelModule->getName()); testableAttr->setInvalid(); } ImportOptions options; if (ID->isExported()) options |= SourceFile::ImportFlags::Exported; if (testableAttr) options |= SourceFile::ImportFlags::Testable; imports.push_back({ { ID->getDeclPath(), M }, options }); if (topLevelModule != M) imports.push_back({ { ID->getDeclPath(), topLevelModule }, options }); if (ID->getImportKind() != ImportKind::Module) { // If we're importing a specific decl, validate the import kind. using namespace namelookup; auto declPath = ID->getDeclPath(); // FIXME: Doesn't handle scoped testable imports correctly. assert(declPath.size() == 1 && "can't handle sub-decl imports"); SmallVector<ValueDecl *, 8> decls; lookupInModule(topLevelModule, declPath, declPath.front().first, decls, NLKind::QualifiedLookup, ResolutionKind::Overloadable, /*resolver*/nullptr, &SF); if (decls.empty()) { diagnose(ID, diag::decl_does_not_exist_in_module, static_cast<unsigned>(ID->getImportKind()), declPath.front().first, ID->getModulePath().front().first) .highlight(SourceRange(declPath.front().second, declPath.back().second)); return; } ID->setDecls(Context.AllocateCopy(decls)); Optional<ImportKind> actualKind = ImportDecl::findBestImportKind(decls); if (!actualKind.hasValue()) { // FIXME: print entire module name? diagnose(ID, diag::ambiguous_decl_in_module, declPath.front().first, M->getName()); for (auto next : decls) diagnose(next, diag::found_candidate); } else if (!isCompatibleImportKind(ID->getImportKind(), *actualKind)) { diagnose(ID, diag::imported_decl_is_wrong_kind, declPath.front().first, getImportKindString(ID->getImportKind()), static_cast<unsigned>(*actualKind)) .fixItReplace(SourceRange(ID->getKindLoc()), getImportKindString(*actualKind)); if (decls.size() == 1) diagnose(decls.front(), diag::decl_declared_here, decls.front()->getFullName()); } } } //===----------------------------------------------------------------------===// // performNameBinding //===----------------------------------------------------------------------===// template<typename OP_DECL> static void insertOperatorDecl(NameBinder &Binder, SourceFile::OperatorMap<OP_DECL*> &Operators, OP_DECL *OpDecl) { auto previousDecl = Operators.find(OpDecl->getName()); if (previousDecl != Operators.end()) { Binder.diagnose(OpDecl->getLoc(), diag::operator_redeclared); Binder.diagnose(previousDecl->second.getPointer(), diag::previous_operator_decl); return; } // FIXME: The second argument indicates whether the given operator is visible // outside the current file. Operators[OpDecl->getName()] = { OpDecl, true }; } static void insertPrecedenceGroupDecl(NameBinder &binder, SourceFile &SF, PrecedenceGroupDecl *group) { auto previousDecl = SF.PrecedenceGroups.find(group->getName()); if (previousDecl != SF.PrecedenceGroups.end()) { binder.diagnose(group->getLoc(), diag::precedence_group_redeclared); binder.diagnose(previousDecl->second.getPointer(), diag::previous_precedence_group_decl); return; } // FIXME: The second argument indicates whether the given precedence // group is visible outside the current file. SF.PrecedenceGroups[group->getName()] = { group, true }; } /// performNameBinding - Once parsing is complete, this walks the AST to /// resolve names and do other top-level validation. /// /// At this parsing has been performed, but we still have UnresolvedDeclRefExpr /// nodes for unresolved value names, and we may have unresolved type names as /// well. This handles import directives and forward references. void swift::performNameBinding(SourceFile &SF, unsigned StartElem) { SharedTimer timer("Name binding"); // Make sure we skip adding the standard library imports if the // source file is empty. if (SF.ASTStage == SourceFile::NameBound || SF.Decls.empty()) { SF.ASTStage = SourceFile::NameBound; return; } // Reset the name lookup cache so we find new decls. // FIXME: This is inefficient. SF.clearLookupCache(); NameBinder Binder(SF); SmallVector<std::pair<ImportedModule, ImportOptions>, 8> ImportedModules; // Do a prepass over the declarations to find and load the imported modules // and map operator decls. for (auto D : llvm::makeArrayRef(SF.Decls).slice(StartElem)) { if (auto *ID = dyn_cast<ImportDecl>(D)) { Binder.addImport(ImportedModules, ID); } else if (auto *OD = dyn_cast<PrefixOperatorDecl>(D)) { insertOperatorDecl(Binder, SF.PrefixOperators, OD); } else if (auto *OD = dyn_cast<PostfixOperatorDecl>(D)) { insertOperatorDecl(Binder, SF.PostfixOperators, OD); } else if (auto *OD = dyn_cast<InfixOperatorDecl>(D)) { insertOperatorDecl(Binder, SF.InfixOperators, OD); } else if (auto *PGD = dyn_cast<PrecedenceGroupDecl>(D)) { insertPrecedenceGroupDecl(Binder, SF, PGD); } } SF.addImports(ImportedModules); SF.ASTStage = SourceFile::NameBound; verify(SF); }
Fix include file name.
Fix include file name.
C++
apache-2.0
shahmishal/swift,sschiau/swift,nathawes/swift,zisko/swift,hooman/swift,natecook1000/swift,glessard/swift,nathawes/swift,allevato/swift,allevato/swift,frootloops/swift,glessard/swift,CodaFi/swift,hooman/swift,rudkx/swift,roambotics/swift,harlanhaskins/swift,gregomni/swift,karwa/swift,gribozavr/swift,sschiau/swift,lorentey/swift,parkera/swift,stephentyrone/swift,atrick/swift,gregomni/swift,danielmartin/swift,jmgc/swift,practicalswift/swift,devincoughlin/swift,xwu/swift,natecook1000/swift,aschwaighofer/swift,stephentyrone/swift,stephentyrone/swift,xedin/swift,CodaFi/swift,glessard/swift,JGiola/swift,parkera/swift,allevato/swift,hooman/swift,apple/swift,roambotics/swift,aschwaighofer/swift,huonw/swift,austinzheng/swift,harlanhaskins/swift,brentdax/swift,sschiau/swift,frootloops/swift,shajrawi/swift,xedin/swift,xwu/swift,zisko/swift,airspeedswift/swift,hooman/swift,tjw/swift,shajrawi/swift,practicalswift/swift,parkera/swift,gregomni/swift,swiftix/swift,frootloops/swift,jckarter/swift,shahmishal/swift,tjw/swift,swiftix/swift,benlangmuir/swift,austinzheng/swift,danielmartin/swift,zisko/swift,sschiau/swift,airspeedswift/swift,danielmartin/swift,OscarSwanros/swift,JGiola/swift,rudkx/swift,brentdax/swift,tkremenek/swift,shajrawi/swift,brentdax/swift,jckarter/swift,apple/swift,danielmartin/swift,alblue/swift,apple/swift,sschiau/swift,swiftix/swift,practicalswift/swift,sschiau/swift,lorentey/swift,karwa/swift,huonw/swift,benlangmuir/swift,swiftix/swift,xwu/swift,xwu/swift,amraboelela/swift,shajrawi/swift,OscarSwanros/swift,swiftix/swift,OscarSwanros/swift,xedin/swift,lorentey/swift,nathawes/swift,xedin/swift,danielmartin/swift,ahoppen/swift,benlangmuir/swift,airspeedswift/swift,xedin/swift,karwa/swift,jopamer/swift,shahmishal/swift,tkremenek/swift,aschwaighofer/swift,ahoppen/swift,airspeedswift/swift,jopamer/swift,huonw/swift,lorentey/swift,frootloops/swift,airspeedswift/swift,harlanhaskins/swift,huonw/swift,CodaFi/swift,atrick/swift,atrick/swift,parkera/swift,gregomni/swift,glessard/swift,rudkx/swift,shahmishal/swift,brentdax/swift,airspeedswift/swift,JGiola/swift,amraboelela/swift,amraboelela/swift,OscarSwanros/swift,karwa/swift,JGiola/swift,allevato/swift,CodaFi/swift,hooman/swift,aschwaighofer/swift,nathawes/swift,huonw/swift,roambotics/swift,xedin/swift,austinzheng/swift,allevato/swift,amraboelela/swift,nathawes/swift,lorentey/swift,parkera/swift,parkera/swift,aschwaighofer/swift,gribozavr/swift,harlanhaskins/swift,benlangmuir/swift,swiftix/swift,devincoughlin/swift,apple/swift,harlanhaskins/swift,shahmishal/swift,alblue/swift,tjw/swift,jckarter/swift,natecook1000/swift,ahoppen/swift,jopamer/swift,tkremenek/swift,zisko/swift,ahoppen/swift,swiftix/swift,tjw/swift,harlanhaskins/swift,jmgc/swift,shahmishal/swift,allevato/swift,roambotics/swift,sschiau/swift,devincoughlin/swift,danielmartin/swift,xedin/swift,gregomni/swift,brentdax/swift,gribozavr/swift,karwa/swift,xwu/swift,jopamer/swift,gribozavr/swift,jckarter/swift,karwa/swift,jmgc/swift,devincoughlin/swift,parkera/swift,lorentey/swift,austinzheng/swift,rudkx/swift,ahoppen/swift,frootloops/swift,gribozavr/swift,gregomni/swift,shahmishal/swift,natecook1000/swift,atrick/swift,jckarter/swift,zisko/swift,airspeedswift/swift,OscarSwanros/swift,xwu/swift,devincoughlin/swift,hooman/swift,tkremenek/swift,glessard/swift,jmgc/swift,harlanhaskins/swift,lorentey/swift,karwa/swift,OscarSwanros/swift,alblue/swift,huonw/swift,shahmishal/swift,jopamer/swift,tjw/swift,gribozavr/swift,devincoughlin/swift,atrick/swift,austinzheng/swift,stephentyrone/swift,zisko/swift,natecook1000/swift,gribozavr/swift,jckarter/swift,amraboelela/swift,tkremenek/swift,alblue/swift,glessard/swift,jopamer/swift,stephentyrone/swift,lorentey/swift,atrick/swift,rudkx/swift,alblue/swift,stephentyrone/swift,amraboelela/swift,sschiau/swift,aschwaighofer/swift,alblue/swift,tkremenek/swift,brentdax/swift,tkremenek/swift,jopamer/swift,xwu/swift,benlangmuir/swift,JGiola/swift,austinzheng/swift,practicalswift/swift,roambotics/swift,shajrawi/swift,danielmartin/swift,austinzheng/swift,CodaFi/swift,brentdax/swift,benlangmuir/swift,jmgc/swift,practicalswift/swift,jmgc/swift,devincoughlin/swift,gribozavr/swift,practicalswift/swift,tjw/swift,practicalswift/swift,allevato/swift,practicalswift/swift,natecook1000/swift,natecook1000/swift,CodaFi/swift,aschwaighofer/swift,shajrawi/swift,alblue/swift,frootloops/swift,JGiola/swift,shajrawi/swift,zisko/swift,nathawes/swift,jmgc/swift,frootloops/swift,OscarSwanros/swift,jckarter/swift,roambotics/swift,nathawes/swift,hooman/swift,amraboelela/swift,tjw/swift,CodaFi/swift,shajrawi/swift,rudkx/swift,karwa/swift,ahoppen/swift,apple/swift,stephentyrone/swift,huonw/swift,xedin/swift,apple/swift,devincoughlin/swift,parkera/swift
63a008d0676e0561504dbd71d8ff0e80c02f2870
src/manager.cpp
src/manager.cpp
#include "manager.h" #include "capturer.h" #include "corrector.h" #include "debug.h" #include "recognizer.h" #include "representer.h" #include "settingseditor.h" #include "task.h" #include "translator.h" #include "trayicon.h" #include "updates.h" #include <QApplication> #include <QDesktopServices> #include <QFileInfo> #include <QMessageBox> #include <QNetworkProxy> #include <QThread> namespace { #ifdef DEVELOP const auto updatesUrl = "http://localhost:8081/updates.json"; #else const auto updatesUrl = "https://raw.githubusercontent.com/OneMoreGres/ScreenTranslator/master/" "updates.json"; #endif const auto resultHideWaitUs = 300'000; } // namespace using Loader = update::Loader; Manager::Manager() : settings_(std::make_unique<Settings>()) , updater_(std::make_unique<Loader>(Loader::Urls{{updatesUrl}})) , updateAutoChecker_(std::make_unique<update::AutoChecker>(*updater_)) , models_(std::make_unique<CommonModels>()) { SOFT_ASSERT(settings_, return ); // updater components (void)QT_TRANSLATE_NOOP("QObject", "app"); (void)QT_TRANSLATE_NOOP("QObject", "recognizers"); (void)QT_TRANSLATE_NOOP("QObject", "hunspell"); (void)QT_TRANSLATE_NOOP("QObject", "translators"); tray_ = std::make_unique<TrayIcon>(*this, *settings_); capturer_ = std::make_unique<Capturer>(*this, *settings_, *models_); recognizer_ = std::make_unique<Recognizer>(*this, *settings_); translator_ = std::make_unique<Translator>(*this, *settings_); corrector_ = std::make_unique<Corrector>(*this, *settings_); representer_ = std::make_unique<Representer>(*this, *tray_, *settings_, *models_); qRegisterMetaType<TaskPtr>(); settings_->load(); updateSettings(); if (settings_->showMessageOnStart) tray_->showInformation(QObject::tr("Screen translator started")); warnIfOutdated(); QObject::connect(updater_.get(), &update::Loader::error, // tray_.get(), &TrayIcon::showError); QObject::connect(updater_.get(), &update::Loader::updated, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Update completed")); }); QObject::connect(updater_.get(), &update::Loader::updatesAvailable, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Updates available")); }); } Manager::~Manager() { SOFT_ASSERT(settings_, return ); if (updateAutoChecker_ && updateAutoChecker_->isLastCheckDateChanged()) { settings_->lastUpdateCheck = updateAutoChecker_->lastCheckDate(); settings_->saveLastUpdateCheck(); } setupTrace(false); } void Manager::warnIfOutdated() { const auto now = QDateTime::currentDateTime(); const auto binaryInfo = QFileInfo(QApplication::applicationFilePath()); const auto date = binaryInfo.fileTime(QFile::FileTime::FileBirthTime); const auto deadlineDays = 90; if (date.daysTo(now) < deadlineDays) return; const auto updateDate = settings_->lastUpdateCheck; if (updateDate.isValid() && updateDate.daysTo(now) < deadlineDays) return; tray_->showInformation( QObject::tr("Current version might be outdated.\n" "Check for updates to silence this warning")); } void Manager::updateSettings() { LTRACE() << "updateSettings"; SOFT_ASSERT(settings_, return ); settings_->writeTrace = setupTrace(settings_->writeTrace); setupProxy(*settings_); setupUpdates(*settings_); models_->update(settings_->tessdataPath); tray_->updateSettings(); capturer_->updateSettings(); recognizer_->updateSettings(); corrector_->updateSettings(); translator_->updateSettings(); representer_->updateSettings(); tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); } void Manager::setupProxy(const Settings &settings) { if (settings.proxyType == ProxyType::System) { QNetworkProxyFactory::setUseSystemConfiguration(true); return; } QNetworkProxyFactory::setUseSystemConfiguration(false); if (settings.proxyType == ProxyType::Disabled) { QNetworkProxy::setApplicationProxy({}); return; } QNetworkProxy proxy; using T = QNetworkProxy::ProxyType; proxy.setType(settings.proxyType == ProxyType::Socks5 ? T::Socks5Proxy : T::HttpProxy); proxy.setHostName(settings.proxyHostName); proxy.setPort(settings.proxyPort); proxy.setUser(settings.proxyUser); proxy.setPassword(settings.proxyPassword); QNetworkProxy::setApplicationProxy(proxy); } void Manager::setupUpdates(const Settings &settings) { updater_->model()->setExpansions({ {"$translators$", settings.translatorsDir}, {"$tessdata$", settings.tessdataPath}, {"$hunspell$", settings.hunspellDir}, {"$appdir$", QApplication::applicationDirPath()}, }); SOFT_ASSERT(updateAutoChecker_, return ); updateAutoChecker_->setLastCheckDate(settings.lastUpdateCheck); updateAutoChecker_->setCheckIntervalDays(settings.autoUpdateIntervalDays); } bool Manager::setupTrace(bool isOn) { const auto oldFile = debug::traceFileName(); if (!isOn) { debug::setTraceFileName({}); debug::isTrace = qEnvironmentVariableIsSet("TRACE"); if (!oldFile.isEmpty()) QDesktopServices::openUrl(QUrl::fromLocalFile(oldFile)); return false; } if (!oldFile.isEmpty()) return true; const auto traceFile = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1String("/screen-translator-") + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss"); if (!debug::setTraceFileName(traceFile)) { QMessageBox::warning( nullptr, {}, QObject::tr("Failed to set log file: %1").arg(traceFile)); return false; } debug::isTrace = true; QMessageBox::information( nullptr, {}, QObject::tr("Started logging to file: %1").arg(traceFile)); return true; } void Manager::finishTask(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "finishTask" << task; --activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { tray_->showError(task->error); tray_->setTaskActionsEnabled(false); return; } tray_->showSuccess(); } void Manager::captured(const TaskPtr &task) { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); SOFT_ASSERT(task, return ); LTRACE() << "captured" << task; ++activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { finishTask(task); return; } recognizer_->recognize(task); } void Manager::captureCanceled() { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); } void Manager::recognized(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "recognized" << task; if (!task->isValid()) { finishTask(task); return; } corrector_->correct(task); } void Manager::corrected(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "corrected" << task; if (!task->isValid()) { finishTask(task); return; } if (!task->targetLanguage.isEmpty()) translator_->translate(task); else translated(task); } void Manager::translated(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "translated" << task; finishTask(task); representer_->represent(task); tray_->setTaskActionsEnabled(!task->isNull()); } void Manager::applySettings(const Settings &settings) { SOFT_ASSERT(settings_, return ); const auto lastUpdate = settings_->lastUpdateCheck; // not handled in editor *settings_ = settings; settings_->lastUpdateCheck = lastUpdate; settings_->save(); updateSettings(); } void Manager::fatalError(const QString &text) { tray_->blockActions(false); tray_->showFatalError(text); } void Manager::capture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->capture(); tray_->setRepeatCaptureEnabled(true); } void Manager::repeatCapture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); capturer_->repeatCapture(); } void Manager::captureLocked() { SOFT_ASSERT(capturer_, return ); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->captureLocked(); } void Manager::settings() { SettingsEditor editor(*this, *updater_); SOFT_ASSERT(settings_, return ); editor.setSettings(*settings_); tray_->blockActions(true); auto result = editor.exec(); tray_->blockActions(false); if (result != QDialog::Accepted) return; tray_->resetFatalError(); const auto edited = editor.settings(); applySettings(edited); } void Manager::showLast() { SOFT_ASSERT(representer_, return ); representer_->showLast(); } void Manager::showTranslator() { SOFT_ASSERT(translator_, return ); translator_->show(); } void Manager::copyLastToClipboard() { SOFT_ASSERT(representer_, return ); representer_->clipboardLast(); } void Manager::quit() { QApplication::quit(); }
#include "manager.h" #include "capturer.h" #include "corrector.h" #include "debug.h" #include "recognizer.h" #include "representer.h" #include "settingseditor.h" #include "task.h" #include "translator.h" #include "trayicon.h" #include "updates.h" #include <QApplication> #include <QDesktopServices> #include <QFileInfo> #include <QMessageBox> #include <QNetworkProxy> #include <QThread> namespace { #ifdef DEVELOP const auto updatesUrl = "http://localhost:8081/updates.json"; #else const auto updatesUrl = "https://raw.githubusercontent.com/OneMoreGres/ScreenTranslator/master/" "updates.json"; #endif const auto resultHideWaitUs = 300'000; } // namespace using Loader = update::Loader; Manager::Manager() : settings_(std::make_unique<Settings>()) , updater_(std::make_unique<Loader>(Loader::Urls{{updatesUrl}})) , updateAutoChecker_(std::make_unique<update::AutoChecker>(*updater_)) , models_(std::make_unique<CommonModels>()) { SOFT_ASSERT(settings_, return ); // updater components (void)QT_TRANSLATE_NOOP("QObject", "app"); (void)QT_TRANSLATE_NOOP("QObject", "recognizers"); (void)QT_TRANSLATE_NOOP("QObject", "hunspell"); (void)QT_TRANSLATE_NOOP("QObject", "translators"); tray_ = std::make_unique<TrayIcon>(*this, *settings_); capturer_ = std::make_unique<Capturer>(*this, *settings_, *models_); recognizer_ = std::make_unique<Recognizer>(*this, *settings_); translator_ = std::make_unique<Translator>(*this, *settings_); corrector_ = std::make_unique<Corrector>(*this, *settings_); representer_ = std::make_unique<Representer>(*this, *tray_, *settings_, *models_); qRegisterMetaType<TaskPtr>(); settings_->load(); updateSettings(); if (settings_->showMessageOnStart) tray_->showInformation(QObject::tr("Screen translator started")); warnIfOutdated(); QObject::connect(updater_.get(), &update::Loader::error, // tray_.get(), &TrayIcon::showError); QObject::connect(updater_.get(), &update::Loader::updated, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Update completed")); }); QObject::connect(updater_.get(), &update::Loader::updatesAvailable, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Updates available")); }); } Manager::~Manager() { SOFT_ASSERT(settings_, return ); if (updateAutoChecker_ && updateAutoChecker_->isLastCheckDateChanged()) { settings_->lastUpdateCheck = updateAutoChecker_->lastCheckDate(); settings_->saveLastUpdateCheck(); } } void Manager::warnIfOutdated() { const auto now = QDateTime::currentDateTime(); const auto binaryInfo = QFileInfo(QApplication::applicationFilePath()); const auto date = binaryInfo.fileTime(QFile::FileTime::FileBirthTime); const auto deadlineDays = 90; if (date.daysTo(now) < deadlineDays) return; const auto updateDate = settings_->lastUpdateCheck; if (updateDate.isValid() && updateDate.daysTo(now) < deadlineDays) return; tray_->showInformation( QObject::tr("Current version might be outdated.\n" "Check for updates to silence this warning")); } void Manager::updateSettings() { LTRACE() << "updateSettings"; SOFT_ASSERT(settings_, return ); settings_->writeTrace = setupTrace(settings_->writeTrace); setupProxy(*settings_); setupUpdates(*settings_); models_->update(settings_->tessdataPath); tray_->updateSettings(); capturer_->updateSettings(); recognizer_->updateSettings(); corrector_->updateSettings(); translator_->updateSettings(); representer_->updateSettings(); tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); } void Manager::setupProxy(const Settings &settings) { if (settings.proxyType == ProxyType::System) { QNetworkProxyFactory::setUseSystemConfiguration(true); return; } QNetworkProxyFactory::setUseSystemConfiguration(false); if (settings.proxyType == ProxyType::Disabled) { QNetworkProxy::setApplicationProxy({}); return; } QNetworkProxy proxy; using T = QNetworkProxy::ProxyType; proxy.setType(settings.proxyType == ProxyType::Socks5 ? T::Socks5Proxy : T::HttpProxy); proxy.setHostName(settings.proxyHostName); proxy.setPort(settings.proxyPort); proxy.setUser(settings.proxyUser); proxy.setPassword(settings.proxyPassword); QNetworkProxy::setApplicationProxy(proxy); } void Manager::setupUpdates(const Settings &settings) { updater_->model()->setExpansions({ {"$translators$", settings.translatorsDir}, {"$tessdata$", settings.tessdataPath}, {"$hunspell$", settings.hunspellDir}, {"$appdir$", QApplication::applicationDirPath()}, }); SOFT_ASSERT(updateAutoChecker_, return ); updateAutoChecker_->setLastCheckDate(settings.lastUpdateCheck); updateAutoChecker_->setCheckIntervalDays(settings.autoUpdateIntervalDays); } bool Manager::setupTrace(bool isOn) { const auto oldFile = debug::traceFileName(); if (!isOn) { debug::setTraceFileName({}); debug::isTrace = qEnvironmentVariableIsSet("TRACE"); if (!oldFile.isEmpty()) QDesktopServices::openUrl(QUrl::fromLocalFile(oldFile)); return false; } if (!oldFile.isEmpty()) return true; const auto traceFile = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1String("/screen-translator-") + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss"); if (!debug::setTraceFileName(traceFile)) { QMessageBox::warning( nullptr, {}, QObject::tr("Failed to set log file: %1").arg(traceFile)); return false; } debug::isTrace = true; QMessageBox::information( nullptr, {}, QObject::tr("Started logging to file: %1").arg(traceFile)); return true; } void Manager::finishTask(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "finishTask" << task; --activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { tray_->showError(task->error); tray_->setTaskActionsEnabled(false); return; } tray_->showSuccess(); } void Manager::captured(const TaskPtr &task) { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); SOFT_ASSERT(task, return ); LTRACE() << "captured" << task; ++activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { finishTask(task); return; } recognizer_->recognize(task); } void Manager::captureCanceled() { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); } void Manager::recognized(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "recognized" << task; if (!task->isValid()) { finishTask(task); return; } corrector_->correct(task); } void Manager::corrected(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "corrected" << task; if (!task->isValid()) { finishTask(task); return; } if (!task->targetLanguage.isEmpty()) translator_->translate(task); else translated(task); } void Manager::translated(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "translated" << task; finishTask(task); representer_->represent(task); tray_->setTaskActionsEnabled(!task->isNull()); } void Manager::applySettings(const Settings &settings) { SOFT_ASSERT(settings_, return ); const auto lastUpdate = settings_->lastUpdateCheck; // not handled in editor *settings_ = settings; settings_->lastUpdateCheck = lastUpdate; settings_->save(); updateSettings(); } void Manager::fatalError(const QString &text) { tray_->blockActions(false); tray_->showFatalError(text); } void Manager::capture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->capture(); tray_->setRepeatCaptureEnabled(true); } void Manager::repeatCapture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); capturer_->repeatCapture(); } void Manager::captureLocked() { SOFT_ASSERT(capturer_, return ); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->captureLocked(); } void Manager::settings() { SettingsEditor editor(*this, *updater_); SOFT_ASSERT(settings_, return ); editor.setSettings(*settings_); tray_->blockActions(true); auto result = editor.exec(); tray_->blockActions(false); if (result != QDialog::Accepted) return; tray_->resetFatalError(); const auto edited = editor.settings(); applySettings(edited); } void Manager::showLast() { SOFT_ASSERT(representer_, return ); representer_->showLast(); } void Manager::showTranslator() { SOFT_ASSERT(translator_, return ); translator_->show(); } void Manager::copyLastToClipboard() { SOFT_ASSERT(representer_, return ); representer_->clipboardLast(); } void Manager::quit() { QApplication::quit(); }
Write log while still can
Write log while still can
C++
mit
OneMoreGres/ScreenTranslator,OneMoreGres/ScreenTranslator,OneMoreGres/ScreenTranslator,OneMoreGres/ScreenTranslator
7ccd282dc23892482be32a9263df25a9165f755b
roofit/roostats/src/ProfileLikelihoodTestStat.cxx
roofit/roostats/src/ProfileLikelihoodTestStat.cxx
// @(#)root/roostats:$Id$ // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke // Additional Contributions: Giovanni Petrucciani /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "RooStats/ProfileLikelihoodTestStat.h" Bool_t RooStats::ProfileLikelihoodTestStat::fgAlwaysReuseNll = kTRUE ; Double_t RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, RooAbsData& data, RooArgSet& paramsOfInterest) { // interna function to evaluate test statistics // can do depending on type: // type = 0 standard evaluation, type = 1 find only unconditional NLL minimum, type = 2 conditional MLL if (!&data) { cout << "problem with data" << endl; return 0 ; } //data.Print("V"); TStopwatch tsw; tsw.Start(); double initial_mu_value = 0; RooRealVar* firstPOI = dynamic_cast<RooRealVar*>( paramsOfInterest.first()); if (firstPOI) initial_mu_value = firstPOI->getVal(); //paramsOfInterest.getRealValue(firstPOI->GetName()); RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow(); if (fPrintLevel < 3) RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL); // simple Bool_t reuse=(fReuseNll || fgAlwaysReuseNll) ; Bool_t created(kFALSE) ; if (!reuse || fNll==0) { RooArgSet* allParams = fPdf->getParameters(data); RooStats::RemoveConstantParameters(allParams); // need to call constrain for RooSimultaneous until stripDisconnected problem fixed fNll = (RooNLLVar*) fPdf->createNLL(data, RooFit::CloneData(kFALSE),RooFit::Constrain(*allParams)); // fNll = (RooNLLVar*) fPdf->createNLL(data, RooFit::CloneData(kFALSE)); // fProfile = (RooProfileLL*) fNll->createProfile(paramsOfInterest); created = kTRUE ; delete allParams; //cout << "creating profile LL " << fNll << " " << fProfile << " data = " << &data << endl ; } if (reuse && !created) { //cout << "reusing profile LL " << fNll << " new data = " << &data << endl ; fNll->setData(data,kFALSE) ; } // make sure we set the variables attached to this nll RooArgSet* attachedSet = fNll->getVariables(); *attachedSet = paramsOfInterest; RooArgSet* origAttachedSet = (RooArgSet*) attachedSet->snapshot(); /////////////////////////////////////////////////////////////////////// // New profiling based on RooMinimizer (allows for Minuit2) // based on major speed increases seen by CMS for complex problems // other order // get the numerator RooArgSet* snap = (RooArgSet*)paramsOfInterest.snapshot(); tsw.Stop(); double createTime = tsw.CpuTime(); tsw.Start(); // get the denominator double uncondML = 0; double fit_favored_mu = 0; int statusD = 0; if (type != 2) { uncondML = GetMinNLL(statusD); // get best fit value for one-sided interval if (firstPOI) fit_favored_mu = attachedSet->getRealValue(firstPOI->GetName()) ; } tsw.Stop(); double fitTime1 = tsw.CpuTime(); double ret = 0; int statusN = 0; tsw.Start(); double condML = 0; bool doConditionalFit = (type != 1); // skip the conditional ML (the numerator) only when fit value is smaller than test value if (fOneSided && fit_favored_mu > initial_mu_value) { doConditionalFit = false; condML = uncondML; } if (doConditionalFit) { // cout <<" reestablish snapshot"<<endl; *attachedSet = *snap; // set the POI to constant RooLinkedListIter it = paramsOfInterest.iterator(); RooRealVar* tmpPar = NULL, *tmpParA=NULL; while((tmpPar = (RooRealVar*)it.Next())){ tmpParA = dynamic_cast<RooRealVar*>( attachedSet->find(tmpPar->GetName())); if (tmpParA) tmpParA->setConstant(); } // check if there are non-const parameters so it is worth to do the minimization RooArgSet allParams(*attachedSet); RooStats::RemoveConstantParameters(&allParams); // in case no nuisance parameters are present // no need to minimize just evaluate the nll if (allParams.getSize() == 0 ) { condML = fNll->getVal(); } else { condML = GetMinNLL(statusN); } } tsw.Stop(); double fitTime2 = tsw.CpuTime(); if (fPrintLevel > 0) { std::cout << "EvaluateProfileLikelihood - "; if (type <= 1) std::cout << "mu hat = " << fit_favored_mu << " uncond ML = " << uncondML; if (type != 1) std::cout << " cond ML = " << condML; if (type == 0) std::cout << " pll = " << condML-uncondML; std::cout << " time (create/fit1/2) " << createTime << " , " << fitTime1 << " , " << fitTime2 << std::endl; } // need to restore the values ? *attachedSet = *origAttachedSet; delete attachedSet; delete origAttachedSet; delete snap; if (!reuse) { delete fNll; fNll = 0; // delete fProfile; fProfile = 0 ; } RooMsgService::instance().setGlobalKillBelow(msglevel); if(statusN!=0 || statusD!=0) ret= -1; // indicate failed fit if (type == 1) return uncondML; if (type == 2) return condML; return condML-uncondML; } double RooStats::ProfileLikelihoodTestStat::GetMinNLL(int& status) { //find minimum of NLL using RooMinimizer RooMinimizer minim(*fNll); minim.setStrategy(fStrategy); //LM: RooMinimizer.setPrintLevel has +1 offset - so subtruct here -1 + an extra -1 int level = (fPrintLevel == 0) ? -1 : fPrintLevel -2; minim.setPrintLevel(level); minim.setEps(fTolerance); // this cayses a memory leak minim.optimizeConst(true); for (int tries = 0, maxtries = 4; tries <= maxtries; ++tries) { // status = minim.minimize(fMinimizer, ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str()); status = minim.minimize(fMinimizer, "Minimize"); if (status == 0) { break; } else { if (tries > 1) { printf(" ----> Doing a re-scan first\n"); minim.minimize(fMinimizer,"Scan"); } if (tries > 2) { printf(" ----> trying with strategy = 1\n"); minim.setStrategy(1); } } } double val = fNll->getVal(); //minim.optimizeConst(false); return val; }
// @(#)root/roostats:$Id$ // Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke // Additional Contributions: Giovanni Petrucciani /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "RooStats/ProfileLikelihoodTestStat.h" Bool_t RooStats::ProfileLikelihoodTestStat::fgAlwaysReuseNll = kTRUE ; Double_t RooStats::ProfileLikelihoodTestStat::EvaluateProfileLikelihood(int type, RooAbsData& data, RooArgSet& paramsOfInterest) { // interna function to evaluate test statistics // can do depending on type: // type = 0 standard evaluation, type = 1 find only unconditional NLL minimum, type = 2 conditional MLL if (!&data) { cout << "problem with data" << endl; return 0 ; } //data.Print("V"); TStopwatch tsw; tsw.Start(); double initial_mu_value = 0; RooRealVar* firstPOI = dynamic_cast<RooRealVar*>( paramsOfInterest.first()); if (firstPOI) initial_mu_value = firstPOI->getVal(); //paramsOfInterest.getRealValue(firstPOI->GetName()); RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow(); if (fPrintLevel < 3) RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL); // simple Bool_t reuse=(fReuseNll || fgAlwaysReuseNll) ; Bool_t created(kFALSE) ; if (!reuse || fNll==0) { RooArgSet* allParams = fPdf->getParameters(data); RooStats::RemoveConstantParameters(allParams); // need to call constrain for RooSimultaneous until stripDisconnected problem fixed fNll = (RooNLLVar*) fPdf->createNLL(data, RooFit::CloneData(kFALSE),RooFit::Constrain(*allParams)); // fNll = (RooNLLVar*) fPdf->createNLL(data, RooFit::CloneData(kFALSE)); // fProfile = (RooProfileLL*) fNll->createProfile(paramsOfInterest); created = kTRUE ; delete allParams; //cout << "creating profile LL " << fNll << " " << fProfile << " data = " << &data << endl ; } if (reuse && !created) { //cout << "reusing profile LL " << fNll << " new data = " << &data << endl ; fNll->setData(data,kFALSE) ; } // make sure we set the variables attached to this nll RooArgSet* attachedSet = fNll->getVariables(); *attachedSet = paramsOfInterest; RooArgSet* origAttachedSet = (RooArgSet*) attachedSet->snapshot(); /////////////////////////////////////////////////////////////////////// // New profiling based on RooMinimizer (allows for Minuit2) // based on major speed increases seen by CMS for complex problems // other order // get the numerator RooArgSet* snap = (RooArgSet*)paramsOfInterest.snapshot(); tsw.Stop(); double createTime = tsw.CpuTime(); tsw.Start(); // get the denominator double uncondML = 0; double fit_favored_mu = 0; int statusD = 0; if (type != 2) { uncondML = GetMinNLL(statusD); // get best fit value for one-sided interval if (firstPOI) fit_favored_mu = attachedSet->getRealValue(firstPOI->GetName()) ; } tsw.Stop(); double fitTime1 = tsw.CpuTime(); double ret = 0; int statusN = 0; tsw.Start(); double condML = 0; bool doConditionalFit = (type != 1); // skip the conditional ML (the numerator) only when fit value is smaller than test value if (fOneSided && fit_favored_mu > initial_mu_value) { doConditionalFit = false; condML = uncondML; } if (doConditionalFit) { // cout <<" reestablish snapshot"<<endl; *attachedSet = *snap; // set the POI to constant RooLinkedListIter it = paramsOfInterest.iterator(); RooRealVar* tmpPar = NULL, *tmpParA=NULL; while((tmpPar = (RooRealVar*)it.Next())){ tmpParA = dynamic_cast<RooRealVar*>( attachedSet->find(tmpPar->GetName())); if (tmpParA) tmpParA->setConstant(); } // check if there are non-const parameters so it is worth to do the minimization RooArgSet allParams(*attachedSet); RooStats::RemoveConstantParameters(&allParams); // in case no nuisance parameters are present // no need to minimize just evaluate the nll if (allParams.getSize() == 0 ) { condML = fNll->getVal(); } else { condML = GetMinNLL(statusN); } } tsw.Stop(); double fitTime2 = tsw.CpuTime(); if (fPrintLevel > 0) { std::cout << "EvaluateProfileLikelihood - "; if (type <= 1) std::cout << "mu hat = " << fit_favored_mu << " uncond ML = " << uncondML; if (type != 1) std::cout << " cond ML = " << condML; if (type == 0) std::cout << " pll = " << condML-uncondML; std::cout << " time (create/fit1/2) " << createTime << " , " << fitTime1 << " , " << fitTime2 << std::endl; } // need to restore the values ? *attachedSet = *origAttachedSet; delete attachedSet; delete origAttachedSet; delete snap; if (!reuse) { delete fNll; fNll = 0; // delete fProfile; fProfile = 0 ; } RooMsgService::instance().setGlobalKillBelow(msglevel); if(statusN!=0 || statusD!=0) ret= -1; // indicate failed fit if (type == 1) return uncondML; if (type == 2) return condML; return condML-uncondML; } double RooStats::ProfileLikelihoodTestStat::GetMinNLL(int& status) { //find minimum of NLL using RooMinimizer RooMinimizer minim(*fNll); minim.setStrategy(fStrategy); //LM: RooMinimizer.setPrintLevel has +1 offset - so subtruct here -1 + an extra -1 int level = (fPrintLevel == 0) ? -1 : fPrintLevel -2; minim.setPrintLevel(level); minim.setEps(fTolerance); // this cayses a memory leak minim.optimizeConst(2); for (int tries = 0, maxtries = 4; tries <= maxtries; ++tries) { // status = minim.minimize(fMinimizer, ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str()); status = minim.minimize(fMinimizer, "Minimize"); if (status == 0) { break; } else { if (tries > 1) { printf(" ----> Doing a re-scan first\n"); minim.minimize(fMinimizer,"Scan"); } if (tries > 2) { printf(" ----> trying with strategy = 1\n"); minim.setStrategy(1); } } } double val = fNll->getVal(); //minim.optimizeConst(false); return val; }
copy fix 42462 from 5.32 brnach to use optimizeConst(2).
copy fix 42462 from 5.32 brnach to use optimizeConst(2). git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@42463 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
mattkretz/root,gganis/root,sirinath/root,gbitzes/root,krafczyk/root,davidlt/root,abhinavmoudgil95/root,karies/root,satyarth934/root,smarinac/root,omazapa/root-old,perovic/root,zzxuanyuan/root,mattkretz/root,mkret2/root,jrtomps/root,mkret2/root,dfunke/root,mattkretz/root,sbinet/cxx-root,vukasinmilosevic/root,bbockelm/root,esakellari/my_root_for_test,veprbl/root,Dr15Jones/root,Duraznos/root,CristinaCristescu/root,zzxuanyuan/root-compressor-dummy,root-mirror/root,ffurano/root5,agarciamontoro/root,omazapa/root,root-mirror/root,veprbl/root,zzxuanyuan/root,tc3t/qoot,BerserkerTroll/root,0x0all/ROOT,CristinaCristescu/root,beniz/root,esakellari/root,georgtroska/root,mhuwiler/rootauto,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,thomaskeck/root,esakellari/my_root_for_test,jrtomps/root,Duraznos/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,arch1tect0r/root,sirinath/root,kirbyherm/root-r-tools,satyarth934/root,Duraznos/root,abhinavmoudgil95/root,strykejern/TTreeReader,vukasinmilosevic/root,mattkretz/root,mattkretz/root,BerserkerTroll/root,gganis/root,bbockelm/root,Duraznos/root,bbockelm/root,omazapa/root-old,vukasinmilosevic/root,beniz/root,omazapa/root,strykejern/TTreeReader,lgiommi/root,gganis/root,thomaskeck/root,root-mirror/root,satyarth934/root,sirinath/root,georgtroska/root,ffurano/root5,gganis/root,zzxuanyuan/root-compressor-dummy,bbockelm/root,arch1tect0r/root,gganis/root,simonpf/root,Duraznos/root,mhuwiler/rootauto,nilqed/root,zzxuanyuan/root,satyarth934/root,tc3t/qoot,omazapa/root,jrtomps/root,thomaskeck/root,davidlt/root,satyarth934/root,mhuwiler/rootauto,abhinavmoudgil95/root,sawenzel/root,gbitzes/root,mkret2/root,gganis/root,omazapa/root-old,sbinet/cxx-root,beniz/root,nilqed/root,Y--/root,CristinaCristescu/root,ffurano/root5,root-mirror/root,tc3t/qoot,kirbyherm/root-r-tools,smarinac/root,mhuwiler/rootauto,georgtroska/root,mhuwiler/rootauto,veprbl/root,strykejern/TTreeReader,nilqed/root,perovic/root,beniz/root,root-mirror/root,strykejern/TTreeReader,sbinet/cxx-root,buuck/root,BerserkerTroll/root,olifre/root,gbitzes/root,esakellari/root,Y--/root,CristinaCristescu/root,pspe/root,Y--/root,CristinaCristescu/root,arch1tect0r/root,olifre/root,sbinet/cxx-root,mattkretz/root,perovic/root,mhuwiler/rootauto,gganis/root,omazapa/root,arch1tect0r/root,esakellari/root,agarciamontoro/root,sawenzel/root,abhinavmoudgil95/root,cxx-hep/root-cern,arch1tect0r/root,lgiommi/root,karies/root,karies/root,zzxuanyuan/root,root-mirror/root,beniz/root,omazapa/root-old,esakellari/root,smarinac/root,beniz/root,BerserkerTroll/root,buuck/root,omazapa/root,evgeny-boger/root,veprbl/root,smarinac/root,abhinavmoudgil95/root,root-mirror/root,simonpf/root,cxx-hep/root-cern,thomaskeck/root,pspe/root,satyarth934/root,esakellari/my_root_for_test,buuck/root,mhuwiler/rootauto,omazapa/root,krafczyk/root,esakellari/my_root_for_test,lgiommi/root,0x0all/ROOT,ffurano/root5,arch1tect0r/root,vukasinmilosevic/root,zzxuanyuan/root,vukasinmilosevic/root,vukasinmilosevic/root,gganis/root,jrtomps/root,dfunke/root,Dr15Jones/root,abhinavmoudgil95/root,davidlt/root,arch1tect0r/root,mkret2/root,0x0all/ROOT,Y--/root,karies/root,BerserkerTroll/root,bbockelm/root,jrtomps/root,mkret2/root,0x0all/ROOT,perovic/root,cxx-hep/root-cern,mhuwiler/rootauto,sawenzel/root,esakellari/root,bbockelm/root,davidlt/root,georgtroska/root,tc3t/qoot,cxx-hep/root-cern,buuck/root,Dr15Jones/root,olifre/root,zzxuanyuan/root,BerserkerTroll/root,simonpf/root,sirinath/root,krafczyk/root,CristinaCristescu/root,sbinet/cxx-root,omazapa/root,omazapa/root-old,esakellari/my_root_for_test,kirbyherm/root-r-tools,Dr15Jones/root,georgtroska/root,simonpf/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,mattkretz/root,esakellari/my_root_for_test,beniz/root,CristinaCristescu/root,Duraznos/root,krafczyk/root,alexschlueter/cern-root,agarciamontoro/root,BerserkerTroll/root,zzxuanyuan/root-compressor-dummy,bbockelm/root,arch1tect0r/root,sirinath/root,thomaskeck/root,sirinath/root,BerserkerTroll/root,omazapa/root-old,sawenzel/root,olifre/root,lgiommi/root,BerserkerTroll/root,krafczyk/root,evgeny-boger/root,krafczyk/root,evgeny-boger/root,nilqed/root,zzxuanyuan/root,zzxuanyuan/root,BerserkerTroll/root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,dfunke/root,esakellari/root,davidlt/root,davidlt/root,0x0all/ROOT,omazapa/root-old,nilqed/root,agarciamontoro/root,olifre/root,nilqed/root,veprbl/root,Duraznos/root,davidlt/root,cxx-hep/root-cern,karies/root,zzxuanyuan/root-compressor-dummy,omazapa/root,buuck/root,buuck/root,beniz/root,zzxuanyuan/root,BerserkerTroll/root,mattkretz/root,georgtroska/root,strykejern/TTreeReader,esakellari/my_root_for_test,sawenzel/root,veprbl/root,gbitzes/root,Duraznos/root,Dr15Jones/root,Y--/root,krafczyk/root,mattkretz/root,georgtroska/root,satyarth934/root,georgtroska/root,simonpf/root,0x0all/ROOT,zzxuanyuan/root,gbitzes/root,satyarth934/root,Duraznos/root,veprbl/root,alexschlueter/cern-root,smarinac/root,sirinath/root,krafczyk/root,abhinavmoudgil95/root,CristinaCristescu/root,pspe/root,lgiommi/root,mattkretz/root,pspe/root,alexschlueter/cern-root,bbockelm/root,perovic/root,olifre/root,gbitzes/root,lgiommi/root,georgtroska/root,simonpf/root,omazapa/root-old,sawenzel/root,evgeny-boger/root,dfunke/root,lgiommi/root,alexschlueter/cern-root,arch1tect0r/root,krafczyk/root,abhinavmoudgil95/root,olifre/root,evgeny-boger/root,alexschlueter/cern-root,beniz/root,gbitzes/root,veprbl/root,dfunke/root,davidlt/root,smarinac/root,pspe/root,dfunke/root,buuck/root,arch1tect0r/root,sbinet/cxx-root,thomaskeck/root,sbinet/cxx-root,tc3t/qoot,esakellari/my_root_for_test,veprbl/root,Y--/root,ffurano/root5,agarciamontoro/root,mkret2/root,nilqed/root,bbockelm/root,pspe/root,jrtomps/root,veprbl/root,mkret2/root,esakellari/root,abhinavmoudgil95/root,root-mirror/root,esakellari/my_root_for_test,strykejern/TTreeReader,tc3t/qoot,sawenzel/root,CristinaCristescu/root,smarinac/root,cxx-hep/root-cern,lgiommi/root,bbockelm/root,dfunke/root,jrtomps/root,satyarth934/root,pspe/root,karies/root,bbockelm/root,beniz/root,tc3t/qoot,nilqed/root,tc3t/qoot,pspe/root,satyarth934/root,gbitzes/root,sawenzel/root,strykejern/TTreeReader,cxx-hep/root-cern,Duraznos/root,simonpf/root,alexschlueter/cern-root,gbitzes/root,pspe/root,mkret2/root,mhuwiler/rootauto,davidlt/root,kirbyherm/root-r-tools,perovic/root,zzxuanyuan/root,kirbyherm/root-r-tools,esakellari/root,perovic/root,gganis/root,dfunke/root,omazapa/root-old,nilqed/root,smarinac/root,karies/root,sawenzel/root,omazapa/root-old,zzxuanyuan/root-compressor-dummy,georgtroska/root,simonpf/root,buuck/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,esakellari/root,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,olifre/root,perovic/root,0x0all/ROOT,omazapa/root,evgeny-boger/root,cxx-hep/root-cern,lgiommi/root,Dr15Jones/root,mhuwiler/rootauto,perovic/root,tc3t/qoot,pspe/root,gbitzes/root,krafczyk/root,root-mirror/root,sirinath/root,tc3t/qoot,vukasinmilosevic/root,esakellari/my_root_for_test,karies/root,dfunke/root,jrtomps/root,Y--/root,jrtomps/root,0x0all/ROOT,agarciamontoro/root,root-mirror/root,perovic/root,veprbl/root,agarciamontoro/root,sawenzel/root,mkret2/root,evgeny-boger/root,omazapa/root,karies/root,davidlt/root,ffurano/root5,jrtomps/root,olifre/root,Y--/root,sirinath/root,smarinac/root,thomaskeck/root,vukasinmilosevic/root,alexschlueter/cern-root,perovic/root,simonpf/root,karies/root,nilqed/root,omazapa/root,sirinath/root,abhinavmoudgil95/root,agarciamontoro/root,sirinath/root,vukasinmilosevic/root,karies/root,gbitzes/root,gganis/root,sbinet/cxx-root,sawenzel/root,beniz/root,kirbyherm/root-r-tools,simonpf/root,mkret2/root,jrtomps/root,evgeny-boger/root,buuck/root,smarinac/root,Y--/root,buuck/root,evgeny-boger/root,olifre/root,pspe/root,Dr15Jones/root,lgiommi/root,lgiommi/root,esakellari/root,vukasinmilosevic/root,CristinaCristescu/root,dfunke/root,thomaskeck/root,agarciamontoro/root,ffurano/root5,mattkretz/root,simonpf/root,Y--/root,0x0all/ROOT,dfunke/root,gganis/root,abhinavmoudgil95/root,georgtroska/root,mkret2/root,Y--/root,Duraznos/root,evgeny-boger/root,olifre/root,root-mirror/root,sbinet/cxx-root,kirbyherm/root-r-tools,omazapa/root-old,sbinet/cxx-root,esakellari/root,evgeny-boger/root,CristinaCristescu/root,buuck/root,davidlt/root,nilqed/root,satyarth934/root,agarciamontoro/root
a789ae2dcccba72598a6e4fe88b03247ac13924c
test/event_registration_test.cpp
test/event_registration_test.cpp
/* * ROS */ #include <ros/ros.h> #include <std_msgs/Int32.h> #include <std_msgs/String.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/TransformStamped.h> #include <sensor_msgs/CameraInfo.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/JointState.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/Range.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <stdlib.h> #include <vector> #include <string> #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> #include <boost/make_shared.hpp> #include <qi/os.hpp> #include <qi/applicationsession.hpp> #include <alrosbridge/tools.hpp> #include <alrosbridge/recorder/recorder.hpp> #include <alrosbridge/recorder/globalrecorder.hpp> #include "../src/converters/memory/float.hpp" #include "../src/recorder/memory/float.hpp" #include "../src/publishers/memory/float.hpp" #include "../src/converters/memory/bool.hpp" #include "../src/recorder/memory/bool.hpp" #include "../src/publishers/memory/bool.hpp" #include "../src/event.hpp" int main( int argc, char** argv ) { qi::ApplicationSession app(argc, argv); app.start(); setenv( "ROS_MASTER_URI", "http://10.0.128.9:11311", 1 ); ros::init( argc, argv, "converter_memory_test" ); ros::NodeHandle n; if(!ros::master::check()) { std::cerr<<"Could not contact master!\nQuitting... "<< std::endl; return -1; } boost::shared_ptr<alros::recorder::GlobalRecorder> gr = boost::make_shared<alros::recorder::GlobalRecorder>(""); qi::SessionPtr sessionPtr = app.session(); alros::EventRegister<alros::converter::MemoryBoolConverter,alros::publisher::MemoryBoolPublisher,alros::recorder::MemoryBoolRecorder> event_register("MiddleTactilTouched", sessionPtr); event_register.reset(n, gr); gr->startRecord(); event_register.startProcess(); event_register.isRecording(true); qi::os::sleep(30); event_register.isRecording(false); event_register.stopProcess(); gr->stopRecord(""); app.run(); app.session()->close(); return 0; }
/* * ROS */ #include <ros/ros.h> #include <std_msgs/Int32.h> #include <std_msgs/String.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/TransformStamped.h> #include <sensor_msgs/CameraInfo.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/JointState.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/Range.h> #include <sensor_msgs/image_encodings.h> #include <naoqi_bridge_msgs/BoolStamped.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <stdlib.h> #include <vector> #include <string> #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> #include <boost/make_shared.hpp> #include <qi/os.hpp> #include <qi/applicationsession.hpp> #include <alrosbridge/tools.hpp> #include <alrosbridge/recorder/recorder.hpp> #include <alrosbridge/recorder/globalrecorder.hpp> #include "../src/publishers/basic.hpp" #include "../src/converters/memory/float.hpp" #include "../src/recorder/memory/float.hpp" #include "../src/converters/memory/bool.hpp" #include "../src/recorder/memory/bool.hpp" #include "../src/event.hpp" int main( int argc, char** argv ) { qi::ApplicationSession app(argc, argv); app.start(); setenv( "ROS_MASTER_URI", "http://10.0.128.9:11311", 1 ); ros::init( argc, argv, "converter_memory_test" ); ros::NodeHandle n; if(!ros::master::check()) { std::cerr<<"Could not contact master!\nQuitting... "<< std::endl; return -1; } boost::shared_ptr<alros::recorder::GlobalRecorder> gr = boost::make_shared<alros::recorder::GlobalRecorder>(""); qi::SessionPtr sessionPtr = app.session(); alros::EventRegister<alros::converter::MemoryBoolConverter,alros::publisher::BasicPublisher<naoqi_bridge_msgs::BoolStamped>,alros::recorder::MemoryBoolRecorder> event_register("MiddleTactilTouched", sessionPtr); event_register.reset(n, gr); gr->startRecord(); event_register.startProcess(); event_register.isRecording(true); qi::os::sleep(30); event_register.isRecording(false); event_register.stopProcess(); gr->stopRecord(""); app.run(); app.session()->close(); return 0; }
Refactor test due to library changes
Refactor test due to library changes
C++
apache-2.0
nlyubova/naoqi_driver,ros-naoqi/alrosbridge,ros-naoqi/naoqi_driver,zygopter/alrosbridge,antegallya/naoqi_driver,antegallya/naoqi_driver,laurent-george/alrosbridge,ros-naoqi/alrosbridge,k-okada/naoqi_driver,ros-naoqi/naoqi_driver,vrabaud/alrosbridge,vrabaud/alrosbridge,zygopter/alrosbridge,k-okada/naoqi_driver,laurent-george/alrosbridge,nlyubova/naoqi_driver
c59bfa00a852aa63bc53f9a343b39507c34ba07c
ProcFd.cpp
ProcFd.cpp
#include <unistd.h> #include <regex> #include <dirent.h> #include "ProcFd.h" vector<string> ProcFd::getSocketInodeList() { auto symLinksContent = getSymlinksContent(); auto socketInodeList = extractSocketsInode(symLinksContent); return socketInodeList; } vector<string> ProcFd::getSymlinksContent() { string directoryName = "/proc/" + pid + "/fd"; DIR* directory = opendir(directoryName.c_str()); if (directory == NULL) { string error = directoryName + " does not exist"; perror(error.c_str()); exit(1); } struct dirent* symlink; vector<string> symlinkContentList; while (symlink = readdir(directory)) { string symlinkName = "/proc/" + pid + "/fd/" + symlink->d_name; char symlinkContent[BUFSIZ]; readlink(symlinkName.c_str(), symlinkContent, sizeof(symlinkContent)); symlinkContentList.push_back(strdup(symlinkContent)); } closedir(directory); return symlinkContentList; } vector<string> ProcFd::extractSocketsInode(vector<string> symlinkContentList) { vector<string> socketInodeList; for_each(symlinkContentList.begin(), symlinkContentList.end(), [&](string symlinkContent) { regex socketInodeRegex("socket:\\[([0-9]+)\\]"); smatch match; if (regex_search(symlinkContent, match, socketInodeRegex)) { socketInodeList.push_back(match[1].str().c_str()); } }); return socketInodeList; }
#include <unistd.h> #include <regex> #include <dirent.h> #include "ProcFd.h" vector<string> ProcFd::getSocketInodeList() { auto symLinksContent = getSymlinksContent(); auto socketInodeList = extractSocketsInode(symLinksContent); return socketInodeList; } vector<string> ProcFd::getSymlinksContent() { string directoryName = "/proc/" + pid + "/fd"; DIR* directory = opendir(directoryName.c_str()); if (directory == NULL) { string error = directoryName + " does not exist"; perror(error.c_str()); exit(1); } struct dirent* symlink; vector<string> symlinkContentList; while (symlink = readdir(directory)) { string symlinkName = "/proc/" + pid + "/fd/" + symlink->d_name; char symlinkContent[BUFSIZ]; readlink(symlinkName.c_str(), symlinkContent, sizeof(symlinkContent)); symlinkContentList.push_back(string(symlinkContent)); } closedir(directory); return symlinkContentList; } vector<string> ProcFd::extractSocketsInode(vector<string> symlinkContentList) { vector<string> socketInodeList; for_each(symlinkContentList.begin(), symlinkContentList.end(), [&](string symlinkContent) { regex socketInodeRegex("socket:\\[([0-9]+)\\]"); smatch match; if (regex_search(symlinkContent, match, socketInodeRegex)) { socketInodeList.push_back(match[1].str().c_str()); } }); return socketInodeList; }
Remove strdup causing memory leak.
Remove strdup causing memory leak.
C++
mit
zulhilmizainuddin/nettomon,zulhilmizainuddin/nettomon,zulhilmizainuddin/nettomon,zulhilmizainuddin/nettomon
ad5c52ebd76692cd31fbcf76e3fe395c530d7cc6
lib/TBDGen/tapi/YAML.cpp
lib/TBDGen/tapi/YAML.cpp
//===- lib/Core/YAML.cpp - Common YAML Mappings------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// Implements common YAML mappings /// //===----------------------------------------------------------------------===// #include "YAML.h" namespace llvm { namespace yaml { using Impl = ScalarTraits<StringRef>; void ScalarTraits<FlowStringRef>::output(const FlowStringRef &value, void *ctx, raw_ostream &os) { Impl::output(value, ctx, os); } StringRef ScalarTraits<FlowStringRef>::input(StringRef value, void *ctx, FlowStringRef &out) { return Impl::input(value, ctx, out.value); } QuotingType ScalarTraits<FlowStringRef>::mustQuote(StringRef name) { return Impl::mustQuote(name); } using tapi::ObjCConstraint; void ScalarEnumerationTraits<ObjCConstraint>::enumeration( IO &io, ObjCConstraint &constraint) { io.enumCase(constraint, "none", ObjCConstraint::None); io.enumCase(constraint, "retain_release", ObjCConstraint::Retain_Release); io.enumCase(constraint, "retain_release_for_simulator", ObjCConstraint::Retain_Release_For_Simulator); io.enumCase(constraint, "retain_release_or_gc", ObjCConstraint::Retain_Release_Or_GC); io.enumCase(constraint, "gc", ObjCConstraint::GC); } using TAPI_INTERNAL::Platform; void ScalarEnumerationTraits<Platform>::enumeration(IO &io, Platform &platform) { io.enumCase(platform, "unknown", Platform::unknown); io.enumCase(platform, "macosx", Platform::macOS); io.enumCase(platform, "ios", Platform::iOS); io.enumCase(platform, "ios", Platform::iOSSimulator); io.enumCase(platform, "watchos", Platform::watchOS); io.enumCase(platform, "watchos", Platform::watchOSSimulator); io.enumCase(platform, "tvos", Platform::tvOS); io.enumCase(platform, "tvos", Platform::tvOSSimulator); io.enumCase(platform, "bridgeos", Platform::bridgeOS); } using TAPI_INTERNAL::Architecture; using TAPI_INTERNAL::ArchitectureSet; void ScalarBitSetTraits<ArchitectureSet>::bitset(IO &io, ArchitectureSet &archs) { #define ARCHINFO(arch, type, subtype) \ io.bitSetCase(archs, #arch, 1U << static_cast<int>(Architecture::arch)); #include "Architecture.def" #undef ARCHINFO } using TAPI_INTERNAL::getArchType; void ScalarTraits<Architecture>::output(const Architecture &value, void *, raw_ostream &os) { os << value; } StringRef ScalarTraits<Architecture>::input(StringRef scalar, void *, Architecture &value) { value = getArchType(scalar); return {}; } QuotingType ScalarTraits<Architecture>::mustQuote(StringRef) { return QuotingType::None; } using TAPI_INTERNAL::PackedVersion; void ScalarTraits<PackedVersion>::output(const PackedVersion &value, void *, raw_ostream &os) { os << value; } StringRef ScalarTraits<PackedVersion>::input(StringRef scalar, void *, PackedVersion &value) { if (!value.parse32(scalar)) return "invalid packed version string."; return {}; } QuotingType ScalarTraits<PackedVersion>::mustQuote(StringRef) { return QuotingType::None; } void ScalarTraits<SwiftVersion>::output(const SwiftVersion &value, void *, raw_ostream &os) { switch (value) { case 1: os << "1.0"; break; case 2: os << "1.1"; break; case 3: os << "2.0"; break; case 4: os << "3.0"; break; default: os << (unsigned)value; break; } } StringRef ScalarTraits<SwiftVersion>::input(StringRef scalar, void *, SwiftVersion &value) { value = StringSwitch<SwiftVersion>(scalar) .Case("1.0", 1) .Case("1.1", 2) .Case("2.0", 3) .Case("3.0", 4) .Default(0); if (value != SwiftVersion(0)) return {}; if (scalar.getAsInteger(10, value)) return "invalid Swift ABI version."; return StringRef(); } QuotingType ScalarTraits<SwiftVersion>::mustQuote(StringRef) { return QuotingType::None; } using TAPI_INTERNAL::AvailabilityInfo; void ScalarTraits<AvailabilityInfo>::output(const AvailabilityInfo &value, void *, raw_ostream &os) { if (value._unavailable) { os << "n/a"; return; } os << value._introduced; if (!value._obsoleted.empty()) os << ".." << value._obsoleted; } StringRef ScalarTraits<AvailabilityInfo>::input(StringRef scalar, void *, AvailabilityInfo &value) { if (scalar == "n/a") { value._unavailable = true; return {}; } auto split = scalar.split(".."); auto introduced = split.first.trim(); auto obsoleted = split.second.trim(); if (!value._introduced.parse32(introduced)) return "invalid packed version string."; if (obsoleted.empty()) return StringRef(); if (!value._obsoleted.parse32(obsoleted)) return "invalid packed version string."; return StringRef(); } QuotingType ScalarTraits<AvailabilityInfo>::mustQuote(StringRef) { return QuotingType::None; } void ScalarTraits<UUID>::output(const UUID &value, void *, raw_ostream &os) { os << value.first << ": " << value.second; } StringRef ScalarTraits<UUID>::input(StringRef scalar, void *, UUID &value) { auto split = scalar.split(':'); auto arch = split.first.trim(); auto uuid = split.second.trim(); if (uuid.empty()) return "invalid uuid string pair"; value.first = getArchType(arch); value.second = uuid; return {}; } QuotingType ScalarTraits<UUID>::mustQuote(StringRef) { return QuotingType::Single; } using clang::Language; void ScalarEnumerationTraits<Language>::enumeration(IO &io, Language &kind) { io.enumCase(kind, "c", Language::C); io.enumCase(kind, "cxx", Language::CXX); io.enumCase(kind, "objective-c", Language::ObjC); io.enumCase(kind, "objc", Language::ObjC); // to keep old snapshots working. io.enumCase(kind, "objective-cxx", Language::ObjCXX); io.enumCase(kind, "objcxx", Language::ObjCXX); // to keep old snapshots working. } } // end namespace yaml. } // end namespace llvm.
//===- lib/Core/YAML.cpp - Common YAML Mappings------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// Implements common YAML mappings /// //===----------------------------------------------------------------------===// #include "YAML.h" namespace llvm { namespace yaml { using tapi::ObjCConstraint; void ScalarEnumerationTraits<ObjCConstraint>::enumeration( IO &io, ObjCConstraint &constraint) { io.enumCase(constraint, "none", ObjCConstraint::None); io.enumCase(constraint, "retain_release", ObjCConstraint::Retain_Release); io.enumCase(constraint, "retain_release_for_simulator", ObjCConstraint::Retain_Release_For_Simulator); io.enumCase(constraint, "retain_release_or_gc", ObjCConstraint::Retain_Release_Or_GC); io.enumCase(constraint, "gc", ObjCConstraint::GC); } using TAPI_INTERNAL::Platform; void ScalarEnumerationTraits<Platform>::enumeration(IO &io, Platform &platform) { io.enumCase(platform, "unknown", Platform::unknown); io.enumCase(platform, "macosx", Platform::macOS); io.enumCase(platform, "ios", Platform::iOS); io.enumCase(platform, "ios", Platform::iOSSimulator); io.enumCase(platform, "watchos", Platform::watchOS); io.enumCase(platform, "watchos", Platform::watchOSSimulator); io.enumCase(platform, "tvos", Platform::tvOS); io.enumCase(platform, "tvos", Platform::tvOSSimulator); io.enumCase(platform, "bridgeos", Platform::bridgeOS); } using TAPI_INTERNAL::Architecture; using TAPI_INTERNAL::ArchitectureSet; void ScalarBitSetTraits<ArchitectureSet>::bitset(IO &io, ArchitectureSet &archs) { #define ARCHINFO(arch, type, subtype) \ io.bitSetCase(archs, #arch, 1U << static_cast<int>(Architecture::arch)); #include "Architecture.def" #undef ARCHINFO } using TAPI_INTERNAL::getArchType; void ScalarTraits<Architecture>::output(const Architecture &value, void *, raw_ostream &os) { os << value; } StringRef ScalarTraits<Architecture>::input(StringRef scalar, void *, Architecture &value) { value = getArchType(scalar); return {}; } QuotingType ScalarTraits<Architecture>::mustQuote(StringRef) { return QuotingType::None; } using TAPI_INTERNAL::PackedVersion; void ScalarTraits<PackedVersion>::output(const PackedVersion &value, void *, raw_ostream &os) { os << value; } StringRef ScalarTraits<PackedVersion>::input(StringRef scalar, void *, PackedVersion &value) { if (!value.parse32(scalar)) return "invalid packed version string."; return {}; } QuotingType ScalarTraits<PackedVersion>::mustQuote(StringRef) { return QuotingType::None; } using TAPI_INTERNAL::AvailabilityInfo; void ScalarTraits<AvailabilityInfo>::output(const AvailabilityInfo &value, void *, raw_ostream &os) { if (value._unavailable) { os << "n/a"; return; } os << value._introduced; if (!value._obsoleted.empty()) os << ".." << value._obsoleted; } StringRef ScalarTraits<AvailabilityInfo>::input(StringRef scalar, void *, AvailabilityInfo &value) { if (scalar == "n/a") { value._unavailable = true; return {}; } auto split = scalar.split(".."); auto introduced = split.first.trim(); auto obsoleted = split.second.trim(); if (!value._introduced.parse32(introduced)) return "invalid packed version string."; if (obsoleted.empty()) return StringRef(); if (!value._obsoleted.parse32(obsoleted)) return "invalid packed version string."; return StringRef(); } QuotingType ScalarTraits<AvailabilityInfo>::mustQuote(StringRef) { return QuotingType::None; } void ScalarTraits<UUID>::output(const UUID &value, void *, raw_ostream &os) { os << value.first << ": " << value.second; } StringRef ScalarTraits<UUID>::input(StringRef scalar, void *, UUID &value) { auto split = scalar.split(':'); auto arch = split.first.trim(); auto uuid = split.second.trim(); if (uuid.empty()) return "invalid uuid string pair"; value.first = getArchType(arch); value.second = uuid; return {}; } QuotingType ScalarTraits<UUID>::mustQuote(StringRef) { return QuotingType::Single; } using clang::Language; void ScalarEnumerationTraits<Language>::enumeration(IO &io, Language &kind) { io.enumCase(kind, "c", Language::C); io.enumCase(kind, "cxx", Language::CXX); io.enumCase(kind, "objective-c", Language::ObjC); io.enumCase(kind, "objc", Language::ObjC); // to keep old snapshots working. io.enumCase(kind, "objective-cxx", Language::ObjCXX); io.enumCase(kind, "objcxx", Language::ObjCXX); // to keep old snapshots working. } } // end namespace yaml. } // end namespace llvm.
Remove ScalarTraits in implementation in tapi
Remove ScalarTraits in implementation in tapi swift-llvm now exposes ScalarTraits implementation for FlowStringRef and SwiftVersion in lib/TextAPI/MachO/TextStubCommon.h. This gets compiled in on all platforms, so remove the swift ones so they don't conflict.
C++
apache-2.0
atrick/swift,xwu/swift,parkera/swift,jckarter/swift,nathawes/swift,airspeedswift/swift,glessard/swift,tkremenek/swift,harlanhaskins/swift,aschwaighofer/swift,nathawes/swift,jmgc/swift,stephentyrone/swift,benlangmuir/swift,airspeedswift/swift,hooman/swift,aschwaighofer/swift,JGiola/swift,hooman/swift,airspeedswift/swift,tkremenek/swift,gregomni/swift,apple/swift,tkremenek/swift,benlangmuir/swift,aschwaighofer/swift,xwu/swift,apple/swift,allevato/swift,rudkx/swift,apple/swift,jmgc/swift,parkera/swift,CodaFi/swift,rudkx/swift,atrick/swift,jckarter/swift,rudkx/swift,jckarter/swift,stephentyrone/swift,jmgc/swift,hooman/swift,ahoppen/swift,hooman/swift,hooman/swift,ahoppen/swift,harlanhaskins/swift,atrick/swift,nathawes/swift,atrick/swift,benlangmuir/swift,roambotics/swift,parkera/swift,allevato/swift,tkremenek/swift,stephentyrone/swift,roambotics/swift,gregomni/swift,gregomni/swift,harlanhaskins/swift,xwu/swift,harlanhaskins/swift,CodaFi/swift,tkremenek/swift,JGiola/swift,airspeedswift/swift,JGiola/swift,roambotics/swift,jmgc/swift,stephentyrone/swift,nathawes/swift,tkremenek/swift,nathawes/swift,benlangmuir/swift,ahoppen/swift,roambotics/swift,ahoppen/swift,xwu/swift,parkera/swift,JGiola/swift,jckarter/swift,parkera/swift,airspeedswift/swift,CodaFi/swift,CodaFi/swift,apple/swift,hooman/swift,allevato/swift,stephentyrone/swift,parkera/swift,xwu/swift,allevato/swift,harlanhaskins/swift,benlangmuir/swift,airspeedswift/swift,jckarter/swift,hooman/swift,apple/swift,jmgc/swift,gregomni/swift,tkremenek/swift,jckarter/swift,parkera/swift,roambotics/swift,apple/swift,gregomni/swift,nathawes/swift,CodaFi/swift,jckarter/swift,allevato/swift,allevato/swift,gregomni/swift,allevato/swift,atrick/swift,glessard/swift,harlanhaskins/swift,JGiola/swift,parkera/swift,roambotics/swift,harlanhaskins/swift,aschwaighofer/swift,CodaFi/swift,airspeedswift/swift,atrick/swift,glessard/swift,JGiola/swift,xwu/swift,jmgc/swift,benlangmuir/swift,rudkx/swift,glessard/swift,glessard/swift,nathawes/swift,rudkx/swift,ahoppen/swift,CodaFi/swift,xwu/swift,stephentyrone/swift,ahoppen/swift,aschwaighofer/swift,stephentyrone/swift,jmgc/swift,aschwaighofer/swift,aschwaighofer/swift,glessard/swift,rudkx/swift
eed1439f5bf7158faa7e72decd2f31ef9fe33f29
src/IRMutator.cpp
src/IRMutator.cpp
#include "IRMutator.h" namespace Halide { namespace Internal { using std::vector; Expr IRMutator::mutate(Expr e) { if (e.defined()) { e.accept(this); } else { expr = Expr(); } stmt = Stmt(); return expr; } Stmt IRMutator::mutate(Stmt s) { if (s.defined()) { s.accept(this); } else { stmt = Stmt(); } expr = Expr(); return stmt; } template<typename T> void mutate_binary_operator(IRMutator *mutator, const T *op, Expr *expr, Stmt *stmt) { Expr a = mutator->mutate(op->a); Expr b = mutator->mutate(op->b); if (a.same_as(op->a) && b.same_as(op->b)) *expr = op; else *expr = T::make(a, b); *stmt = NULL; } void IRMutator::visit(const IntImm *op) {expr = op;} void IRMutator::visit(const FloatImm *op) {expr = op;} void IRMutator::visit(const Variable *op) {expr = op;} void IRMutator::visit(const Cast *op) { Expr value = mutate(op->value); if (value.same_as(op->value)) expr = op; else expr = Cast::make(op->type, value); } void IRMutator::visit(const Add *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Sub *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Mul *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Div *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Mod *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Min *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Max *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const EQ *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const NE *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const LT *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const LE *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const GT *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const GE *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const And *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Or *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Not *op) { Expr a = mutate(op->a); if (a.same_as(op->a)) expr = op; else expr = Not::make(a); } void IRMutator::visit(const Select *op) { Expr cond = mutate(op->condition); Expr t = mutate(op->true_value); Expr f = mutate(op->false_value); if (cond.same_as(op->condition) && t.same_as(op->true_value) && f.same_as(op->false_value)) expr = op; else expr = Select::make(cond, t, f); } void IRMutator::visit(const Load *op) { Expr index = mutate(op->index); if (index.same_as(op->index)) expr = op; else expr = Load::make(op->type, op->name, index, op->image, op->param); } void IRMutator::visit(const Ramp *op) { Expr base = mutate(op->base); Expr stride = mutate(op->stride); if (base.same_as(op->base) && stride.same_as(op->stride)) expr = op; else expr = Ramp::make(base, stride, op->width); } void IRMutator::visit(const Broadcast *op) { Expr value = mutate(op->value); if (value.same_as(op->value)) expr = op; else expr = Broadcast::make(value, op->width); } void IRMutator::visit(const Call *op) { vector<Expr > new_args(op->args.size()); bool changed = false; // Mutate the args for (size_t i = 0; i < op->args.size(); i++) { Expr old_arg = op->args[i]; Expr new_arg = mutate(old_arg); if (!new_arg.same_as(old_arg)) changed = true; new_args[i] = new_arg; } if (!changed) expr = op; else expr = Call::make(op->type, op->name, new_args, op->call_type, op->func, op->image, op->param); } void IRMutator::visit(const Let *op) { Expr value = mutate(op->value); Expr body = mutate(op->body); if (value.same_as(op->value) && body.same_as(op->body)) expr = op; else expr = Let::make(op->name, value, body); } void IRMutator::visit(const LetStmt *op) { Expr value = mutate(op->value); Stmt body = mutate(op->body); if (value.same_as(op->value) && body.same_as(op->body)) stmt = op; else stmt = LetStmt::make(op->name, value, body); } void IRMutator::visit(const PrintStmt *op) { vector<Expr > new_args(op->args.size()); bool args_changed = false; // Mutate the args for (size_t i = 0; i < op->args.size(); i++) { Expr old_arg = op->args[i]; Expr new_arg = mutate(old_arg); if (!new_arg.same_as(old_arg)) args_changed = true; new_args[i] = new_arg; } if (!args_changed) stmt = op; else stmt = PrintStmt::make(op->prefix, new_args); } void IRMutator::visit(const AssertStmt *op) { Expr condition = mutate(op->condition); if (condition.same_as(op->condition)) stmt = op; else stmt = AssertStmt::make(condition, op->message); } void IRMutator::visit(const Pipeline *op) { Stmt produce = mutate(op->produce); Stmt update = mutate(op->update); Stmt consume = mutate(op->consume); if (produce.same_as(op->produce) && update.same_as(op->update) && consume.same_as(op->consume)) { stmt = op; } else { stmt = Pipeline::make(op->name, produce, update, consume); } } void IRMutator::visit(const For *op) { Expr min = mutate(op->min); Expr extent = mutate(op->extent); Stmt body = mutate(op->body); if (min.same_as(op->min) && extent.same_as(op->extent) && body.same_as(op->body)) { stmt = op; } else { stmt = For::make(op->name, min, extent, op->for_type, body); } } void IRMutator::visit(const Store *op) { Expr value = mutate(op->value); Expr index = mutate(op->index); if (value.same_as(op->value) && index.same_as(op->index)) stmt = op; else stmt = Store::make(op->name, value, index); } void IRMutator::visit(const Provide *op) { vector<Expr > new_args(op->args.size()); bool args_changed = false; // Mutate the args for (size_t i = 0; i < op->args.size(); i++) { Expr old_arg = op->args[i]; Expr new_arg = mutate(old_arg); if (!new_arg.same_as(old_arg)) args_changed = true; new_args[i] = new_arg; } Expr value = mutate(op->value); if (!args_changed && value.same_as(op->value)) stmt = op; else stmt = Provide::make(op->name, value, new_args); } void IRMutator::visit(const Allocate *op) { Expr size = mutate(op->size); Stmt body = mutate(op->body); if (size.same_as(op->size) && body.same_as(op->body)) stmt = op; else stmt = Allocate::make(op->name, op->type, size, body); } void IRMutator::visit(const Free *op) { stmt = op; } void IRMutator::visit(const Realize *op) { Region new_bounds(op->bounds.size()); bool bounds_changed = false; // Mutate the bounds for (size_t i = 0; i < op->bounds.size(); i++) { Expr old_min = op->bounds[i].min; Expr old_extent = op->bounds[i].extent; Expr new_min = mutate(old_min); Expr new_extent = mutate(old_extent); if (!new_min.same_as(old_min)) bounds_changed = true; if (!new_extent.same_as(old_extent)) bounds_changed = true; new_bounds[i] = Range(new_min, new_extent); } Stmt body = mutate(op->body); if (!bounds_changed && body.same_as(op->body)) stmt = op; else stmt = Realize::make(op->name, op->type, new_bounds, body); } void IRMutator::visit(const Block *op) { Stmt first = mutate(op->first); Stmt rest = mutate(op->rest); if (first.same_as(op->first) && rest.same_as(op->rest)) stmt = op; else stmt = Block::make(first, rest); } } }
#include "IRMutator.h" namespace Halide { namespace Internal { using std::vector; Expr IRMutator::mutate(Expr e) { if (e.defined()) { e.accept(this); } else { expr = Expr(); } stmt = Stmt(); return expr; } Stmt IRMutator::mutate(Stmt s) { if (s.defined()) { s.accept(this); } else { stmt = Stmt(); } expr = Expr(); return stmt; } namespace { template<typename T> void mutate_binary_operator(IRMutator *mutator, const T *op, Expr *expr, Stmt *stmt) { Expr a = mutator->mutate(op->a); Expr b = mutator->mutate(op->b); if (a.same_as(op->a) && b.same_as(op->b)) *expr = op; else *expr = T::make(a, b); *stmt = NULL; } } void IRMutator::visit(const IntImm *op) {expr = op;} void IRMutator::visit(const FloatImm *op) {expr = op;} void IRMutator::visit(const Variable *op) {expr = op;} void IRMutator::visit(const Cast *op) { Expr value = mutate(op->value); if (value.same_as(op->value)) expr = op; else expr = Cast::make(op->type, value); } void IRMutator::visit(const Add *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Sub *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Mul *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Div *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Mod *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Min *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Max *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const EQ *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const NE *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const LT *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const LE *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const GT *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const GE *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const And *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Or *op) {mutate_binary_operator(this, op, &expr, &stmt);} void IRMutator::visit(const Not *op) { Expr a = mutate(op->a); if (a.same_as(op->a)) expr = op; else expr = Not::make(a); } void IRMutator::visit(const Select *op) { Expr cond = mutate(op->condition); Expr t = mutate(op->true_value); Expr f = mutate(op->false_value); if (cond.same_as(op->condition) && t.same_as(op->true_value) && f.same_as(op->false_value)) expr = op; else expr = Select::make(cond, t, f); } void IRMutator::visit(const Load *op) { Expr index = mutate(op->index); if (index.same_as(op->index)) expr = op; else expr = Load::make(op->type, op->name, index, op->image, op->param); } void IRMutator::visit(const Ramp *op) { Expr base = mutate(op->base); Expr stride = mutate(op->stride); if (base.same_as(op->base) && stride.same_as(op->stride)) expr = op; else expr = Ramp::make(base, stride, op->width); } void IRMutator::visit(const Broadcast *op) { Expr value = mutate(op->value); if (value.same_as(op->value)) expr = op; else expr = Broadcast::make(value, op->width); } void IRMutator::visit(const Call *op) { vector<Expr > new_args(op->args.size()); bool changed = false; // Mutate the args for (size_t i = 0; i < op->args.size(); i++) { Expr old_arg = op->args[i]; Expr new_arg = mutate(old_arg); if (!new_arg.same_as(old_arg)) changed = true; new_args[i] = new_arg; } if (!changed) expr = op; else expr = Call::make(op->type, op->name, new_args, op->call_type, op->func, op->image, op->param); } void IRMutator::visit(const Let *op) { Expr value = mutate(op->value); Expr body = mutate(op->body); if (value.same_as(op->value) && body.same_as(op->body)) expr = op; else expr = Let::make(op->name, value, body); } void IRMutator::visit(const LetStmt *op) { Expr value = mutate(op->value); Stmt body = mutate(op->body); if (value.same_as(op->value) && body.same_as(op->body)) stmt = op; else stmt = LetStmt::make(op->name, value, body); } void IRMutator::visit(const PrintStmt *op) { vector<Expr > new_args(op->args.size()); bool args_changed = false; // Mutate the args for (size_t i = 0; i < op->args.size(); i++) { Expr old_arg = op->args[i]; Expr new_arg = mutate(old_arg); if (!new_arg.same_as(old_arg)) args_changed = true; new_args[i] = new_arg; } if (!args_changed) stmt = op; else stmt = PrintStmt::make(op->prefix, new_args); } void IRMutator::visit(const AssertStmt *op) { Expr condition = mutate(op->condition); if (condition.same_as(op->condition)) stmt = op; else stmt = AssertStmt::make(condition, op->message); } void IRMutator::visit(const Pipeline *op) { Stmt produce = mutate(op->produce); Stmt update = mutate(op->update); Stmt consume = mutate(op->consume); if (produce.same_as(op->produce) && update.same_as(op->update) && consume.same_as(op->consume)) { stmt = op; } else { stmt = Pipeline::make(op->name, produce, update, consume); } } void IRMutator::visit(const For *op) { Expr min = mutate(op->min); Expr extent = mutate(op->extent); Stmt body = mutate(op->body); if (min.same_as(op->min) && extent.same_as(op->extent) && body.same_as(op->body)) { stmt = op; } else { stmt = For::make(op->name, min, extent, op->for_type, body); } } void IRMutator::visit(const Store *op) { Expr value = mutate(op->value); Expr index = mutate(op->index); if (value.same_as(op->value) && index.same_as(op->index)) stmt = op; else stmt = Store::make(op->name, value, index); } void IRMutator::visit(const Provide *op) { vector<Expr > new_args(op->args.size()); bool args_changed = false; // Mutate the args for (size_t i = 0; i < op->args.size(); i++) { Expr old_arg = op->args[i]; Expr new_arg = mutate(old_arg); if (!new_arg.same_as(old_arg)) args_changed = true; new_args[i] = new_arg; } Expr value = mutate(op->value); if (!args_changed && value.same_as(op->value)) stmt = op; else stmt = Provide::make(op->name, value, new_args); } void IRMutator::visit(const Allocate *op) { Expr size = mutate(op->size); Stmt body = mutate(op->body); if (size.same_as(op->size) && body.same_as(op->body)) stmt = op; else stmt = Allocate::make(op->name, op->type, size, body); } void IRMutator::visit(const Free *op) { stmt = op; } void IRMutator::visit(const Realize *op) { Region new_bounds(op->bounds.size()); bool bounds_changed = false; // Mutate the bounds for (size_t i = 0; i < op->bounds.size(); i++) { Expr old_min = op->bounds[i].min; Expr old_extent = op->bounds[i].extent; Expr new_min = mutate(old_min); Expr new_extent = mutate(old_extent); if (!new_min.same_as(old_min)) bounds_changed = true; if (!new_extent.same_as(old_extent)) bounds_changed = true; new_bounds[i] = Range(new_min, new_extent); } Stmt body = mutate(op->body); if (!bounds_changed && body.same_as(op->body)) stmt = op; else stmt = Realize::make(op->name, op->type, new_bounds, body); } void IRMutator::visit(const Block *op) { Stmt first = mutate(op->first); Stmt rest = mutate(op->rest); if (first.same_as(op->first) && rest.same_as(op->rest)) stmt = op; else stmt = Block::make(first, rest); } } }
Put local function in an anonymous namespace
Put local function in an anonymous namespace Former-commit-id: 2f2ca00b60b87c69b0a1b0480aebdb787b425fa1
C++
mit
darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide
0645c162cdc50554416abf581b804d2f4cd92a3c
src/MediaImpl.cpp
src/MediaImpl.cpp
#include "ExceptionHelpers.h" #include "ImagesImpl.h" #include "MediaImpl.h" #include "VideosImpl.h" using namespace Instagram; MediaImpl::MediaImpl(const MediaInfo& mediaInfo) : mInfo(mediaInfo), mImages(new ImagesImpl(*mediaInfo.mImageInfo)), mVideos(mediaInfo.mType == MediaType::Video ? new VideosImpl(*mediaInfo.mVideoInfo) : nullptr) { } std::string MediaImpl::getId() const { return mInfo.mId; } std::string MediaImpl::getLink() const { return mInfo.mLink; } std::string MediaImpl::getCaption() const { return mInfo.mCaption; } std::string MediaImpl::getCreatedTime() const { return mInfo.mCreatedTime; } MediaType MediaImpl::getType() const { return mInfo.mType; } std::string MediaImpl::getFilter() const { return mInfo.mFilter; } std::vector<std::string> MediaImpl::getTags() const { return mInfo.mTags; } ImagesPtr MediaImpl::getImages() const { return mImages; } VideosPtr MediaImpl::getVideos() const { if (mInfo.mType != MediaType::Video) Throw(GET_VIDEOS_FROM_NOT_VIDEO_MEDIA); return mVideos; } MediaPtr Instagram::CreateMedia(const MediaInfo& mediaInfo) { return MediaPtr(new MediaImpl(mediaInfo)); }
#include "ExceptionHelpers.h" #include "ImagesImpl.h" #include "MediaImpl.h" #include "VideosImpl.h" using namespace Instagram; MediaImpl::MediaImpl(const MediaInfo& mediaInfo) : mInfo(mediaInfo), mImages(CreateImagesImpl(mediaInfo.mImageInfo)), mVideos(mediaInfo.mType == MediaType::Video ? new VideosImpl(*mediaInfo.mVideoInfo) : nullptr) { } std::string MediaImpl::getId() const { return mInfo.mId; } std::string MediaImpl::getLink() const { return mInfo.mLink; } std::string MediaImpl::getCaption() const { return mInfo.mCaption; } std::string MediaImpl::getCreatedTime() const { return mInfo.mCreatedTime; } MediaType MediaImpl::getType() const { return mInfo.mType; } std::string MediaImpl::getFilter() const { return mInfo.mFilter; } std::vector<std::string> MediaImpl::getTags() const { return mInfo.mTags; } ImagesPtr MediaImpl::getImages() const { return mImages; } VideosPtr MediaImpl::getVideos() const { if (mInfo.mType != MediaType::Video) Throw(GET_VIDEOS_FROM_NOT_VIDEO_MEDIA); return mVideos; } MediaPtr Instagram::CreateMedia(const MediaInfo& mediaInfo) { return MediaPtr(new MediaImpl(mediaInfo)); }
Create ImagesImpl through factory function
Create ImagesImpl through factory function
C++
mit
gumb0/cpp-instagram,gumb0/cpp-instagram
21cadc48fa6e8e4309d3633e1249ce9eb1369a43
src/MixClient.cpp
src/MixClient.cpp
/* 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/>. */ /** @file MixClient.cpp * @author Arkadiy Paronyan [email protected] * @date 2015 * Ethereum IDE client. */ #include "MixClient.h" #include <vector> #include <utility> #include <libdevcore/Exceptions.h> #include <libethcore/Params.h> #include <libethcore/BasicAuthority.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/Transaction.h> #include <libethereum/Executive.h> #include <libethereum/ExtVM.h> #include <libethereum/BlockChain.h> #include <libevm/VM.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace mix { u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow namespace { } MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot): FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill) { } bytes MixBlockChain::createGenesisBlock(h256 _stateRoot) { RLPStream block(3); block.appendList(13) << h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_mixGenesisDifficulty << 0 << 3141592 << 0 << (unsigned)0 << std::string(); block.appendRaw(RLPEmptyList); block.appendRaw(RLPEmptyList); return block.out(); } MixClient::MixClient(std::string const& _dbPath): m_dbPath(_dbPath) { resetState(std::unordered_map<Address, Account>()); } MixClient::~MixClient() { } void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts, Secret const& _miner) { WriteGuard l(x_state); Guard fl(x_filtersWatches); m_filters.clear(); for (auto& i: m_specialFilters) i.second.clear(); m_watches.clear(); m_stateDB = OverlayDB(); SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB); accountState.init(); dev::eth::commit(_accounts, accountState); h256 stateRoot = accountState.root(); m_bc.reset(); m_bc.reset(new MixBlockChain(m_dbPath, stateRoot)); Block b(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address()); b.sync(bc()); m_preMine = b; m_postMine = b; WriteGuard lx(x_executions); m_executions.clear(); } Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret) { Transaction ret; if (_secret) { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret); } else { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce()); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce()); ret.forceSender(_t.safeSender()); } return ret; } // TODO: prototype changed - will need rejigging. ExecutionResult MixClient::debugTransaction(Transaction const& _t, State const& _state, EnvInfo const& _envInfo, bool _call) { State execState = _state; execState.addBalance(_t.sender(), _t.gas() * _t.gasPrice()); //give it enough balance for gas estimation eth::ExecutionResult er; Executive execution(execState, _envInfo); execution.setResultRecipient(er); ExecutionResult d; d.address = _t.receiveAddress(); d.sender = _t.sender(); d.value = _t.value(); d.inputParameters = _t.data(); d.executonIndex = m_executions.size(); if (!_call) d.transactionIndex = m_postMine.pending().size(); try { execution.initialize(_t); execution.execute(); } catch (Exception const& _e) { d.excepted = toTransactionException(_e); d.transactionData.push_back(_t.data()); return d; } std::vector<MachineState> machineStates; std::vector<unsigned> levels; std::vector<MachineCode> codes; std::map<bytes const*, unsigned> codeIndexes; std::vector<bytes> data; std::map<bytesConstRef const*, unsigned> dataIndexes; bytes const* lastCode = nullptr; bytesConstRef const* lastData = nullptr; unsigned codeIndex = 0; unsigned dataIndex = 0; auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt) { VM& vm = *static_cast<VM*>(voidVM); ExtVM const& ext = *static_cast<ExtVM const*>(voidExt); if (lastCode == nullptr || lastCode != &ext.code) { auto const& iter = codeIndexes.find(&ext.code); if (iter != codeIndexes.end()) codeIndex = iter->second; else { codeIndex = codes.size(); codes.push_back(MachineCode({ext.myAddress, ext.code})); codeIndexes[&ext.code] = codeIndex; } lastCode = &ext.code; } if (lastData == nullptr || lastData != &ext.data) { auto const& iter = dataIndexes.find(&ext.data); if (iter != dataIndexes.end()) dataIndex = iter->second; else { dataIndex = data.size(); data.push_back(ext.data.toBytes()); dataIndexes[&ext.data] = dataIndex; } lastData = &ext.data; } if (levels.size() < ext.depth) levels.push_back(machineStates.size() - 1); else levels.resize(ext.depth); machineStates.push_back(MachineState{ steps, vm.curPC(), inst, newMemSize, static_cast<u256>(gas), vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), std::move(levels), codeIndex, dataIndex }); }; execution.go(onOp); execution.finalize(); d.excepted = er.excepted; d.result = er; d.machineStates = machineStates; d.executionCode = std::move(codes); d.transactionData = std::move(data); d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend; if (_t.isCreation()) d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce()))); return d; } void MixClient::executeTransaction(Transaction const& _t, Block& _block, bool _call, bool _gasAuto, Secret const& _secret) { Transaction t = _gasAuto ? replaceGas(_t, m_postMine.gasLimitRemaining()) : _t; // do debugging run first EnvInfo envInfo(bc().info(), bc().lastHashes()); ExecutionResult d = debugTransaction(t, _block.state(), envInfo, _call); // execute on a state if (!_call && d.excepted == TransactionException::None) { u256 useGas = min(d.gasUsed, _block.gasLimitRemaining()); t = _gasAuto ? replaceGas(_t, useGas, _secret) : _t; eth::ExecutionResult const& er = _block.execute(envInfo.lastHashes(), t); if (t.isCreation() && _block.state().code(d.contractAddress).empty()) BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment")); d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend; LocalisedLogEntries logs; TransactionReceipt const& tr = _block.receipt(_block.pending().size() - 1); LogEntries le = tr.log(); if (le.size()) for (unsigned j = 0; j < le.size(); ++j) logs.insert(logs.begin(), LocalisedLogEntry(le[j])); d.logs = logs; } WriteGuard l(x_executions); m_executions.emplace_back(std::move(d)); } std::unordered_map<u256, u256> MixClient::contractStorage(Address _contract) { return m_preMine.state().storage(_contract); } void MixClient::mine() { WriteGuard l(x_state); m_postMine.commitToSeal(bc()); NoProof::BlockHeader h(m_postMine.info()); RLPStream header; h.streamRLP(header); m_postMine.sealBlock(header.out()); bc().import(m_postMine.blockData(), m_postMine.state().db(), (ImportRequirements::Everything & ~ImportRequirements::ValidSeal) != 0); m_postMine.sync(bc()); m_preMine = m_postMine; } ExecutionResult MixClient::lastExecution() const { ReadGuard l(x_executions); return m_executions.empty() ? ExecutionResult() : m_executions.back(); } ExecutionResult MixClient::execution(unsigned _index) const { ReadGuard l(x_executions); return m_executions.size() > _index ? m_executions.at(_index) : ExecutionResult(); } Block MixClient::asOf(h256 const& _block) const { ReadGuard l(x_state); Block ret(m_stateDB); ret.populateFromChain(bc(), _block); return ret; } pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto) { WriteGuard l(x_state); TransactionSkeleton ts = _ts; ts.from = toAddress(_secret); ts.nonce = m_postMine.transactionsFrom(ts.from); eth::Transaction t(ts, _secret); executeTransaction(t, m_postMine, false, _gasAuto, _secret); return make_pair(t.sha3(), toAddress(ts.from, ts.nonce)); } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff) { (void)_blockNumber; Block block = asOf(eth::PendingBlock); u256 n = block.transactionsFrom(_from); Transaction t(_value, _gasPrice, _gas, _dest, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) block.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, block, true, _gasAuto); return lastExecution().result; } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff); } dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { (void)_blockNumber; u256 n; Block temp; { ReadGuard lr(x_state); temp = asOf(eth::PendingBlock); n = temp.transactionsFrom(_from); } Transaction t(_value, _gasPrice, _gas, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, false); return lastExecution().result; } eth::BlockInfo MixClient::blockInfo() const { ReadGuard l(x_state); return BlockInfo(bc().block()); } void MixClient::setBeneficiary(Address const& _us) { WriteGuard l(x_state); m_postMine.setBeneficiary(_us); } void MixClient::startMining() { //no-op } void MixClient::stopMining() { //no-op } bool MixClient::isMining() const { return false; } u256 MixClient::hashrate() const { return 0; } eth::WorkingProgress MixClient::miningProgress() const { return eth::WorkingProgress(); } } }
/* 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/>. */ /** @file MixClient.cpp * @author Arkadiy Paronyan [email protected] * @date 2015 * Ethereum IDE client. */ #include "MixClient.h" #include <vector> #include <utility> #include <libdevcore/Exceptions.h> #include <libethcore/Params.h> #include <libethcore/BasicAuthority.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/Transaction.h> #include <libethereum/Executive.h> #include <libethereum/ExtVM.h> #include <libethereum/BlockChain.h> #include <libevm/VM.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace mix { u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow namespace { } MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot): FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill) { } bytes MixBlockChain::createGenesisBlock(h256 _stateRoot) { RLPStream block(3); block.appendList(13) << h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_mixGenesisDifficulty << 0 << 3141592 << 0 << (unsigned)0 << std::string(); block.appendRaw(RLPEmptyList); block.appendRaw(RLPEmptyList); return block.out(); } MixClient::MixClient(std::string const& _dbPath): m_dbPath(_dbPath) { resetState(std::unordered_map<Address, Account>()); } MixClient::~MixClient() { } void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts, Secret const& _miner) { WriteGuard l(x_state); Guard fl(x_filtersWatches); m_filters.clear(); for (auto& i: m_specialFilters) i.second.clear(); m_watches.clear(); m_stateDB = OverlayDB(); SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB); accountState.init(); dev::eth::commit(_accounts, accountState); h256 stateRoot = accountState.root(); m_bc.reset(); m_bc.reset(new MixBlockChain(m_dbPath, stateRoot)); Block b(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address()); b.sync(bc()); m_preMine = b; m_postMine = b; WriteGuard lx(x_executions); m_executions.clear(); } Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret) { Transaction ret; if (_secret) { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret); } else { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce()); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce()); ret.forceSender(_t.safeSender()); } return ret; } // TODO: prototype changed - will need rejigging. ExecutionResult MixClient::debugTransaction(Transaction const& _t, State const& _state, EnvInfo const& _envInfo, bool _call) { State execState = _state; execState.addBalance(_t.sender(), _t.gas() * _t.gasPrice()); //give it enough balance for gas estimation eth::ExecutionResult er; Executive execution(execState, _envInfo); execution.setResultRecipient(er); ExecutionResult d; d.address = _t.receiveAddress(); d.sender = _t.sender(); d.value = _t.value(); d.inputParameters = _t.data(); d.executonIndex = m_executions.size(); if (!_call) d.transactionIndex = m_postMine.pending().size(); try { execution.initialize(_t); execution.execute(); } catch (Exception const& _e) { d.excepted = toTransactionException(_e); d.transactionData.push_back(_t.data()); return d; } std::vector<MachineState> machineStates; std::vector<unsigned> levels; std::vector<MachineCode> codes; std::map<bytes const*, unsigned> codeIndexes; std::vector<bytes> data; std::map<bytesConstRef const*, unsigned> dataIndexes; bytes const* lastCode = nullptr; bytesConstRef const* lastData = nullptr; unsigned codeIndex = 0; unsigned dataIndex = 0; auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt) { VM& vm = *static_cast<VM*>(voidVM); ExtVM const& ext = *static_cast<ExtVM const*>(voidExt); if (lastCode == nullptr || lastCode != &ext.code) { auto const& iter = codeIndexes.find(&ext.code); if (iter != codeIndexes.end()) codeIndex = iter->second; else { codeIndex = codes.size(); codes.push_back(MachineCode({ext.myAddress, ext.code})); codeIndexes[&ext.code] = codeIndex; } lastCode = &ext.code; } if (lastData == nullptr || lastData != &ext.data) { auto const& iter = dataIndexes.find(&ext.data); if (iter != dataIndexes.end()) dataIndex = iter->second; else { dataIndex = data.size(); data.push_back(ext.data.toBytes()); dataIndexes[&ext.data] = dataIndex; } lastData = &ext.data; } if (levels.size() < ext.depth) levels.push_back(machineStates.size() - 1); else levels.resize(ext.depth); machineStates.push_back(MachineState{ steps, vm.curPC(), inst, newMemSize, static_cast<u256>(gas), vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), std::move(levels), codeIndex, dataIndex }); }; execution.go(onOp); execution.finalize(); d.excepted = er.excepted; d.result = er; d.machineStates = machineStates; d.executionCode = std::move(codes); d.transactionData = std::move(data); d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend; if (_t.isCreation()) d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce()))); return d; } void MixClient::executeTransaction(Transaction const& _t, Block& _block, bool _call, bool _gasAuto, Secret const& _secret) { Transaction t = _gasAuto ? replaceGas(_t, m_postMine.gasLimitRemaining()) : _t; // do debugging run first EnvInfo envInfo(bc().info(), bc().lastHashes()); ExecutionResult d = debugTransaction(t, _block.state(), envInfo, _call); // execute on a state if (!_call && d.excepted == TransactionException::None) { u256 useGas = min(d.gasUsed, _block.gasLimitRemaining()); t = _gasAuto ? replaceGas(_t, useGas, _secret) : _t; eth::ExecutionResult const& er = _block.execute(envInfo.lastHashes(), t); if (t.isCreation() && _block.state().code(d.contractAddress).empty()) BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment")); d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend; LocalisedLogEntries logs; TransactionReceipt const& tr = _block.receipt(_block.pending().size() - 1); LogEntries le = tr.log(); if (le.size()) for (unsigned j = 0; j < le.size(); ++j) logs.insert(logs.begin(), LocalisedLogEntry(le[j])); d.logs = logs; } WriteGuard l(x_executions); m_executions.emplace_back(std::move(d)); } std::unordered_map<u256, u256> MixClient::contractStorage(Address _contract) { return m_preMine.state().storage(_contract); } void MixClient::mine() { WriteGuard l(x_state); m_postMine.commitToSeal(bc()); NoProof::BlockHeader h(m_postMine.info()); RLPStream header; h.streamRLP(header); m_postMine.sealBlock(header.out()); bc().import(m_postMine.blockData(), m_postMine.state().db(), (ImportRequirements::Everything & ~ImportRequirements::ValidSeal) != 0); m_postMine.sync(bc()); m_preMine = m_postMine; } ExecutionResult MixClient::lastExecution() const { ReadGuard l(x_executions); return m_executions.empty() ? ExecutionResult() : m_executions.back(); } ExecutionResult MixClient::execution(unsigned _index) const { ReadGuard l(x_executions); return m_executions.size() > _index ? m_executions.at(_index) : ExecutionResult(); } Block MixClient::asOf(h256 const& _block) const { ReadGuard l(x_state); Block ret(m_stateDB); ret.populateFromChain(bc(), _block); return ret; } pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto) { TransactionSkeleton ts = _ts; ts.from = toAddress(_secret); ts.nonce = m_postMine.transactionsFrom(ts.from); if (ts.nonce == UndefinedU256) ts.nonce = max<u256>(postMine().transactionsFrom(ts.from), m_tq.maxNonce(ts.from)); if (ts.gasPrice == UndefinedU256) ts.gasPrice = gasBidPrice(); if (ts.gas == UndefinedU256) ts.gas = min<u256>(gasLimitRemaining() / 5, balanceAt(ts.from) / ts.gasPrice); WriteGuard l(x_state); eth::Transaction t(ts, _secret); executeTransaction(t, m_postMine, false, _gasAuto, _secret); return make_pair(t.sha3(), toAddress(ts.from, ts.nonce)); } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff) { (void)_blockNumber; Block block = asOf(eth::PendingBlock); u256 n = block.transactionsFrom(_from); u256 gas = _gas == UndefinedU256 ? gasLimitRemaining() : _gas; u256 gasPrice = _gasPrice == UndefinedU256 ? gasBidPrice() : _gasPrice; Transaction t(_value, gasPrice, gas, _dest, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) block.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, block, true, _gasAuto); return lastExecution().result; } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff); } dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { (void)_blockNumber; u256 n; Block temp; { ReadGuard lr(x_state); temp = asOf(eth::PendingBlock); n = temp.transactionsFrom(_from); } Transaction t(_value, _gasPrice, _gas, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, false); return lastExecution().result; } eth::BlockInfo MixClient::blockInfo() const { ReadGuard l(x_state); return BlockInfo(bc().block()); } void MixClient::setBeneficiary(Address const& _us) { WriteGuard l(x_state); m_postMine.setBeneficiary(_us); } void MixClient::startMining() { //no-op } void MixClient::stopMining() { //no-op } bool MixClient::isMining() const { return false; } u256 MixClient::hashrate() const { return 0; } eth::WorkingProgress MixClient::miningProgress() const { return eth::WorkingProgress(); } } }
set transaction/call gas defaults
set transaction/call gas defaults
C++
mit
yann300/mix,ethereum/mix,LianaHus/mix,yann300/mix,ethereum/mix,ethereum/mix,LefterisJP/mix,yann300/mix,LefterisJP/mix,LianaHus/mix,LefterisJP/mix,LianaHus/mix
0189ff6f9de445e0f88b43b2235a35743bbfb6f5
src/ParseNode.cpp
src/ParseNode.cpp
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include <functional> #include "ParseNode.hpp" #include "Context.hpp" #include "StringPool.hpp" #include "AssemblyFileWriter.hpp" #include "Utils.hpp" using std::list; using std::vector; using std::mem_fun; using std::bind2nd; using namespace eddic; void ParseNode::write(AssemblyFileWriter& writer) { for_each(begin(), end(), [&](std::shared_ptr<ParseNode> p){ p->write(writer); }); } void ParseNode::checkFunctions(Program& program){ for_each(begin(), end(), [&](std::shared_ptr<ParseNode> p){ p->checkFunctions(program); }); } void ParseNode::checkVariables() { for_each(begin(), end(), [](std::shared_ptr<ParseNode> p){ p->checkVariables(); }); } void ParseNode::checkStrings(StringPool& pool) { for_each(begin(), end(), [&](std::shared_ptr<ParseNode> p){ p->checkStrings(pool); }); } void ParseNode::optimize() { for_each(begin(), end(), [](std::shared_ptr<ParseNode> p){ p->optimize(); }); } void ParseNode::addLast(std::shared_ptr<ParseNode> node) { childs.push_back(node); node->parent = std::weak_ptr<ParseNode>(shared_from_this()); } void ParseNode::addFirst(std::shared_ptr<ParseNode> node) { childs.push_front(node); node->parent = std::weak_ptr<ParseNode>(shared_from_this()); } void ParseNode::replace(std::shared_ptr<ParseNode> old, std::shared_ptr<ParseNode> node) { node->parent = std::weak_ptr<ParseNode>(shared_from_this()); auto it = find(childs.begin(), childs.end(), old); if(it != childs.end()){ *it = node; } } void ParseNode::remove(std::shared_ptr<ParseNode> node) { childs.remove(node); } NodeIterator ParseNode::begin() { return childs.begin(); } NodeIterator ParseNode::end() { return childs.end(); }
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include "ParseNode.hpp" #include "Context.hpp" #include "StringPool.hpp" #include "AssemblyFileWriter.hpp" #include "Utils.hpp" using std::list; using std::vector; using std::mem_fun; using std::bind2nd; using namespace eddic; void ParseNode::write(AssemblyFileWriter& writer) { for_each(begin(), end(), [&](std::shared_ptr<ParseNode> p){ p->write(writer); }); } void ParseNode::checkFunctions(Program& program){ for_each(begin(), end(), [&](std::shared_ptr<ParseNode> p){ p->checkFunctions(program); }); } void ParseNode::checkVariables() { for_each(begin(), end(), [](std::shared_ptr<ParseNode> p){ p->checkVariables(); }); } void ParseNode::checkStrings(StringPool& pool) { for_each(begin(), end(), [&](std::shared_ptr<ParseNode> p){ p->checkStrings(pool); }); } void ParseNode::optimize() { for_each(begin(), end(), [](std::shared_ptr<ParseNode> p){ p->optimize(); }); } void ParseNode::addLast(std::shared_ptr<ParseNode> node) { childs.push_back(node); node->parent = std::weak_ptr<ParseNode>(shared_from_this()); } void ParseNode::addFirst(std::shared_ptr<ParseNode> node) { childs.push_front(node); node->parent = std::weak_ptr<ParseNode>(shared_from_this()); } void ParseNode::replace(std::shared_ptr<ParseNode> old, std::shared_ptr<ParseNode> node) { node->parent = std::weak_ptr<ParseNode>(shared_from_this()); auto it = find(childs.begin(), childs.end(), old); if(it != childs.end()){ *it = node; } } void ParseNode::remove(std::shared_ptr<ParseNode> node) { childs.remove(node); } NodeIterator ParseNode::begin() { return childs.begin(); } NodeIterator ParseNode::end() { return childs.end(); }
Remove old include of functional (replaced by lambda expressions)
Remove old include of functional (replaced by lambda expressions)
C++
mit
wichtounet/eddic,wichtounet/eddic,vogelsgesang/eddic,wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic
00372751a863e000ef58a7dea2a6d8614cca0929
src/Proximity.cpp
src/Proximity.cpp
/* cbr * Proximity.cpp * * Copyright (c) 2009, Ewen Cheslack-Postava * 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 cbr nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Proximity.hpp" #include "ObjectFactory.hpp" #include <algorithm> #include <prox/BruteForceQueryHandler.hpp> #include <prox/RTreeQueryHandler.hpp> namespace CBR { Proximity::Proximity(ObjectFactory* objfactory, LocationService* locservice) : mLastTime(0), mObjectFactory(objfactory), mLocCache(NULL), mHandler(NULL) { mLocCache = new CBRLocationServiceCache(locservice); Prox::BruteForceQueryHandler<ProxSimulationTraits>* bhandler = new Prox::BruteForceQueryHandler<ProxSimulationTraits>(); mHandler = bhandler; mHandler->initialize(mLocCache); } Proximity::~Proximity() { while(!mQueries.empty()) removeQuery( mQueries.begin()->first ); delete mHandler; } void Proximity::addQuery(UUID obj, const TimedMotionVector3f& loc, SolidAngle sa) { assert( mQueries.find(obj) == mQueries.end() ); Query* q = new Query(loc, sa); mQueries[obj] = q; mHandler->registerQuery(q); } void Proximity::removeQuery(UUID obj) { QueryMap::iterator it = mQueries.find(obj); assert(it != mQueries.end()); Query* q = it->second; mQueries.erase(it); delete q; // Note: Deleting query notifies QueryHandler and unsubscribes. } void Proximity::evaluate(const Time& t, std::queue<ProximityEventInfo>& events) { if ( ((uint32)(t-Time(0)).seconds()) - ((uint32)(mLastTime-Time(0)).seconds()) > 0) printf("Objects: %d, Queries: %d\n", mHandler->numObjects(), mHandler->numQueries()); mHandler->tick(t); mLastTime = t; typedef std::deque<QueryEvent> QueryEventList; for(QueryMap::iterator query_it = mQueries.begin(); query_it != mQueries.end(); query_it++) { UUID query_id = query_it->first; Query* query = query_it->second; QueryEventList evts; query->popEvents(evts); for(QueryEventList::iterator evt_it = evts.begin(); evt_it != evts.end(); evt_it++) { if (evt_it->type() == QueryEvent::Added) events.push(ProximityEventInfo(query_id, evt_it->id(), mLocCache->location(evt_it->id()), ProximityEventInfo::Entered)); else events.push(ProximityEventInfo(query_id, evt_it->id(), ProximityEventInfo::Exited)); } } } void Proximity::queryHasEvents(Query* query) { // Currently we don't use this directly, we just always iterate over all queries and check them. // FIXME we could store this information and only check the ones we get callbacks for here } } // namespace CBR
/* cbr * Proximity.cpp * * Copyright (c) 2009, Ewen Cheslack-Postava * 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 cbr nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Proximity.hpp" #include "ObjectFactory.hpp" #include <algorithm> #include <prox/BruteForceQueryHandler.hpp> #include <prox/RTreeQueryHandler.hpp> namespace CBR { Proximity::Proximity(ObjectFactory* objfactory, LocationService* locservice) : mLastTime(0), mObjectFactory(objfactory), mLocCache(NULL), mHandler(NULL) { mLocCache = new CBRLocationServiceCache(locservice); Prox::BruteForceQueryHandler<ProxSimulationTraits>* bhandler = new Prox::BruteForceQueryHandler<ProxSimulationTraits>(); mHandler = bhandler; mHandler->initialize(mLocCache); } Proximity::~Proximity() { while(!mQueries.empty()) removeQuery( mQueries.begin()->first ); delete mHandler; } void Proximity::addQuery(UUID obj, const TimedMotionVector3f& loc, SolidAngle sa) { assert( mQueries.find(obj) == mQueries.end() ); Query* q = mHandler->registerQuery(loc, sa); mQueries[obj] = q; } void Proximity::removeQuery(UUID obj) { QueryMap::iterator it = mQueries.find(obj); assert(it != mQueries.end()); Query* q = it->second; mQueries.erase(it); delete q; // Note: Deleting query notifies QueryHandler and unsubscribes. } void Proximity::evaluate(const Time& t, std::queue<ProximityEventInfo>& events) { if ( ((uint32)(t-Time(0)).seconds()) - ((uint32)(mLastTime-Time(0)).seconds()) > 0) printf("Objects: %d, Queries: %d\n", mHandler->numObjects(), mHandler->numQueries()); mHandler->tick(t); mLastTime = t; typedef std::deque<QueryEvent> QueryEventList; for(QueryMap::iterator query_it = mQueries.begin(); query_it != mQueries.end(); query_it++) { UUID query_id = query_it->first; Query* query = query_it->second; QueryEventList evts; query->popEvents(evts); for(QueryEventList::iterator evt_it = evts.begin(); evt_it != evts.end(); evt_it++) { if (evt_it->type() == QueryEvent::Added) events.push(ProximityEventInfo(query_id, evt_it->id(), mLocCache->location(evt_it->id()), ProximityEventInfo::Entered)); else events.push(ProximityEventInfo(query_id, evt_it->id(), ProximityEventInfo::Exited)); } } } void Proximity::queryHasEvents(Query* query) { // Currently we don't use this directly, we just always iterate over all queries and check them. // FIXME we could store this information and only check the ones we get callbacks for here } } // namespace CBR
Switch to use new prox interface for queries.
Switch to use new prox interface for queries.
C++
bsd-3-clause
sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata
7fc695d5362daf020279948069adefa157b053fd
src/TwitchBot.cpp
src/TwitchBot.cpp
#include <cpr/cpr.h> #include <fstream> #include <regex> #include <tw/reader.h> #include <utils.h> #include "permissions.h" #include "TwitchBot.h" #include "version.h" static const char *TWITCH_SERV = "irc.twitch.tv"; static const char *TWITCH_PORT = "80"; static std::string urltitle(const std::string &resp); TwitchBot::TwitchBot(const std::string &nick, const std::string &channel, const std::string &password, const std::string &token, ConfigReader *cfgr) : m_connected(false), m_nick(nick), m_channelName(channel), m_token(token), m_client(TWITCH_SERV, TWITCH_PORT), m_cmdHandler(nick, channel.substr(1), token, &m_mod, &m_parser, &m_event, &m_giveaway, cfgr, &m_auth), m_cfgr(cfgr), m_event(cfgr), m_giveaway(channel.substr(1), time(nullptr), cfgr), m_mod(&m_parser, cfgr) { std::string err; if ((m_connected = m_client.cconnect())) { /* send required IRC data: PASS, NICK, USER */ sendData("PASS " + password); sendData("NICK " + nick); sendData("USER " + nick); /* enable tags in PRIVMSGs */ sendData("CAP REQ :twitch.tv/tags"); /* join channel */ sendData("JOIN " + channel); m_tick = std::thread(&TwitchBot::tick, this); /* create giveaway checking event */ m_event.add("checkgiveaway", 10, time(nullptr)); /* read the subscriber messages */ parseSubMsg(m_subMsg, "submessage"); parseSubMsg(m_resubMsg, "resubmessage"); if (!utils::parseBool(m_urltitles, m_cfgr->get("url_titles"), err)) { std::cerr << m_cfgr->path() << ": url_titles: " << err << " (defaulting to true)" << std::endl; m_urltitles = true; std::cin.get(); } } } TwitchBot::~TwitchBot() { m_client.cdisconnect(); } bool TwitchBot::isConnected() const { return m_connected; } /* disconnect: disconnect from Twitch server */ void TwitchBot::disconnect() { m_client.cdisconnect(); m_connected = false; m_tick.join(); } /* serverLoop: continously receive and process data */ void TwitchBot::serverLoop() { std::string msg; /* continously receive data from server */ while (true) { if (m_client.cread(msg) <= 0) { std::cerr << "No data received. Exiting." << std::endl; disconnect(); break; } std::cout << "[RECV] " << msg << std::endl; processData(msg); if (!m_connected) break; } } /* sendData: format data and write to client */ bool TwitchBot::sendData(const std::string &data) { /* format string by adding CRLF */ std::string formatted = data + (utils::endsWith(data, "\r\n") ? "" : "\r\n"); /* send formatted data */ int32_t bytes = m_client.cwrite(formatted); std::cout << (bytes > 0 ? "[SENT] " : "Failed to send: ") << formatted << std::endl; /* return true iff data was sent succesfully */ return bytes > 0; } /* sendMsg: send a PRIVMSG to the connected channel */ bool TwitchBot::sendMsg(const std::string &msg) { return sendData("PRIVMSG " + m_channelName + " :" + msg); } /* sendPong: send an IRC PONG */ bool TwitchBot::sendPong(const std::string &ping) { /* first six chars are "PING :", server name starts after */ return sendData("PONG " + ping.substr(6)); } /* processData: send data to designated function */ void TwitchBot::processData(const std::string &data) { if (data.find("Error logging in") != std::string::npos || data.find("Login unsuccessful") != std::string::npos) { disconnect(); std::cerr << "\nCould not log in to Twitch IRC.\nMake sure " << utils::configdir() << utils::config("config") << " is configured correctly." << std::endl; std::cin.get(); } else if (utils::startsWith(data, "PING")) { sendPong(data); } else if (data.find("PRIVMSG") != std::string::npos) { processPRIVMSG(data); } } /* processPRIVMSG: parse a chat message and perform relevant actions */ bool TwitchBot::processPRIVMSG(const std::string &PRIVMSG) { /* regex to extract all necessary data from message */ static const std::regex privmsgRegex("mod=(\\d).*subscriber=(\\d).*" ":(\\w+)!\\3@\\3.* PRIVMSG (#\\w+) :(.+)"); static const std::regex subRegex(":twitchnotify.* PRIVMSG (#\\w+) " ":(.+) (?:just subscribed!|subscribed for (\\d+) " "months)"); std::smatch match; cpr::Response resp; if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, privmsgRegex)) { const std::string nick = match[3].str(); const std::string channel = match[4].str(); const std::string msg = match[5].str(); /* confirm message is from current channel */ if (channel != m_channelName) return false; /* set user privileges */ perm_t p; P_RESET(p); if (nick == channel.substr(1) || nick == "brainsoldier") P_STOWN(p); if (match[1].str() == "1") P_STMOD(p); if (match[2].str() == "1") P_STSUB(p); /* check if the message contains a URL */ m_parser.parse(msg); /* check if message is valid */ if (P_ISREG(p) && m_mod.active() && moderate(nick, msg)) return true; /* all chat commands i with $ */ if (utils::startsWith(msg, "$") && msg.length() > 1) { std::string output = m_cmdHandler.processCommand( nick, msg.substr(1), p); if (!output.empty()) sendMsg(output); return true; } /* count */ if (m_cmdHandler.isCounting() && utils::startsWith(msg, "+") && msg.length() > 1) { m_cmdHandler.count(nick, msg.substr(1)); return true; } /* link information */ if (m_parser.wasModified()) { URLParser::URL *url = m_parser.getLast(); /* print info about twitter statuses */ if (url->twitter && !url->tweetID.empty()) { tw::Reader twr(&m_auth); if (twr.read_tweet(url->tweetID)) { sendMsg(twr.result()); return true; } std::cerr << "could not read tweet" << std::endl; return false; } /* get the title of the url otherwise */ if (m_urltitles) { resp = cpr::Get(cpr::Url(url->full), cpr::Header{{ "Connection", "close" }}); std::string title; std::string s = url->subdomain + url->domain; if (!(title = urltitle(resp.text)).empty()) { sendMsg("[URL] " + title + " (at " + s + ")"); return true; } return false; } } /* check for responses */ std::string output = m_cmdHandler.processResponse(msg); if (!output.empty()) sendMsg("@" + nick + ", " + output); return true; } else if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, subRegex)) { /* send sub/resub messages */ std::string nick, fmt, len; nick = match[2].str(); if (match[3].str().empty()) { fmt = m_subMsg; len = "1"; } else { fmt = m_resubMsg; len = match[3].str(); } if (!fmt.empty()) sendMsg(formatSubMsg(fmt, nick, len)); return true; } else { std::cerr << "Could not extract data" << std::endl; return false; } return false; } /* moderate: check if message is valid; penalize nick if not */ bool TwitchBot::moderate(const std::string &nick, const std::string &msg) { std::string reason; if (!m_mod.isValidMsg(msg, nick, reason)) { uint8_t offenses = m_mod.getOffenses(nick); static const std::string warnings[3] = { "first", "second", "FINAL" }; std::string warning; if (offenses < 4) { /* timeout for 2^(offenses - 1) minutes */ uint16_t t = 60 * (uint16_t)pow(2, offenses - 1); sendMsg("/timeout " + nick + " " + std::to_string(t)); warning = warnings[offenses - 1] + " warning"; } else { sendMsg("/ban " + nick); warning = "Permanently banned"; } sendMsg(nick + " - " + reason + " (" + warning + ")"); return true; } return false; } /* tick: repeatedly check variables and perform actions if conditions met */ void TwitchBot::tick() { /* check every second */ while (m_connected) { for (std::vector<std::string>::size_type i = 0; i < m_event.messages()->size(); ++i) { if (m_event.ready("msg" + std::to_string(i))) { if (m_event.messagesActive()) sendMsg(((*m_event.messages())[i]).first); m_event.setUsed("msg" + std::to_string(i)); break; } } if (m_giveaway.active() && m_event.ready("checkgiveaway")) { if (m_giveaway.checkConditions(time(nullptr))) sendMsg(m_giveaway.giveaway()); m_event.setUsed("checkgiveaway"); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } /* parseSubMsg: read which from m_cfgr into tgt and verify validity */ void TwitchBot::parseSubMsg(std::string &tgt, const std::string &which) { static const std::string fmt_c = "%Ncmn"; size_t ind; std::string fmt, err; char c; ind = -1; fmt = m_cfgr->get(which); while ((ind = fmt.find('%', ind + 1)) != std::string::npos) { if (ind == fmt.length() - 1) { err = "unexpected end of line after '%'"; break; } c = fmt[ind + 1]; if (fmt_c.find(c) == std::string::npos) { err = "invalid format character -- '"; err += c; err += "'"; break; } if (c == '%') ++ind; } if (!err.empty()) { std::cerr << m_cfgr->path() << ": " << which << ": " << err << std::endl; std::cin.get(); fmt = ""; } tgt = fmt; } /* formatSubMsg: replace placeholders in format string with data */ std::string TwitchBot::formatSubMsg(const std::string &format, const std::string &n, const std::string &m) { size_t ind; std::string out, ins; char c; ind = 0; out = format; while ((ind = out.find('%', ind)) != std::string::npos) { c = out[ind + 1]; out.erase(ind, 2); switch (c) { case '%': ins = "%"; break; case 'N': ins = "@" + n + ","; break; case 'c': ins = m_channelName.substr(1); break; case 'm': ins = m; break; case 'n': ins = n; break; default: break; } out.insert(ind, ins); ind += ins.length(); } return out; } /* map of html encoded characters */ static std::unordered_map<std::string, char> encoded = { { "amp", '&' }, { "gt", '>' }, { "lt", '<' }, { "quot", '"' } }; /* urltitle: extract webpage title from html */ static std::string urltitle(const std::string &resp) { size_t i; std::string title, enc; if ((i = resp.find("<title>")) != std::string::npos) { for (i += 7; resp[i] != '<'; ++i) { if (resp[i] == '&') { enc.clear(); for (++i; resp[i] != ';'; ++i) enc += resp[i]; title += encoded[enc]; ++i; } title += resp[i] == '\n' ? ' ' : resp[i]; } return title; } return ""; }
#include <cpr/cpr.h> #include <fstream> #include <regex> #include <tw/reader.h> #include <utils.h> #include "permissions.h" #include "TwitchBot.h" #include "version.h" static const char *TWITCH_SERV = "irc.twitch.tv"; static const char *TWITCH_PORT = "80"; static std::string urltitle(const std::string &resp); TwitchBot::TwitchBot(const std::string &nick, const std::string &channel, const std::string &password, const std::string &token, ConfigReader *cfgr) : m_connected(false), m_nick(nick), m_channelName(channel), m_token(token), m_client(TWITCH_SERV, TWITCH_PORT), m_cmdHandler(nick, channel.substr(1), token, &m_mod, &m_parser, &m_event, &m_giveaway, cfgr, &m_auth), m_cfgr(cfgr), m_event(cfgr), m_giveaway(channel.substr(1), time(nullptr), cfgr), m_mod(&m_parser, cfgr) { std::string err; if ((m_connected = m_client.cconnect())) { /* send required IRC data: PASS, NICK, USER */ sendData("PASS " + password); sendData("NICK " + nick); sendData("USER " + nick); /* enable tags in PRIVMSGs */ sendData("CAP REQ :twitch.tv/tags"); /* join channel */ sendData("JOIN " + channel); m_tick = std::thread(&TwitchBot::tick, this); /* create giveaway checking event */ m_event.add("checkgiveaway", 10, time(nullptr)); /* read the subscriber messages */ parseSubMsg(m_subMsg, "submessage"); parseSubMsg(m_resubMsg, "resubmessage"); if (!utils::parseBool(m_urltitles, m_cfgr->get("url_titles"), err)) { std::cerr << m_cfgr->path() << ": url_titles: " << err << " (defaulting to true)" << std::endl; m_urltitles = true; std::cin.get(); } } } TwitchBot::~TwitchBot() { m_client.cdisconnect(); } bool TwitchBot::isConnected() const { return m_connected; } /* disconnect: disconnect from Twitch server */ void TwitchBot::disconnect() { m_client.cdisconnect(); m_connected = false; m_tick.join(); } /* serverLoop: continously receive and process data */ void TwitchBot::serverLoop() { std::string msg; /* continously receive data from server */ while (true) { if (m_client.cread(msg) <= 0) { std::cerr << "No data received. Exiting." << std::endl; disconnect(); break; } std::cout << "[RECV] " << msg << std::endl; processData(msg); if (!m_connected) break; } } /* sendData: format data and write to client */ bool TwitchBot::sendData(const std::string &data) { /* format string by adding CRLF */ std::string formatted = data + (utils::endsWith(data, "\r\n") ? "" : "\r\n"); /* send formatted data */ int32_t bytes = m_client.cwrite(formatted); std::cout << (bytes > 0 ? "[SENT] " : "Failed to send: ") << formatted << std::endl; /* return true iff data was sent succesfully */ return bytes > 0; } /* sendMsg: send a PRIVMSG to the connected channel */ bool TwitchBot::sendMsg(const std::string &msg) { return sendData("PRIVMSG " + m_channelName + " :" + msg); } /* sendPong: send an IRC PONG */ bool TwitchBot::sendPong(const std::string &ping) { /* first six chars are "PING :", server name starts after */ return sendData("PONG " + ping.substr(6)); } /* processData: send data to designated function */ void TwitchBot::processData(const std::string &data) { if (data.find("Error logging in") != std::string::npos || data.find("Login unsuccessful") != std::string::npos) { disconnect(); std::cerr << "\nCould not log in to Twitch IRC.\nMake sure " << utils::configdir() << utils::config("config") << " is configured correctly." << std::endl; std::cin.get(); } else if (utils::startsWith(data, "PING")) { sendPong(data); } else if (data.find("PRIVMSG") != std::string::npos) { processPRIVMSG(data); } } /* processPRIVMSG: parse a chat message and perform relevant actions */ bool TwitchBot::processPRIVMSG(const std::string &PRIVMSG) { /* regex to extract all necessary data from message */ static const std::regex privmsgRegex("mod=(\\d).*subscriber=(\\d).*" ":(\\w+)!\\3@\\3.* PRIVMSG (#\\w+) :(.+)"); static const std::regex subRegex(":twitchnotify.* PRIVMSG (#\\w+) " ":(.+) (?:just subscribed!|subscribed for (\\d+) " "months)"); std::smatch match; cpr::Response resp; if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, privmsgRegex)) { const std::string nick = match[3].str(); const std::string channel = match[4].str(); const std::string msg = match[5].str(); /* confirm message is from current channel */ if (channel != m_channelName) return false; /* set user privileges */ perm_t p; P_RESET(p); if (nick == channel.substr(1) || nick == "brainsoldier") P_STOWN(p); if (match[1].str() == "1") P_STMOD(p); if (match[2].str() == "1") P_STSUB(p); /* check if the message contains a URL */ m_parser.parse(msg); /* check if message is valid */ if (P_ISREG(p) && m_mod.active() && moderate(nick, msg)) return true; /* all chat commands i with $ */ if (utils::startsWith(msg, "$") && msg.length() > 1) { std::string output = m_cmdHandler.processCommand( nick, msg.substr(1), p); if (!output.empty()) sendMsg(output); return true; } /* count */ if (m_cmdHandler.isCounting() && utils::startsWith(msg, "+") && msg.length() > 1) { m_cmdHandler.count(nick, msg.substr(1)); return true; } /* link information */ if (m_parser.wasModified()) { URLParser::URL *url = m_parser.getLast(); /* print info about twitter statuses */ if (url->twitter && !url->tweetID.empty()) { tw::Reader twr(&m_auth); if (twr.read_tweet(url->tweetID)) { sendMsg(twr.result()); return true; } std::cerr << "could not read tweet" << std::endl; return false; } /* get the title of the url otherwise */ if (m_urltitles) { resp = cpr::Get(cpr::Url(url->full), cpr::Header{{ "Connection", "close" }}); std::string title; std::string s = url->subdomain + url->domain; if (!(title = urltitle(resp.text)).empty()) { sendMsg("[URL] " + title + " (at " + s + ")"); return true; } return false; } } /* check for responses */ std::string output = m_cmdHandler.processResponse(msg); if (!output.empty()) sendMsg("@" + nick + ", " + output); return true; } else if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, subRegex)) { /* send sub/resub messages */ std::string nick, fmt, len; nick = match[2].str(); if (match[3].str().empty()) { fmt = m_subMsg; len = "1"; } else { fmt = m_resubMsg; len = match[3].str(); } if (!fmt.empty()) sendMsg(formatSubMsg(fmt, nick, len)); return true; } else { std::cerr << "Could not extract data" << std::endl; return false; } return false; } /* moderate: check if message is valid; penalize nick if not */ bool TwitchBot::moderate(const std::string &nick, const std::string &msg) { std::string reason; if (!m_mod.isValidMsg(msg, nick, reason)) { uint8_t offenses = m_mod.getOffenses(nick); static const std::string warnings[3] = { "first", "second", "FINAL" }; std::string warning; if (offenses < 4) { /* timeout for 2^(offenses - 1) minutes */ uint16_t t = 60 * (uint16_t)pow(2, offenses - 1); sendMsg("/timeout " + nick + " " + std::to_string(t)); warning = warnings[offenses - 1] + " warning"; } else { sendMsg("/ban " + nick); warning = "Permanently banned"; } sendMsg(nick + " - " + reason + " (" + warning + ")"); return true; } return false; } /* tick: repeatedly check variables and perform actions if conditions met */ void TwitchBot::tick() { /* check every second */ while (m_connected) { for (std::vector<std::string>::size_type i = 0; i < m_event.messages()->size(); ++i) { if (m_event.ready("msg" + std::to_string(i))) { if (m_event.messagesActive()) sendMsg(((*m_event.messages())[i]).first); m_event.setUsed("msg" + std::to_string(i)); break; } } if (m_giveaway.active() && m_event.ready("checkgiveaway")) { if (m_giveaway.checkConditions(time(nullptr))) sendMsg(m_giveaway.giveaway()); m_event.setUsed("checkgiveaway"); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } /* parseSubMsg: read which from m_cfgr into tgt and verify validity */ void TwitchBot::parseSubMsg(std::string &tgt, const std::string &which) { static const std::string fmt_c = "%Ncmn"; size_t ind; std::string fmt, err; char c; ind = -1; fmt = m_cfgr->get(which); while ((ind = fmt.find('%', ind + 1)) != std::string::npos) { if (ind == fmt.length() - 1) { err = "unexpected end of line after '%'"; break; } c = fmt[ind + 1]; if (fmt_c.find(c) == std::string::npos) { err = "invalid format character -- '"; err += c; err += "'"; break; } if (c == '%') ++ind; } if (!err.empty()) { std::cerr << m_cfgr->path() << ": " << which << ": " << err << std::endl; std::cin.get(); fmt = ""; } tgt = fmt; } /* formatSubMsg: replace placeholders in format string with data */ std::string TwitchBot::formatSubMsg(const std::string &format, const std::string &n, const std::string &m) { size_t ind; std::string out, ins; char c; ind = 0; out = format; while ((ind = out.find('%', ind)) != std::string::npos) { c = out[ind + 1]; out.erase(ind, 2); switch (c) { case '%': ins = "%"; break; case 'N': ins = "@" + n + ","; break; case 'c': ins = m_channelName.substr(1); break; case 'm': ins = m; break; case 'n': ins = n; break; default: break; } out.insert(ind, ins); ind += ins.length(); } return out; } /* map of html encoded characters */ static std::unordered_map<std::string, char> encoded = { { "amp", '&' }, { "gt", '>' }, { "lt", '<' }, { "quot", '"' }, }; /* urltitle: extract webpage title from html */ static std::string urltitle(const std::string &resp) { size_t i; std::string title, enc; if ((i = resp.find("<title>")) != std::string::npos) { for (i += 7; resp[i] != '<'; ++i) { if (resp[i] == '&') { enc.clear(); for (++i; resp[i] != ';'; ++i) enc += resp[i]; title += encoded[enc]; ++i; } title += resp[i] == '\n' ? ' ' : resp[i]; } return title; } return ""; }
Add HTML chars
Add HTML chars
C++
mit
frolv/lynxbot,frolv/osrs-twitch-bot,frolv/osrs-twitch-bot,frolv/lynxbot
797596bfbad8f9f8b29d8c4e1d0cd460a6b321c8
src/options.cpp
src/options.cpp
#include "options.h" #include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> program_options options = {".",false,false,false,false,false,8 }; bool get_options(int argc, char* argv[]){ int c; opterr = 0; while ((c = getopt (argc, argv, "adfhl:v")) != -1){ switch (c){ case 'a': options.include_hidden = true; break; case 'd': options.directories_only = true; break; case 'f': options.files_only = true; break; case 'h': options.show_help = true; break; case 'l': options.number_of_result_lines = std::atoi(optarg); break; case 'v': options.show_version = true; break; case '?': if (optopt == 'l') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option '-%c'.\n", optopt); else fprintf (stderr, "Unknown option character '\\x%x'.\n", optopt); return false; default: abort (); } } if(optind < argc){ options.search_dir = std::string(argv[optind]); } return true; } void print_version(){ fprintf(stderr,"search version %s\n",SEARCHVERSION); } void print_help(){ fprintf(stderr,"Usage: search [OPTION]... DIRECTORY\n"); fprintf(stderr,"\n"); fprintf(stderr,"Options:\n"); fprintf(stderr," -h show this help message and exit.\n"); fprintf(stderr," -v show version info and exit.\n"); fprintf(stderr," -a do not ignore entries starting with '.'.\n"); fprintf(stderr," -l L use L number of lines to show result.\n"); fprintf(stderr," -f search only for files. ignore directories.\n"); fprintf(stderr," -d search only for directories. ignore files.\n"); }
#include "options.h" #include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> #include <getopt.h> program_options options = {".",false,false,false,false,false,8 }; bool get_options(int argc, char* argv[]){ int c; while (1){ static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"all", no_argument, 0, 'a'}, {"lines", required_argument, 0, 'l'}, {"dirs-only", no_argument, 0, 'd'}, {"files-only", no_argument, 0, 'f'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "hval:df", long_options, &option_index); if (c == -1) break; switch (c){ case 'h': options.show_help = true; break; case 'v': options.show_version = true; break; case 'a': options.include_hidden = true; break; case 'l': options.number_of_result_lines = std::atoi(optarg); break; case 'd': options.directories_only = true; break; case 'f': options.files_only = true; break; case '?': /* getopt_long already printed an error message. */ return false; default: abort (); } } if(optind < argc){ options.search_dir = std::string(argv[optind]); } return true; } void print_version(){ fprintf(stderr,"search version %s\n",SEARCHVERSION); } void print_help(){ fprintf(stderr,"Usage: search [OPTION]... DIRECTORY\n"); fprintf(stderr,"\n"); fprintf(stderr,"Options:\n"); fprintf(stderr," -h --help show this help message and exit.\n"); fprintf(stderr," -v --version show version info and exit.\n"); fprintf(stderr," -a --all do not ignore entries starting with '.'.\n"); fprintf(stderr," -d --dirs-only search only for directories. ignore files.\n"); fprintf(stderr," -f --files-only search only for files. ignore directories.\n"); fprintf(stderr," -l L --lines=L use L number of lines to show result.\n"); }
Switch from getopt to getopt_long.
Switch from getopt to getopt_long.
C++
mit
actinium/search,actinium/search
d45f70d52556d0f2323123788bb9d2d2d1b7e534
src/URLParser.cpp
src/URLParser.cpp
#include <ctype.h> #include <regex> #include "URLParser.h" URLParser::URLParser() :m_modified(false) { } /* parse: search message for URL and extract data into m_last */ bool URLParser::parse(const std::string &url) { std::regex urlRegex("(?:https?://)?(?:www\\.)?([a-zA-Z0-9]+\\.)*" "([a-zA-Z0-9\\-]+)((?:\\.[a-zA-Z]{2,4}){1,4})(/.+)?\\b"); std::smatch match; if ((m_modified = std::regex_search(url.begin(), url.end(), match, urlRegex))) { /* get the domain name */ std::string website = match[2].str() + match[3].str(); m_last.full = match[0].str(); m_last.domain = website; m_last.subdomain = match[1].str(); m_last.tweetID = ""; if ((m_last.twitter = website == "twitter.com")) { /* check if the URL is a twitter status */ std::string::size_type ind; if (match.size() > 3 && (ind = match[4].str().find("status/")) != std::string::npos) { std::string s = match[4].str().substr(ind + 7); for (char c : s) { if (!isdigit(c)) break; m_last.tweetID += c; } } } } return m_modified; } URLParser::URL *URLParser::getLast() { return &m_last; } bool URLParser::wasModified() { return m_modified; }
#include <ctype.h> #include <regex> #include "URLParser.h" URLParser::URLParser() :m_modified(false) { } /* parse: search message for URL and extract data into m_last */ bool URLParser::parse(const std::string &url) { std::regex urlRegex("(?:https?://)?(?:www\\.)?([a-zA-Z0-9]+\\.)*" "([a-zA-Z0-9\\-]+)((?:\\.[a-zA-Z]{2,3}){1,4})(/.+)?\\b"); std::smatch match; if ((m_modified = std::regex_search(url.begin(), url.end(), match, urlRegex))) { /* get the domain name */ std::string website = match[2].str() + match[3].str(); m_last.full = match[0].str(); m_last.domain = website; m_last.subdomain = match[1].str(); m_last.tweetID = ""; if ((m_last.twitter = website == "twitter.com")) { /* check if the URL is a twitter status */ std::string::size_type ind; if (match.size() > 3 && (ind = match[4].str().find("status/")) != std::string::npos) { std::string s = match[4].str().substr(ind + 7); for (char c : s) { if (!isdigit(c)) break; m_last.tweetID += c; } } } } return m_modified; } URLParser::URL *URLParser::getLast() { return &m_last; } bool URLParser::wasModified() { return m_modified; }
Update URL regex
Update URL regex
C++
mit
frolv/lynxbot,frolv/osrs-twitch-bot,frolv/lynxbot,frolv/osrs-twitch-bot
45e96831ffbd684544fa843691967623ba875b74
book/CppPkg/Library/VcppCrt.cpp
book/CppPkg/Library/VcppCrt.cpp
/* * ===================================================================================== * * Filename: VcppCrt.cpp * * Description: * * Version: 1.0 * Created: 04/17/2013 07:54:10 PM * Revision: none * Compiler: gcc * * Author: DAI ZHENGHUA (), [email protected] * Company: * * ===================================================================================== */ #include "cpp.h" #include <vector> _STD_BEGIN void _Throw(stdext::exception const &){} void _String_base::_Xran(){} void _String_base::_Xlen(){} void (__cdecl* std::_Raise_handler)(class stdext::exception const &); _STD_END extern "C"{ void _invalid_parameter_noinfo(){} } // extern "C"{
/* * ===================================================================================== * * Filename: VcppCrt.cpp * * Description: * * Version: 1.0 * Created: 04/17/2013 07:54:10 PM * Revision: none * Compiler: gcc * * Author: DAI ZHENGHUA (), [email protected] * Company: * * ===================================================================================== */ #include "cpp.h" /* #include <vector> _STD_BEGIN void _Throw(stdext::exception const &){} void _String_base::_Xran(){} void _String_base::_Xlen(){} void (__cdecl* std::_Raise_handler)(class stdext::exception const &); _STD_END */ extern "C"{ void _invalid_parameter_noinfo(){} } // extern "C"{
remove std support for Microsoft VC++ compiler
remove std support for Microsoft VC++ compiler
C++
apache-2.0
zszszsz/uefi-programming,killbug2004/uefi-programming,zszszsz/uefi-programming,killbug2004/uefi-programming,killbug2004/uefi-programming,zhenghuadai/uefi-programming,zszszsz/uefi-programming,zhenghuadai/uefi-programming,zszszsz/uefi-programming,killbug2004/uefi-programming,zhenghuadai/uefi-programming,zhenghuadai/uefi-programming
094afb9430fea751579bba95eb64de3f2cd40727
src/parsing.cpp
src/parsing.cpp
// Copyright 2016 Etix Labs // // 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 "server.h" #include <iostream> #include <string.h> // Set config defaults or from env void parse_env(std::shared_ptr<t_config> &config) { // Address config->address = DEFAULT_ADDRESS; if (const char *address = std::getenv("RTSP_ADDRESS")) { config->address = address; } // Port config->port = DEFAULT_PORT; if (const char *port = std::getenv("RTSP_PORT")) { config->port = port; } // Route config->route = DEFAULT_ROUTE; if (const char *route = std::getenv("RTSP_ROUTE")) { config->route = route; } // Username config->username = DEFAULT_USERNAME; if (const char *username = std::getenv("RTSP_USERNAME")) { config->username = username; } // Password config->password = DEFAULT_PASSWORD; if (const char *password = std::getenv("RTSP_PASSWORD")) { config->password = password; } // Framerate config->framerate = DEFAULT_FRAMERATE; if (const char *framerate = std::getenv("RTSP_FRAMERATE")) { config->framerate = framerate; } // Scale config->scale = std::make_pair<std::string, std::string>(DEFAULT_WIDTH, DEFAULT_HEIGHT); if (const char *scale = std::getenv("RTSP_RESOLUTION")) { size_t pos = 0; std::string scale_str(scale); if ((pos = scale_str.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale argument: " << scale_str << std::endl << "Using default values"; } else { config->scale = std::make_pair<std::string, std::string>( scale_str.substr(0, pos), scale_str.substr(pos + 1)); } } // Input config->input = DEFAULT_INPUT; if (const char *input = std::getenv("INPUT")) { config->input = input; } config->time = DEFAULT_TIME_ENABLED; if (const char *time = std::getenv("ENABLE_TIME_OVERLAY")) { if (strcmp(time, "false") == 0) { config->time = false; } else { config->time = true; } } } // Overwrite default parameters via cmd line bool parse_args(std::shared_ptr<t_config> &config, int argc, char **argv) { int c; opterr = 0; while ((c = getopt(argc, argv, "r:u:l:p:b:f:s:i:ht")) != -1) { switch (c) { case 'r': // Route if (optarg && optarg[0] == '-') { break; } if (not optarg[0] == '/') { config->route = "/"; } config->route += optarg; break; case 'u': // Username if (optarg && optarg[0] == '-') { break; } config->username = optarg; break; case 'p': // Password if (optarg && optarg[0] == '-') { break; } config->password = optarg; break; case 'i': // Input if (optarg && optarg[0] == '-') { break; } config->input = optarg; break; case 'l': // Listen address if (optarg && optarg[0] == '-') { break; } config->address = optarg; break; case 'b': // Port if (optarg && optarg[0] == '-') { break; } config->port = optarg; break; case 'f': // Framerate if (optarg && optarg[0] == '-') { break; } config->framerate = optarg; break; case 's': { // Scale if (optarg && optarg[0] == '-') { break; } size_t pos = 0; std::string scale = optarg; if ((pos = scale.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale " "argument: " << scale << std::endl << "Using default values instead"; return false; } config->scale.first = scale.substr(0, pos); config->scale.second = scale.substr(pos + 1); break; } case 't': // Time Overlay config->time = true; break; case 'h': // help fprintf(stdout, "Usage: %s [-l address] [-b port] [-r route] [-i " "input] [-u username] [-p password] [-f framerate] [-s " "'width'x'height'] [-t] [-h]\n", argv[0]); return true; case '?': if (optopt == 'r' || optopt == 'l' || optopt == 'p' || optopt == 'u' || optopt == 'i' || optopt == 'a' || optopt == 'b' || optopt == 'f' || optopt == 's') { fprintf(stderr, "Option -%c requires an argument.\n", optopt); } else if (isprint(optopt)) { fprintf(stderr, "Unknown option `-%c'.\n", optopt); } else { fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); } return false; default: return false; ; } } return true; } void parse_input_type(std::shared_ptr<t_config> &config) { if (config->input.compare(0, 7, "rtsp://") == 0) { // RTSP stream input config->input_type = RTSP_INPUT; } else if (config->input.empty() || config->input.compare(0, 8, "pattern:") == 0) { // Videotestsrc pattern input config->input_type = VIDEOTESTSRC_INPUT; } else if (config->input.compare(0, 10, "/dev/video") == 0) { // v4l2src input config->input_type = DEVICE_INPUT; } else { // File config->input_type = FILE_INPUT; } } std::string input_type_to_string(InputType type) { switch (type) { case UNDEFINED_INPUT: return "undefined"; case FILE_INPUT: return "file"; case RTSP_INPUT: return "rtsp"; case VIDEOTESTSRC_INPUT: return "videotestsrc"; case DEVICE_INPUT; return "v4l2src"; default: break; } } void dump_config(std::shared_ptr<t_config> &config) { // Server config std::cout << "Server configuration:" << std::endl << "Address:\t" << config->address << std::endl << "Port:\t\t" << config->port << std::endl << "Route:\t\t" << config->route << std::endl << "Username:\t" << config->username << std::endl << "Password:\t" << config->password << std::endl << std::endl; // Input std::cout << "Input:\t\t"; config->input.empty() ? std::cout << "pattern:smpte" << std::endl : std::cout << config->input << std::endl; std::cout << "Input type:\t" << input_type_to_string(config->input_type) << std::endl << std::endl; }
// Copyright 2016 Etix Labs // // 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 "server.h" #include <iostream> #include <string.h> // Set config defaults or from env void parse_env(std::shared_ptr<t_config> &config) { // Address config->address = DEFAULT_ADDRESS; if (const char *address = std::getenv("RTSP_ADDRESS")) { config->address = address; } // Port config->port = DEFAULT_PORT; if (const char *port = std::getenv("RTSP_PORT")) { config->port = port; } // Route config->route = DEFAULT_ROUTE; if (const char *route = std::getenv("RTSP_ROUTE")) { config->route = route; } // Username config->username = DEFAULT_USERNAME; if (const char *username = std::getenv("RTSP_USERNAME")) { config->username = username; } // Password config->password = DEFAULT_PASSWORD; if (const char *password = std::getenv("RTSP_PASSWORD")) { config->password = password; } // Framerate config->framerate = DEFAULT_FRAMERATE; if (const char *framerate = std::getenv("RTSP_FRAMERATE")) { config->framerate = framerate; } // Scale config->scale = std::make_pair<std::string, std::string>(DEFAULT_WIDTH, DEFAULT_HEIGHT); if (const char *scale = std::getenv("RTSP_RESOLUTION")) { size_t pos = 0; std::string scale_str(scale); if ((pos = scale_str.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale argument: " << scale_str << std::endl << "Using default values"; } else { config->scale = std::make_pair<std::string, std::string>( scale_str.substr(0, pos), scale_str.substr(pos + 1)); } } // Input config->input = DEFAULT_INPUT; if (const char *input = std::getenv("INPUT")) { config->input = input; } config->time = DEFAULT_TIME_ENABLED; if (const char *time = std::getenv("ENABLE_TIME_OVERLAY")) { if (strcmp(time, "false") == 0) { config->time = false; } else { config->time = true; } } } // Overwrite default parameters via cmd line bool parse_args(std::shared_ptr<t_config> &config, int argc, char **argv) { int c; opterr = 0; while ((c = getopt(argc, argv, "r:u:l:p:b:f:s:i:ht")) != -1) { switch (c) { case 'r': // Route if (optarg && optarg[0] == '-') { break; } if (not optarg[0] == '/') { config->route = "/"; } config->route += optarg; break; case 'u': // Username if (optarg && optarg[0] == '-') { break; } config->username = optarg; break; case 'p': // Password if (optarg && optarg[0] == '-') { break; } config->password = optarg; break; case 'i': // Input if (optarg && optarg[0] == '-') { break; } config->input = optarg; break; case 'l': // Listen address if (optarg && optarg[0] == '-') { break; } config->address = optarg; break; case 'b': // Port if (optarg && optarg[0] == '-') { break; } config->port = optarg; break; case 'f': // Framerate if (optarg && optarg[0] == '-') { break; } config->framerate = optarg; break; case 's': { // Scale if (optarg && optarg[0] == '-') { break; } size_t pos = 0; std::string scale = optarg; if ((pos = scale.find("x")) == std::string::npos) { std::cerr << "No x token found between width and height in the scale " "argument: " << scale << std::endl << "Using default values instead"; return false; } config->scale.first = scale.substr(0, pos); config->scale.second = scale.substr(pos + 1); break; } case 't': // Time Overlay config->time = true; break; case 'h': // help fprintf(stdout, "Usage: %s [-l address] [-b port] [-r route] [-i " "input] [-u username] [-p password] [-f framerate] [-s " "'width'x'height'] [-t] [-h]\n", argv[0]); return true; case '?': if (optopt == 'r' || optopt == 'l' || optopt == 'p' || optopt == 'u' || optopt == 'i' || optopt == 'a' || optopt == 'b' || optopt == 'f' || optopt == 's') { fprintf(stderr, "Option -%c requires an argument.\n", optopt); } else if (isprint(optopt)) { fprintf(stderr, "Unknown option `-%c'.\n", optopt); } else { fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); } return false; default: return false; ; } } return true; } void parse_input_type(std::shared_ptr<t_config> &config) { if (config->input.compare(0, 7, "rtsp://") == 0) { // RTSP stream input config->input_type = RTSP_INPUT; } else if (config->input.empty() || config->input.compare(0, 8, "pattern:") == 0) { // Videotestsrc pattern input config->input_type = VIDEOTESTSRC_INPUT; } else if (config->input.compare(0, 10, "/dev/video") == 0) { // v4l2src input config->input_type = DEVICE_INPUT; } else { // File config->input_type = FILE_INPUT; } } std::string input_type_to_string(InputType type) { switch (type) { case UNDEFINED_INPUT: return "undefined"; case FILE_INPUT: return "file"; case RTSP_INPUT: return "rtsp"; case VIDEOTESTSRC_INPUT: return "videotestsrc"; case DEVICE_INPUT: return "v4l2src"; default: break; } } void dump_config(std::shared_ptr<t_config> &config) { // Server config std::cout << "Server configuration:" << std::endl << "Address:\t" << config->address << std::endl << "Port:\t\t" << config->port << std::endl << "Route:\t\t" << config->route << std::endl << "Username:\t" << config->username << std::endl << "Password:\t" << config->password << std::endl << std::endl; // Input std::cout << "Input:\t\t"; config->input.empty() ? std::cout << "pattern:smpte" << std::endl : std::cout << config->input << std::endl; std::cout << "Input type:\t" << input_type_to_string(config->input_type) << std::endl << std::endl; }
fix ; typo
fix ; typo
C++
apache-2.0
EtixLabs/RTSPAllTheThings,EtixLabs/CES,EtixLabs/CES,EtixLabs/RTSPAllTheThings
7a19bf4c5378604396ac06fde36cb84d9bc81fc1
src/allocator.cpp
src/allocator.cpp
/* Copyright (c) 2009-2013, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #elif !defined TORRENT_WINDOWS #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS #include <malloc.h> // memalign and _aligned_malloc #include <stdlib.h> // _aligned_malloc on mingw #endif #ifdef TORRENT_WINDOWS // windows.h must be included after stdlib.h under mingw #include <windows.h> #endif #ifdef TORRENT_MINGW #define _aligned_malloc __mingw_aligned_malloc #define _aligned_free __mingw_aligned_free #endif #ifdef TORRENT_DEBUG_BUFFERS #ifndef TORRENT_WINDOWS #include <sys/mman.h> #endif #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { TORRENT_ASSERT(bytes >= page_size()); #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) / page + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #endif // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #endif #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)_aligned_malloc(bytes, page_size()); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #define PROT_WRITE PAGE_READWRITE #endif int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) / page + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #undef PROT_WRITE #endif #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif // TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS _aligned_free(block); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif // TORRENT_WINDOWS } }
/* Copyright (c) 2009-2013, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #elif !defined TORRENT_WINDOWS #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS #include <malloc.h> // memalign and _aligned_malloc #include <stdlib.h> // _aligned_malloc on mingw #endif #ifdef TORRENT_WINDOWS // windows.h must be included after stdlib.h under mingw #include <windows.h> #endif #ifdef TORRENT_MINGW #define _aligned_malloc __mingw_aligned_malloc #define _aligned_free __mingw_aligned_free #endif #ifdef TORRENT_DEBUG_BUFFERS #ifndef TORRENT_WINDOWS #include <sys/mman.h> #endif #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { TORRENT_ASSERT(bytes >= page_size()); #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) / page + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #endif // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #else #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)_aligned_malloc(bytes, page_size()); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif #endif // TORRENT_DEBUG_BUFFERS } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS #define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK) #define PROT_READ PAGE_READONLY #define PROT_WRITE PAGE_READWRITE #endif int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) / page + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #ifdef TORRENT_WINDOWS #undef mprotect #undef PROT_READ #undef PROT_WRITE #endif #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif // TORRENT_DEBUG_BUFFERS #ifdef TORRENT_WINDOWS _aligned_free(block); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif // TORRENT_WINDOWS } }
fix build with allocator debugging
fix build with allocator debugging git-svn-id: 6ed3528c1be4534134272ad6dd050eeaa1f628d3@9515 f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
C++
bsd-3-clause
steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent
00ee14bdfdf640469cdea3f1b00a079a70db3c4e
src/framework/XSECW32Config.hpp
src/framework/XSECW32Config.hpp
/* * Copyright 2002-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * XSEC * * Configuration file for Windows platform * * Needs to be modified by hand * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xercesc/util/XercesVersion.hpp> /* * These are the high level numerics that need to be changed to bump the * version number. * * They are used to create version strings - see the details at the end of this file */ #define XSEC_VERSION_MAJOR 1 #define XSEC_VERSION_MEDIUM 3 #define XSEC_VERSION_MINOR 0 /* * Because we don't have a configure script, we need to rely on version * numbers to understand library idiosycracies */ #if (XERCES_VERSION_MAJOR >= 2) && (XERCES_VERSION_MINOR >= 3) /* * As of version 2.3, xerces requires a version parameter in XMLFormatter * constructors */ # define XSEC_XERCES_FORMATTER_REQUIRES_VERSION 1 /* 2.3 and above use a user defined Memory Manager. In some cases, this actually needs to be passed to functions */ # define XSEC_XERCES_REQUIRES_MEMMGR 1 /* Does XMLString::release() exist */ #define XSEC_XERCES_XMLSTRING_HAS_RELEASE 1 /* Is it possible to setIdAttributes? - DOM level 3 call */ #define XSEC_XERCES_HAS_SETIDATTRIBUTE 1 #else /* * In version 2.2, the XMLUri class was broken for relative URI de-referencing */ # define XSEC_XERCES_BROKEN_XMLURI 1 #endif /* * The following defines whether Xalan integration is required. * * Xalan is used for XSLT and complex XPath processing. * Activate this #define if Xalan is not required (or desired) */ // #define XSEC_NO_XALAN #if !defined (XSEC_NO_XALAN) # include <xalanc/Include/XalanVersion.hpp> # if (_XALAN_VERSION <= 10800) # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 # endif # if (_XALAN_VERSION >= 10900) /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # undef XSEC_XSLEXCEPTION_RETURNS_DOMSTRING /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # undef XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # define XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # define XSEC_XALAN_REQS_MEMORYMANAGER # else /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # define XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # undef XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # undef XSEC_XALAN_REQS_MEMORYMANAGER # endif #endif /* * Define presence of cryptographic providers */ #define HAVE_OPENSSL 1 #define HAVE_WINCAPI 1 // NSS Code is currently alpha. It should work, but you will also // need to include the NSS libraries during the link. /* #define HAVE_NSS 1 */ /* * Some settings for OpenSSL if we have it * */ #if defined (HAVE_OPENSSL) # include <openssl/opensslv.h> # if (OPENSSL_VERSION_NUMBER >= 0x00907000) # define XSEC_OPENSSL_CONST_BUFFERS # define XSEC_OPENSSL_HAVE_AES # define XSEC_OPENSSL_CANSET_PADDING # define XSEC_OPENSSL_HAVE_CRYPTO_CLEANUP_ALL_EX_DATA # endif # if (OPENSSL_VERSION_NUMBER >= 0x00908000) # define XSEC_OPENSSL_D2IX509_CONST_BUFFER # endif #endif /* * Macros used to determine what header files exist on this * system */ /* Posix unistd.h */ /* #define HAVE_UNISTD_H */ /* Windows direct.h */ #define HAVE_DIRECT_H 1 // -------------------------------------------------------------------------------- // Version Handling // -------------------------------------------------------------------------------- /* * The following code makes use of the Xerces version handling macros to define * some constants that can be used during conditional compilation. */ /* This can be used for conditional compilation and for testing during * autoconfigures. * * It will create a string of the form 10000 * MAJOR + 100 * MEDIUM + MINOR * E.g. 10301 for version 1.3.1 */ #define _XSEC_VERSION_FULL CALC_EXPANDED_FORM (XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) /* Some useful strings for versioning - based on the same strings from Xerces */ #define XSEC_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) #define XSEC_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) #define XSEC_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) #define XSEC_VERSIONSTR INVK_CAT2_SEP_UNDERSCORE(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM) /* The following is used for backwards compatibility with previous version handling */ #define XSEC_VERSION "XSEC_FULLVERSIONDOT"
/* * Copyright 2002-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * XSEC * * Configuration file for Windows platform * * Needs to be modified by hand * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xercesc/util/XercesVersion.hpp> /* * These are the high level numerics that need to be changed to bump the * version number. * * They are used to create version strings - see the details at the end of this file */ #define XSEC_VERSION_MAJOR 1 #define XSEC_VERSION_MEDIUM 3 #define XSEC_VERSION_MINOR 1 /* * Because we don't have a configure script, we need to rely on version * numbers to understand library idiosycracies */ #if (XERCES_VERSION_MAJOR >= 3) /* Is it possible to setIdAttributes? - DOM level 3 call. V3.x API Version */ # define XSEC_XERCES_HAS_BOOLSETIDATTRIBUTE 1 /* 3.0 no longer supports DOMWriter, must use DOMLSSerializer instead */ # define XSEC_XERCES_DOMLSSERIALIZER 1 /* 3.0 now uses getInputEncoding rather than getEncoding to determine encoding that was found in input document */ # define XSEC_XERCES_DOMENTITYINPUTENCODING 1 #endif #if (XERCES_VERSION_MAJOR == 3) || ((XERCES_VERSION_MAJOR == 2) && (XERCES_VERSION_MINOR >= 3)) /* * As of version 2.3, xerces requires a version parameter in XMLFormatter * constructors */ # define XSEC_XERCES_FORMATTER_REQUIRES_VERSION 1 /* 2.3 and above use a user defined Memory Manager. In some cases, this actually needs to be passed to functions */ # define XSEC_XERCES_REQUIRES_MEMMGR 1 /* Does XMLString::release() exist */ # define XSEC_XERCES_XMLSTRING_HAS_RELEASE 1 # if (XERCES_VERSION_MAJOR < 3) /* Is it possible to setIdAttributes? - DOM level 3 call. V2.x API */ # define XSEC_XERCES_HAS_SETIDATTRIBUTE 1 # endif #else /* * In version 2.2, the XMLUri class was broken for relative URI de-referencing */ # define XSEC_XERCES_BROKEN_XMLURI 1 #endif /* * The following defines whether Xalan integration is required. * * Xalan is used for XSLT and complex XPath processing. * Activate this #define if Xalan is not required (or desired) */ // #define XSEC_NO_XALAN #if !defined (XSEC_NO_XALAN) # include <xalanc/Include/XalanVersion.hpp> # if (_XALAN_VERSION <= 10800) # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 # endif # if (_XALAN_VERSION >= 10900) /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # undef XSEC_XSLEXCEPTION_RETURNS_DOMSTRING /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # undef XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # define XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # define XSEC_XALAN_REQS_MEMORYMANAGER # else /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # define XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # undef XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # undef XSEC_XALAN_REQS_MEMORYMANAGER # endif #endif /* * Define presence of cryptographic providers */ #define HAVE_OPENSSL 1 #define HAVE_WINCAPI 1 // NSS Code is currently alpha. It should work, but you will also // need to include the NSS libraries during the link. /* #define HAVE_NSS 1 */ /* * Some settings for OpenSSL if we have it * */ #if defined (HAVE_OPENSSL) # include <openssl/opensslv.h> # if (OPENSSL_VERSION_NUMBER >= 0x00907000) # define XSEC_OPENSSL_CONST_BUFFERS # define XSEC_OPENSSL_HAVE_AES # define XSEC_OPENSSL_CANSET_PADDING # define XSEC_OPENSSL_HAVE_CRYPTO_CLEANUP_ALL_EX_DATA # endif # if (OPENSSL_VERSION_NUMBER >= 0x00908000) # define XSEC_OPENSSL_D2IX509_CONST_BUFFER # endif #endif /* * Macros used to determine what header files exist on this * system */ /* Posix unistd.h */ /* #define HAVE_UNISTD_H */ /* Windows direct.h */ #define HAVE_DIRECT_H 1 // -------------------------------------------------------------------------------- // Version Handling // -------------------------------------------------------------------------------- /* * The following code makes use of the Xerces version handling macros to define * some constants that can be used during conditional compilation. */ /* This can be used for conditional compilation and for testing during * autoconfigures. * * It will create a string of the form 10000 * MAJOR + 100 * MEDIUM + MINOR * E.g. 10301 for version 1.3.1 */ #define _XSEC_VERSION_FULL CALC_EXPANDED_FORM (XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) /* Some useful strings for versioning - based on the same strings from Xerces */ #define XSEC_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) #define XSEC_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) #define XSEC_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM,XSEC_VERSION_MINOR) #define XSEC_VERSIONSTR INVK_CAT2_SEP_UNDERSCORE(XSEC_VERSION_MAJOR,XSEC_VERSION_MEDIUM) /* The following is used for backwards compatibility with previous version handling */ #define XSEC_VERSION "XSEC_FULLVERSIONDOT"
Update to 1.3.1 version and detect Xerces V3 source
Update to 1.3.1 version and detect Xerces V3 source git-svn-id: 35e0c45cba356f0e2c1fbea81384ac7531a87101@464120 13f79535-47bb-0310-9956-ffa450edef68
C++
apache-2.0
apache/santuario-cpp,apache/santuario-cpp,apache/santuario-cpp
6ec228f3010884e3d4a8111fafc6e7a6740798a0
glfw3_app/ignitor/relay_map.hpp
glfw3_app/ignitor/relay_map.hpp
#pragma once //=====================================================================// /*! @file @brief イグナイター・リレー切り替えクラス @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 "core/glcore.hpp" #include "utils/director.hpp" #include "widgets/widget_dialog.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_button.hpp" #include "widgets/widget_text.hpp" #include "widgets/widget_label.hpp" #include "widgets/widget_spinbox.hpp" #include "widgets/widget_check.hpp" #include "widgets/widget_filer.hpp" #include "utils/input.hpp" #include "utils/format.hpp" #include "utils/preference.hpp" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief リレー・マップ・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class relay_map { utils::director<core>& director_; gui::widget_dialog* dialog_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// relay_map(utils::director<core>& d) : director_(d), dialog_(nullptr) { } //-----------------------------------------------------------------// /*! @brief ダイアログの取得 @return ダイアログ */ //-----------------------------------------------------------------// gui::widget_dialog* get_dialog() { return dialog_; } //-----------------------------------------------------------------// /*! @brief 初期化(リソースの構築) */ //-----------------------------------------------------------------// void initialize() { using namespace gui; widget_director& wd = director_.at().widget_director_; int d_w = 700; int d_h = 500; { widget::param wp(vtx::irect(100, 100, d_w, d_h)); widget_dialog::param wp_; wp_.style_ = widget_dialog::style::OK; dialog_ = wd.add_widget<widget_dialog>(wp, wp_); dialog_->enable(false); // dialog_->at_local_param().select_func_ = [this](bool ok) { // }; } } //-----------------------------------------------------------------// /*! @brief 更新 */ //-----------------------------------------------------------------// void update() { } //-----------------------------------------------------------------// /*! @brief セーブ @param[in] pre プリファレンス(参照) @return 正常なら「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre) { return true; } //-----------------------------------------------------------------// /*! @brief セーブ @param[in] pre プリファレンス(参照) @return 正常なら「true」 */ //-----------------------------------------------------------------// bool load(sys::preference& pre) { return true; } }; }
#pragma once //=====================================================================// /*! @file @brief イグナイター・リレー切り替えクラス @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 <array> #include "core/glcore.hpp" #include "utils/director.hpp" #include "widgets/widget_dialog.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_image.hpp" #include "widgets/widget_button.hpp" #include "widgets/widget_text.hpp" #include "widgets/widget_label.hpp" #include "widgets/widget_spinbox.hpp" #include "widgets/widget_check.hpp" #include "widgets/widget_filer.hpp" #include "utils/input.hpp" #include "utils/format.hpp" #include "utils/preference.hpp" #include "img_io/img_files.hpp" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief リレー・マップ・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class relay_map { utils::director<core>& director_; gui::widget_dialog* dialog_; gui::widget_image* image_; gui::widget_check* l_sw_[18]; gui::widget_check* r_sw_[18]; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// relay_map(utils::director<core>& d) : director_(d), dialog_(nullptr), image_(nullptr), l_sw_{ nullptr }, r_sw_{ nullptr } { } //-----------------------------------------------------------------// /*! @brief ダイアログの取得 @return ダイアログ */ //-----------------------------------------------------------------// gui::widget_dialog* get_dialog() { return dialog_; } //-----------------------------------------------------------------// /*! @brief 初期化(リソースの構築) */ //-----------------------------------------------------------------// void initialize() { using namespace gui; widget_director& wd = director_.at().widget_director_; int d_w = 800; int d_h = 600; img::img_files imgf; auto state = imgf.load("relay_map.png"); if(state) { auto s = imgf.get_image().get()->get_size(); d_w = s.x + 10; d_h = s.y + 60 + 10; } { widget::param wp(vtx::irect(100, 100, d_w, d_h)); widget_dialog::param wp_; wp_.style_ = widget_dialog::style::OK; dialog_ = wd.add_widget<widget_dialog>(wp, wp_); dialog_->enable(false); // dialog_->at_local_param().select_func_ = [this](bool ok) { // }; } { // リレー・マップ・イメージ widget::param wp(vtx::irect(5, 5, 0, 0), dialog_); widget_image::param wp_(imgf.get_image().get()); image_ = wd.add_widget<widget_image>(wp, wp_); } static const vtx::ipos l_tbls[] = { { 253, 52 + 20 * 0 }, // S1 { 253, 52 + 20 * 1 }, // S2 { 253, 52 + 20 * 2 }, // S3 { 253, 52 + 20 * 3 }, // S4 { 253, 52 + 20 * 4 }, // S5 { 253, 52 + 20 * 5 }, // S6 { 253, 52 + 20 * 6 }, // S7 { 253, 52 + 20 * 7 }, // S8 { 253, 52 + 20 * 8 }, // S9 { 253, 52 + 20 * 9 }, // S10 { 253, 52 + 20 * 10 }, // S11 { 253, 52 + 20 * 11 }, // S12 { 253, 52 + 20 * 12 }, // S13 { 253, 52 + 20 * 13 }, // S14 { 253, 52 + 20 * 14 }, // S15 { 253, 52 + 20 * 15 }, // S16 { 253, 52 + 20 * 16 }, // S17 { 253, 52 + 20 * 17 }, // S18 }; for(int i = 0; i < 18; ++i) { // リレー切り替え、左側 widget::param wp(vtx::irect(l_tbls[i].x + 4, l_tbls[i].y - 10, 30, 30), dialog_); widget_check::param wp_; l_sw_[i] = wd.add_widget<widget_check>(wp, wp_); // l_sw_[i]_->at_local_param().select_func_ // = [=](const std::string& str, uint32_t pos) { // }; } static const vtx::ipos r_tbls[] = { { 614, 52 + 20 * 0 }, // S34 { 614, 52 + 20 * 2 }, // S19 { 614, 52 + 20 * 3 }, // S20 { 614, 52 + 20 * 5 }, // S21 { 614, 52 + 20 * 6 }, // S35 { 614, 52 + 20 * 7 }, // S22 { 614, 52 + 20 * 8 }, // S23 { 614, 52 + 20 * 9 }, // S24 { 614, 52 + 20 * 10 }, // S25 { 614, 52 + 20 * 11 }, // S26 { 614, 52 + 20 * 12 }, // S27 { 614, 52 + 20 * 13 }, // S28 { 614, 52 + 20 * 15 }, // S29 { 614, 52 + 20 * 16 }, // S35 { 614, 52 + 20 * 17 }, // S30 { 614, 52 + 20 * 18 }, // S31 { 614, 52 + 20 * 19 }, // S32 { 614, 52 + 20 * 20 }, // S33 }; for(int i = 0; i < 18; ++i) { // リレー切り替え、右側 widget::param wp(vtx::irect(r_tbls[i].x + 4, r_tbls[i].y - 10, 30, 30), dialog_); widget_check::param wp_; r_sw_[i] = wd.add_widget<widget_check>(wp, wp_); // r_sw_[i]_->at_local_param().select_func_ // = [=](const std::string& str, uint32_t pos) { // }; } } //-----------------------------------------------------------------// /*! @brief 更新 */ //-----------------------------------------------------------------// void update() { if(!dialog_->get_state(gui::widget::state::ENABLE)) return; if(image_->get_select_in()) { auto pos = image_->get_param().in_point_; if(52 <= pos.y && pos.y <= 397) { if(253 <= pos.x && pos.x <= 275) { // S1 to S18 } else if(614 <= pos.x && pos.x <= 636) { // S19 to S34 } } // std::cout << pos.x << ", " << pos.y << std::endl; } } //-----------------------------------------------------------------// /*! @brief セーブ @param[in] pre プリファレンス(参照) @return 正常なら「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre) { for(int i = 0; i < 18; ++i) { l_sw_[i]->save(pre); } for(int i = 0; i < 18; ++i) { r_sw_[i]->save(pre); } return true; } //-----------------------------------------------------------------// /*! @brief セーブ @param[in] pre プリファレンス(参照) @return 正常なら「true」 */ //-----------------------------------------------------------------// bool load(sys::preference& pre) { for(int i = 0; i < 18; ++i) { l_sw_[i]->load(pre); } for(int i = 0; i < 18; ++i) { r_sw_[i]->load(pre); } return true; } }; }
update relay setting
update relay setting
C++
bsd-3-clause
hirakuni45/glfw3_app,hirakuni45/glfw3_app,hirakuni45/glfw3_app
b37cdb8bfe5d9efcb086ff0690bc03dec5ecdc6d
src/base/utils.cc
src/base/utils.cc
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/ext/base/utils.h" #include <string> #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" #include "perfetto/ext/base/file_utils.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) #include <limits.h> #include <stdlib.h> // For _exit() #include <unistd.h> // For getpagesize() and geteuid() & fork() #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) #include <mach-o/dyld.h> #include <mach/vm_page_size.h> #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <Windows.h> #include <io.h> #include <malloc.h> // For _aligned_malloc(). #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #include <dlfcn.h> #include <malloc.h> #ifdef M_PURGE #define PERFETTO_M_PURGE M_PURGE #else // Only available in in-tree builds and on newer SDKs. #define PERFETTO_M_PURGE -101 #endif // M_PURGE namespace { extern "C" { using MalloptType = void (*)(int, int); } } // namespace #endif // OS_ANDROID namespace { #if PERFETTO_BUILDFLAG(PERFETTO_X64_CPU_OPT) // Preserve the %rbx register via %rdi to work around a clang bug // https://bugs.llvm.org/show_bug.cgi?id=17907 (%rbx in an output constraint // is not considered a clobbered register). #define PERFETTO_GETCPUID(a, b, c, d, a_inp, c_inp) \ asm("mov %%rbx, %%rdi\n" \ "cpuid\n" \ "xchg %%rdi, %%rbx\n" \ : "=a"(a), "=D"(b), "=c"(c), "=d"(d) \ : "a"(a_inp), "2"(c_inp)) uint32_t GetXCR0EAX() { uint32_t eax = 0, edx = 0; asm("xgetbv" : "=a"(eax), "=d"(edx) : "c"(0)); return eax; } // If we are building with -msse4 check that the CPU actually supports it. // This file must be kept in sync with gn/standalone/BUILD.gn. void PERFETTO_EXPORT_COMPONENT __attribute__((constructor)) CheckCpuOptimizations() { uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0; PERFETTO_GETCPUID(eax, ebx, ecx, edx, 1, 0); static constexpr uint64_t xcr0_xmm_mask = 0x2; static constexpr uint64_t xcr0_ymm_mask = 0x4; static constexpr uint64_t xcr0_avx_mask = xcr0_xmm_mask | xcr0_ymm_mask; const bool have_popcnt = ecx & (1u << 23); const bool have_sse4_2 = ecx & (1u << 20); const bool have_avx = // Does the OS save/restore XMM and YMM state? (ecx & (1u << 27)) && // OS support XGETBV. (ecx & (1u << 28)) && // AVX supported in hardware ((GetXCR0EAX() & xcr0_avx_mask) == xcr0_avx_mask); if (!have_sse4_2 || !have_popcnt || !have_avx) { fprintf( stderr, "This executable requires a cpu that supports SSE4.2 and AVX2.\n" "Rebuild with enable_perfetto_x64_cpu_opt=false (ebx=%x, ecx=%x).\n", ebx, ecx); _exit(126); } } #endif } // namespace namespace perfetto { namespace base { void MaybeReleaseAllocatorMemToOS() { #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // mallopt() on Android requires SDK level 26. Many targets and embedders // still depend on a lower SDK level. Given mallopt() is a quite simple API, // use reflection to do this rather than bumping the SDK level for all // embedders. This keeps the behavior of standalone builds aligned with // in-tree builds. static MalloptType mallopt_fn = reinterpret_cast<MalloptType>(dlsym(RTLD_DEFAULT, "mallopt")); if (!mallopt_fn) return; mallopt_fn(PERFETTO_M_PURGE, 0); #endif } uint32_t GetSysPageSize() { ignore_result(kPageSize); // Just to keep the amalgamated build happy. #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) static std::atomic<uint32_t> page_size{0}; // This function might be called in hot paths. Avoid calling getpagesize() all // the times, in many implementations getpagesize() calls sysconf() which is // not cheap. uint32_t cached_value = page_size.load(std::memory_order_relaxed); if (PERFETTO_UNLIKELY(cached_value == 0)) { cached_value = static_cast<uint32_t>(getpagesize()); page_size.store(cached_value, std::memory_order_relaxed); } return cached_value; #elif PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) return static_cast<uint32_t>(vm_page_size); #else return 4096; #endif } uid_t GetCurrentUserId() { #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) return geteuid(); #else // TODO(primiano): On Windows we could hash the current user SID and derive a // numeric user id [1]. It is not clear whether we need that. Right now that // would not bring any benefit. Returning 0 unil we can prove we need it. // [1]:https://android-review.googlesource.com/c/platform/external/perfetto/+/1513879/25/src/base/utils.cc return 0; #endif } void SetEnv(const std::string& key, const std::string& value) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) PERFETTO_CHECK(::_putenv_s(key.c_str(), value.c_str()) == 0); #else PERFETTO_CHECK(::setenv(key.c_str(), value.c_str(), /*overwrite=*/true) == 0); #endif } void Daemonize(std::function<int()> parent_cb) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) pid_t pid; switch (pid = fork()) { case -1: PERFETTO_FATAL("fork"); case 0: { PERFETTO_CHECK(setsid() != -1); base::ignore_result(chdir("/")); base::ScopedFile null = base::OpenFile("/dev/null", O_RDONLY); PERFETTO_CHECK(null); PERFETTO_CHECK(dup2(*null, STDIN_FILENO) != -1); PERFETTO_CHECK(dup2(*null, STDOUT_FILENO) != -1); PERFETTO_CHECK(dup2(*null, STDERR_FILENO) != -1); // Do not accidentally close stdin/stdout/stderr. if (*null <= 2) null.release(); break; } default: printf("%d\n", pid); int err = parent_cb(); exit(err); } #else // Avoid -Wunreachable warnings. if (reinterpret_cast<intptr_t>(&Daemonize) != 16) PERFETTO_FATAL("--background is only supported on Linux/Android/Mac"); ignore_result(parent_cb); #endif // OS_WIN } std::string GetCurExecutablePath() { std::string self_path; #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) char buf[PATH_MAX]; ssize_t size = readlink("/proc/self/exe", buf, sizeof(buf)); PERFETTO_CHECK(size != -1); // readlink does not null terminate. self_path = std::string(buf, static_cast<size_t>(size)); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) uint32_t size = 0; PERFETTO_CHECK(_NSGetExecutablePath(nullptr, &size)); self_path.resize(size); PERFETTO_CHECK(_NSGetExecutablePath(&self_path[0], &size) == 0); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) char buf[MAX_PATH]; auto len = ::GetModuleFileNameA(nullptr /*current*/, buf, sizeof(buf)); self_path = std::string(buf, len); #else PERFETTO_FATAL( "GetCurExecutableDir() not implemented on the current platform"); #endif return self_path; } std::string GetCurExecutableDir() { auto path = GetCurExecutablePath(); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Paths in Windows can have both kinds of slashes (mingw vs msvc). path = path.substr(0, path.find_last_of('\\')); #endif path = path.substr(0, path.find_last_of('/')); return path; } void* AlignedAlloc(size_t alignment, size_t size) { void* res = nullptr; alignment = AlignUp<sizeof(void*)>(alignment); // At least pointer size. #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Window's _aligned_malloc() has a nearly identically signature to Unix's // aligned_alloc() but its arguments are obviously swapped. res = _aligned_malloc(size, alignment); #else // aligned_alloc() has been introduced in Android only in API 28. // Also NaCl and Fuchsia seems to have only posix_memalign(). ignore_result(posix_memalign(&res, alignment, size)); #endif PERFETTO_CHECK(res); return res; } void AlignedFree(void* ptr) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) _aligned_free(ptr); // MSDN says it is fine to pass nullptr. #else free(ptr); #endif } std::string HexDump(const void* data_void, size_t len, size_t bytes_per_line) { const char* data = reinterpret_cast<const char*>(data_void); std::string res; static const size_t kPadding = bytes_per_line * 3 + 12; std::unique_ptr<char[]> line(new char[bytes_per_line * 4 + 128]); for (size_t i = 0; i < len; i += bytes_per_line) { char* wptr = line.get(); wptr += sprintf(wptr, "%08zX: ", i); for (size_t j = i; j < i + bytes_per_line && j < len; j++) wptr += sprintf(wptr, "%02X ", static_cast<unsigned>(data[j]) & 0xFF); for (size_t j = static_cast<size_t>(wptr - line.get()); j < kPadding; ++j) *(wptr++) = ' '; for (size_t j = i; j < i + bytes_per_line && j < len; j++) { char c = data[j]; *(wptr++) = (c >= 32 && c < 127) ? c : '.'; } *(wptr++) = '\n'; *(wptr++) = '\0'; res.append(line.get()); } return res; } } // namespace base } // namespace perfetto
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/ext/base/utils.h" #include <string> #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" #include "perfetto/ext/base/file_utils.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) #include <limits.h> #include <stdlib.h> // For _exit() #include <unistd.h> // For getpagesize() and geteuid() & fork() #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) #include <mach-o/dyld.h> #include <mach/vm_page_size.h> #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <Windows.h> #include <io.h> #include <malloc.h> // For _aligned_malloc(). #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #include <dlfcn.h> #include <malloc.h> #ifdef M_PURGE #define PERFETTO_M_PURGE M_PURGE #else // Only available in in-tree builds and on newer SDKs. #define PERFETTO_M_PURGE -101 #endif // M_PURGE namespace { extern "C" { using MalloptType = void (*)(int, int); } } // namespace #endif // OS_ANDROID namespace { #if PERFETTO_BUILDFLAG(PERFETTO_X64_CPU_OPT) // Preserve the %rbx register via %rdi to work around a clang bug // https://bugs.llvm.org/show_bug.cgi?id=17907 (%rbx in an output constraint // is not considered a clobbered register). #define PERFETTO_GETCPUID(a, b, c, d, a_inp, c_inp) \ asm("mov %%rbx, %%rdi\n" \ "cpuid\n" \ "xchg %%rdi, %%rbx\n" \ : "=a"(a), "=D"(b), "=c"(c), "=d"(d) \ : "a"(a_inp), "2"(c_inp)) uint32_t GetXCR0EAX() { uint32_t eax = 0, edx = 0; asm("xgetbv" : "=a"(eax), "=d"(edx) : "c"(0)); return eax; } // If we are building with -msse4 check that the CPU actually supports it. // This file must be kept in sync with gn/standalone/BUILD.gn. void PERFETTO_EXPORT_COMPONENT __attribute__((constructor)) CheckCpuOptimizations() { uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0; PERFETTO_GETCPUID(eax, ebx, ecx, edx, 1, 0); static constexpr uint64_t xcr0_xmm_mask = 0x2; static constexpr uint64_t xcr0_ymm_mask = 0x4; static constexpr uint64_t xcr0_avx_mask = xcr0_xmm_mask | xcr0_ymm_mask; const bool have_popcnt = ecx & (1u << 23); const bool have_sse4_2 = ecx & (1u << 20); const bool have_avx = // Does the OS save/restore XMM and YMM state? (ecx & (1u << 27)) && // OS support XGETBV. (ecx & (1u << 28)) && // AVX supported in hardware ((GetXCR0EAX() & xcr0_avx_mask) == xcr0_avx_mask); if (!have_sse4_2 || !have_popcnt || !have_avx) { fprintf( stderr, "This executable requires a X86_64 cpu that supports SSE4.2 and AVX.\n" #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) "On MacOS, this might be caused by running x86_64 binaries on arm64.\n" "See https://github.com/google/perfetto/issues/294 for more.\n" #endif "Rebuild with enable_perfetto_x64_cpu_opt=false (ebx=%x, ecx=%x).\n", ebx, ecx); _exit(126); } } #endif } // namespace namespace perfetto { namespace base { void MaybeReleaseAllocatorMemToOS() { #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // mallopt() on Android requires SDK level 26. Many targets and embedders // still depend on a lower SDK level. Given mallopt() is a quite simple API, // use reflection to do this rather than bumping the SDK level for all // embedders. This keeps the behavior of standalone builds aligned with // in-tree builds. static MalloptType mallopt_fn = reinterpret_cast<MalloptType>(dlsym(RTLD_DEFAULT, "mallopt")); if (!mallopt_fn) return; mallopt_fn(PERFETTO_M_PURGE, 0); #endif } uint32_t GetSysPageSize() { ignore_result(kPageSize); // Just to keep the amalgamated build happy. #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) static std::atomic<uint32_t> page_size{0}; // This function might be called in hot paths. Avoid calling getpagesize() all // the times, in many implementations getpagesize() calls sysconf() which is // not cheap. uint32_t cached_value = page_size.load(std::memory_order_relaxed); if (PERFETTO_UNLIKELY(cached_value == 0)) { cached_value = static_cast<uint32_t>(getpagesize()); page_size.store(cached_value, std::memory_order_relaxed); } return cached_value; #elif PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) return static_cast<uint32_t>(vm_page_size); #else return 4096; #endif } uid_t GetCurrentUserId() { #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) return geteuid(); #else // TODO(primiano): On Windows we could hash the current user SID and derive a // numeric user id [1]. It is not clear whether we need that. Right now that // would not bring any benefit. Returning 0 unil we can prove we need it. // [1]:https://android-review.googlesource.com/c/platform/external/perfetto/+/1513879/25/src/base/utils.cc return 0; #endif } void SetEnv(const std::string& key, const std::string& value) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) PERFETTO_CHECK(::_putenv_s(key.c_str(), value.c_str()) == 0); #else PERFETTO_CHECK(::setenv(key.c_str(), value.c_str(), /*overwrite=*/true) == 0); #endif } void Daemonize(std::function<int()> parent_cb) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) pid_t pid; switch (pid = fork()) { case -1: PERFETTO_FATAL("fork"); case 0: { PERFETTO_CHECK(setsid() != -1); base::ignore_result(chdir("/")); base::ScopedFile null = base::OpenFile("/dev/null", O_RDONLY); PERFETTO_CHECK(null); PERFETTO_CHECK(dup2(*null, STDIN_FILENO) != -1); PERFETTO_CHECK(dup2(*null, STDOUT_FILENO) != -1); PERFETTO_CHECK(dup2(*null, STDERR_FILENO) != -1); // Do not accidentally close stdin/stdout/stderr. if (*null <= 2) null.release(); break; } default: printf("%d\n", pid); int err = parent_cb(); exit(err); } #else // Avoid -Wunreachable warnings. if (reinterpret_cast<intptr_t>(&Daemonize) != 16) PERFETTO_FATAL("--background is only supported on Linux/Android/Mac"); ignore_result(parent_cb); #endif // OS_WIN } std::string GetCurExecutablePath() { std::string self_path; #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) char buf[PATH_MAX]; ssize_t size = readlink("/proc/self/exe", buf, sizeof(buf)); PERFETTO_CHECK(size != -1); // readlink does not null terminate. self_path = std::string(buf, static_cast<size_t>(size)); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) uint32_t size = 0; PERFETTO_CHECK(_NSGetExecutablePath(nullptr, &size)); self_path.resize(size); PERFETTO_CHECK(_NSGetExecutablePath(&self_path[0], &size) == 0); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) char buf[MAX_PATH]; auto len = ::GetModuleFileNameA(nullptr /*current*/, buf, sizeof(buf)); self_path = std::string(buf, len); #else PERFETTO_FATAL( "GetCurExecutableDir() not implemented on the current platform"); #endif return self_path; } std::string GetCurExecutableDir() { auto path = GetCurExecutablePath(); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Paths in Windows can have both kinds of slashes (mingw vs msvc). path = path.substr(0, path.find_last_of('\\')); #endif path = path.substr(0, path.find_last_of('/')); return path; } void* AlignedAlloc(size_t alignment, size_t size) { void* res = nullptr; alignment = AlignUp<sizeof(void*)>(alignment); // At least pointer size. #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Window's _aligned_malloc() has a nearly identically signature to Unix's // aligned_alloc() but its arguments are obviously swapped. res = _aligned_malloc(size, alignment); #else // aligned_alloc() has been introduced in Android only in API 28. // Also NaCl and Fuchsia seems to have only posix_memalign(). ignore_result(posix_memalign(&res, alignment, size)); #endif PERFETTO_CHECK(res); return res; } void AlignedFree(void* ptr) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) _aligned_free(ptr); // MSDN says it is fine to pass nullptr. #else free(ptr); #endif } std::string HexDump(const void* data_void, size_t len, size_t bytes_per_line) { const char* data = reinterpret_cast<const char*>(data_void); std::string res; static const size_t kPadding = bytes_per_line * 3 + 12; std::unique_ptr<char[]> line(new char[bytes_per_line * 4 + 128]); for (size_t i = 0; i < len; i += bytes_per_line) { char* wptr = line.get(); wptr += sprintf(wptr, "%08zX: ", i); for (size_t j = i; j < i + bytes_per_line && j < len; j++) wptr += sprintf(wptr, "%02X ", static_cast<unsigned>(data[j]) & 0xFF); for (size_t j = static_cast<size_t>(wptr - line.get()); j < kPadding; ++j) *(wptr++) = ' '; for (size_t j = i; j < i + bytes_per_line && j < len; j++) { char c = data[j]; *(wptr++) = (c >= 32 && c < 127) ? c : '.'; } *(wptr++) = '\n'; *(wptr++) = '\0'; res.append(line.get()); } return res; } } // namespace base } // namespace perfetto
Improve SSE4.2 errors on MacOS
Improve SSE4.2 errors on MacOS Give some more hints about Rosetta-related errors when failing on MacOS. Bug: https://github.com/google/perfetto/issues/294 Change-Id: If4ac88f63382eb19702865615cc6955e2146f30c
C++
apache-2.0
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
dfea0bbb817a6cf06aea49933eab92fb68c0ab4a
modules/prediction/scenario/feature_extractor/feature_extractor.cc
modules/prediction/scenario/feature_extractor/feature_extractor.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/scenario/feature_extractor/feature_extractor.h" #include <string> #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/common/math/vec2d.h" #include "modules/map/hdmap/hdmap_util.h" using apollo::common::adapter::AdapterConfig; using apollo::common::math::Vec2d; using apollo::planning::ADCTrajectory; using apollo::hdmap::HDMapUtil; using apollo::hdmap::LaneInfo; using apollo::hdmap::JunctionInfo; using JunctionInfoPtr = std::shared_ptr<const JunctionInfo>; using LaneInfoPtr = std::shared_ptr<const LaneInfo>; namespace apollo { namespace prediction { EnvironmentFeatures FeatureExtractor::ExtractEnvironmentFeatures() { EnvironmentFeatures environment_features; PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::LOCALIZATION)); if (pose_container == nullptr) { AERROR << "Null pose container found."; return environment_features; } ExtractEgoVehicleFeatures(&environment_features); auto ego_trajectory_point = pose_container->GetPosition(); if (!ego_trajectory_point.has_x() || !ego_trajectory_point.has_y()) { AERROR << "Fail to get ego vehicle position"; return environment_features; } Vec2d ego_position(ego_trajectory_point.x(), ego_trajectory_point.y()); auto ptr_ego_lane = GetEgoLane(ego_position); ExtractEgoLaneFeatures(&environment_features, ptr_ego_lane, ego_position); ExtractNeighborLaneFeatures( &environment_features, ptr_ego_lane, ego_position); ExtractFrontJunctionFeatures(&environment_features); ExtractObstacleFeatures(&environment_features); // TODO(all): add other features return environment_features; } void FeatureExtractor::ExtractEgoVehicleFeatures( EnvironmentFeatures* ptr_environment_features) { PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::LOCALIZATION)); // TODO(all): change this to ego_speed and ego_heading ptr_environment_features->set_ego_speed(pose_container->GetSpeed()); ptr_environment_features->set_ego_heading(pose_container->GetTheta()); // TODO(all): add acceleration if needed } void FeatureExtractor::ExtractEgoLaneFeatures( EnvironmentFeatures* ptr_environment_features, const LaneInfoPtr& ptr_ego_lane, const common::math::Vec2d& ego_position) { if (ptr_ego_lane == nullptr) { ADEBUG << "Ego vehicle is not on any lane."; return; } double curr_lane_s = 0.0; double curr_lane_l = 0.0; ptr_ego_lane->GetProjection(ego_position, &curr_lane_s, &curr_lane_l); ptr_environment_features->SetEgoLane(ptr_ego_lane->id().id(), curr_lane_s); double threshold = 1.0; auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold); if (ptr_left_neighbor_lane == nullptr && ptr_ego_lane->lane().has_left_boundary() && ptr_ego_lane->lane().left_boundary().boundary_type_size() != 0 && ptr_ego_lane->lane().left_boundary().boundary_type(0).types_size() != 0 && ptr_ego_lane->lane().left_boundary().boundary_type(0).types(0) != hdmap::LaneBoundaryType::CURB) { const auto& reverse_lanes = ptr_ego_lane->lane().left_neighbor_reverse_lane_id(); std::for_each(reverse_lanes.begin(), reverse_lanes.end(), [&ptr_environment_features](decltype(*reverse_lanes.begin())& t) { ptr_environment_features->AddNonneglectableReverseLanes(t.id()); }); } } void FeatureExtractor::ExtractNeighborLaneFeatures( EnvironmentFeatures* ptr_environment_features, const LaneInfoPtr& ptr_ego_lane, const Vec2d& ego_position) { if (ptr_ego_lane == nullptr) { AERROR << "Ego vehicle is not on any lane."; return; } // TODO(all): make this a gflag double threshold = 3.0; auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold); if (ptr_left_neighbor_lane != nullptr) { double left_neighbor_lane_s = 0.0; double left_neighbor_lane_l = 0.0; ptr_left_neighbor_lane->GetProjection(ego_position, &left_neighbor_lane_s, &left_neighbor_lane_l); ptr_environment_features->SetLeftNeighborLane( ptr_left_neighbor_lane->id().id(), left_neighbor_lane_s); } auto ptr_right_neighbor_lane = PredictionMap::GetRightNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold); if (ptr_right_neighbor_lane != nullptr) { double right_neighbor_lane_s = 0.0; double right_neighbor_lane_l = 0.0; ptr_right_neighbor_lane->GetProjection(ego_position, &right_neighbor_lane_s, &right_neighbor_lane_l); ptr_environment_features->SetRightNeighborLane( ptr_right_neighbor_lane->id().id(), right_neighbor_lane_s); } } void FeatureExtractor::ExtractFrontJunctionFeatures( EnvironmentFeatures* ptr_environment_features) { ADCTrajectoryContainer* ego_trajectory_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); if (ego_trajectory_container == nullptr) { AERROR << "Null ego trajectory container"; return; } JunctionInfoPtr junction = ego_trajectory_container->ADCJunction(); if (junction != nullptr) { ptr_environment_features->SetFrontJunction(junction->id().id(), ego_trajectory_container->ADCDistanceToJunction()); } } void FeatureExtractor::ExtractObstacleFeatures( EnvironmentFeatures* ptr_environment_features) { } LaneInfoPtr FeatureExtractor::GetEgoLane(const Vec2d& ego_position) { ADCTrajectoryContainer* ego_trajectory_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); const auto& trajectory = ego_trajectory_container->adc_trajectory(); for (const auto& lane_id : trajectory.lane_id()) { LaneInfoPtr lane_info = HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(lane_id.id())); if (lane_info->IsOnLane(ego_position)) { return lane_info; } } return nullptr; } } // namespace prediction } // namespace apollo
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/scenario/feature_extractor/feature_extractor.h" #include <string> #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/common/math/vec2d.h" #include "modules/map/hdmap/hdmap_util.h" using apollo::common::adapter::AdapterConfig; using apollo::common::math::Vec2d; using apollo::planning::ADCTrajectory; using apollo::hdmap::HDMapUtil; using apollo::hdmap::LaneInfo; using apollo::hdmap::JunctionInfo; using JunctionInfoPtr = std::shared_ptr<const JunctionInfo>; using LaneInfoPtr = std::shared_ptr<const LaneInfo>; namespace apollo { namespace prediction { EnvironmentFeatures FeatureExtractor::ExtractEnvironmentFeatures() { EnvironmentFeatures environment_features; PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::LOCALIZATION)); if (pose_container == nullptr) { AERROR << "Null pose container found."; return environment_features; } ExtractEgoVehicleFeatures(&environment_features); auto ego_trajectory_point = pose_container->GetPosition(); if (!ego_trajectory_point.has_x() || !ego_trajectory_point.has_y()) { AERROR << "Fail to get ego vehicle position"; return environment_features; } Vec2d ego_position(ego_trajectory_point.x(), ego_trajectory_point.y()); auto ptr_ego_lane = GetEgoLane(ego_position); ExtractEgoLaneFeatures(&environment_features, ptr_ego_lane, ego_position); ExtractNeighborLaneFeatures( &environment_features, ptr_ego_lane, ego_position); ExtractFrontJunctionFeatures(&environment_features); ExtractObstacleFeatures(&environment_features); // TODO(all): add other features return environment_features; } void FeatureExtractor::ExtractEgoVehicleFeatures( EnvironmentFeatures* ptr_environment_features) { PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::LOCALIZATION)); // TODO(all): change this to ego_speed and ego_heading ptr_environment_features->set_ego_speed(pose_container->GetSpeed()); ptr_environment_features->set_ego_heading(pose_container->GetTheta()); // TODO(all): add acceleration if needed } void FeatureExtractor::ExtractEgoLaneFeatures( EnvironmentFeatures* ptr_environment_features, const LaneInfoPtr& ptr_ego_lane, const common::math::Vec2d& ego_position) { if (ptr_ego_lane == nullptr) { ADEBUG << "Ego vehicle is not on any lane."; return; } AINFO << "Ego vehicle is on lane [" << ptr_ego_lane->id().id() << "]"; double curr_lane_s = 0.0; double curr_lane_l = 0.0; ptr_ego_lane->GetProjection(ego_position, &curr_lane_s, &curr_lane_l); ptr_environment_features->SetEgoLane(ptr_ego_lane->id().id(), curr_lane_s); double threshold = 1.0; auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold); if (ptr_left_neighbor_lane == nullptr && ptr_ego_lane->lane().has_left_boundary() && ptr_ego_lane->lane().left_boundary().boundary_type_size() != 0 && ptr_ego_lane->lane().left_boundary().boundary_type(0).types_size() != 0 && ptr_ego_lane->lane().left_boundary().boundary_type(0).types(0) != hdmap::LaneBoundaryType::CURB) { const auto& reverse_lanes = ptr_ego_lane->lane().left_neighbor_reverse_lane_id(); std::for_each(reverse_lanes.begin(), reverse_lanes.end(), [&ptr_environment_features](decltype(*reverse_lanes.begin())& t) { ptr_environment_features->AddNonneglectableReverseLanes(t.id()); }); } } void FeatureExtractor::ExtractNeighborLaneFeatures( EnvironmentFeatures* ptr_environment_features, const LaneInfoPtr& ptr_ego_lane, const Vec2d& ego_position) { if (ptr_ego_lane == nullptr) { AERROR << "Ego vehicle is not on any lane."; return; } // TODO(all): make this a gflag double threshold = 3.0; auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold); if (ptr_left_neighbor_lane != nullptr) { double left_neighbor_lane_s = 0.0; double left_neighbor_lane_l = 0.0; ptr_left_neighbor_lane->GetProjection(ego_position, &left_neighbor_lane_s, &left_neighbor_lane_l); ptr_environment_features->SetLeftNeighborLane( ptr_left_neighbor_lane->id().id(), left_neighbor_lane_s); } auto ptr_right_neighbor_lane = PredictionMap::GetRightNeighborLane( ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold); if (ptr_right_neighbor_lane != nullptr) { double right_neighbor_lane_s = 0.0; double right_neighbor_lane_l = 0.0; ptr_right_neighbor_lane->GetProjection(ego_position, &right_neighbor_lane_s, &right_neighbor_lane_l); ptr_environment_features->SetRightNeighborLane( ptr_right_neighbor_lane->id().id(), right_neighbor_lane_s); } } void FeatureExtractor::ExtractFrontJunctionFeatures( EnvironmentFeatures* ptr_environment_features) { ADCTrajectoryContainer* ego_trajectory_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); if (ego_trajectory_container == nullptr) { AERROR << "Null ego trajectory container"; return; } JunctionInfoPtr junction = ego_trajectory_container->ADCJunction(); if (junction != nullptr) { ptr_environment_features->SetFrontJunction(junction->id().id(), ego_trajectory_container->ADCDistanceToJunction()); } } void FeatureExtractor::ExtractObstacleFeatures( EnvironmentFeatures* ptr_environment_features) { } LaneInfoPtr FeatureExtractor::GetEgoLane(const Vec2d& ego_position) { ADCTrajectoryContainer* ego_trajectory_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); const auto& trajectory = ego_trajectory_container->adc_trajectory(); for (const auto& lane_id : trajectory.lane_id()) { LaneInfoPtr lane_info = HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(lane_id.id())); if (lane_info->IsOnLane(ego_position)) { return lane_info; } } return nullptr; } } // namespace prediction } // namespace apollo
add a log of ego vehicle lane
Prediction: add a log of ego vehicle lane
C++
apache-2.0
xiaoxq/apollo,jinghaomiao/apollo,wanglei828/apollo,jinghaomiao/apollo,wanglei828/apollo,xiaoxq/apollo,ycool/apollo,ycool/apollo,jinghaomiao/apollo,ycool/apollo,ApolloAuto/apollo,ycool/apollo,ApolloAuto/apollo,wanglei828/apollo,ApolloAuto/apollo,xiaoxq/apollo,xiaoxq/apollo,jinghaomiao/apollo,ApolloAuto/apollo,ApolloAuto/apollo,ycool/apollo,ycool/apollo,xiaoxq/apollo,wanglei828/apollo,wanglei828/apollo,wanglei828/apollo,xiaoxq/apollo,ApolloAuto/apollo,jinghaomiao/apollo,jinghaomiao/apollo
67f4f5a87a590102dd0ee33bf9e7493296cc709b
graf3d/eve/src/TEveCalo2DGL.cxx
graf3d/eve/src/TEveCalo2DGL.cxx
// @(#)root/eve:$Id$ // Author: Matevz Tadel 2007 /************************************************************************* * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TEveCalo2DGL.h" #include "TEveCalo.h" #include "TEveProjections.h" #include "TEveProjectionManager.h" #include "TEveRGBAPalette.h" #include "TGLRnrCtx.h" #include "TGLSelectRecord.h" #include "TGLIncludes.h" #include "TGLUtil.h" #include "TAxis.h" //______________________________________________________________________________ // OpenGL renderer class for TEveCalo2D. // ClassImp(TEveCalo2DGL); //______________________________________________________________________________ TEveCalo2DGL::TEveCalo2DGL() : TGLObject(), fM(0) { // Constructor. // fDLCache = kFALSE; // Disable display list. fMultiColor = kTRUE; } /******************************************************************************/ //______________________________________________________________________________ Bool_t TEveCalo2DGL::SetModel(TObject* obj, const Option_t* /*opt*/) { // Set model object. if (SetModelCheckClass(obj, TEveCalo2D::Class())) { fM = dynamic_cast<TEveCalo2D*>(obj); return kTRUE; } return kFALSE; } //______________________________________________________________________________ void TEveCalo2DGL::SetBBox() { // Set bounding box. SetAxisAlignedBBox(((TEveCalo2D*)fExternalObj)->AssertBBox()); } /******************************************************************************/ //______________________________________________________________________________ Float_t TEveCalo2DGL::MakeRPhiCell(Float_t phiMin, Float_t phiMax, Float_t towerH, Float_t offset) const { // Calculate vertices for the calorimeter cell in RPhi projection. // Returns outside radius of the tower. using namespace TMath; Float_t r1 = fM->fBarrelRadius + offset; Float_t r2 = r1 + towerH; Float_t pnts[8]; pnts[0] = r1*Cos(phiMin); pnts[1] = r1*Sin(phiMin); pnts[2] = r2*Cos(phiMin); pnts[3] = r2*Sin(phiMin); pnts[4] = r2*Cos(phiMax); pnts[5] = r2*Sin(phiMax); pnts[6] = r1*Cos(phiMax); pnts[7] = r1*Sin(phiMax); Float_t x, y, z; for (Int_t i = 0; i < 4; ++i) { x = pnts[2*i]; y = pnts[2*i+1]; z = 0.f; fM->fManager->GetProjection()->ProjectPoint(x, y, z); glVertex3f(x, y, fM->fDepth); } return offset + towerH; } //______________________________________________________________________________ void TEveCalo2DGL::DrawRPhi(TGLRnrCtx & rnrCtx) const { // Draw calorimeter cells in RPhi projection. TEveCaloData* data = fM->GetData(); if (fM->fCacheOK == kFALSE) { fM->ResetCache(); const TAxis* ay = data->GetPhiBins(); Int_t nBins = ay->GetNbins(); for (Int_t ibin = 1; ibin <= nBins; ++ibin) { if (TEveUtil::IsU1IntervalOverlappingByMinMax (fM->GetPhiMin(), fM->GetPhiMax(), ay->GetBinLowEdge(ibin), ay->GetBinUpEdge(ibin))) { TEveCaloData::vCellId_t* clv = new TEveCaloData::vCellId_t(); data->GetCellList(fM->GetEta(), fM->GetEtaRng(), ay->GetBinCenter(ibin), ay->GetBinWidth(ibin), *clv); if (clv->empty() == kFALSE) fM->fCellLists.push_back(clv); else delete clv; } } fM->fCacheOK = kTRUE; } Int_t nSlices = data->GetNSlices(); Float_t *sliceVal = new Float_t[nSlices]; TEveCaloData::CellData_t cellData; Float_t towerH; if (rnrCtx.SecSelection()) glPushName(0); for(UInt_t vi = 0; vi < fM->fCellLists.size(); ++vi) { // reset values Float_t off = 0; for (Int_t s = 0; s < nSlices; ++s) sliceVal[s] = 0; // loop through eta bins TEveCaloData::vCellId_t* cids = fM->fCellLists[vi]; for (TEveCaloData::vCellId_i it = cids->begin(); it != cids->end(); it++) { data->GetCellData(*it, cellData); sliceVal[(*it).fSlice] += cellData.Value(fM->fPlotEt); } // draw if (rnrCtx.SecSelection()) { glLoadName(vi); glPushName(0); } for (Int_t s = 0; s < nSlices; ++s) { fM->SetupColorHeight(sliceVal[s], s, towerH); if (rnrCtx.SecSelection()) glLoadName(s); glBegin(GL_QUADS); off = MakeRPhiCell(cellData.PhiMin(), cellData.PhiMax(), towerH, off); glEnd(); } if (rnrCtx.SecSelection()) glPopName(); // slice } if (rnrCtx.SecSelection()) glPopName(); // etha bin } /*******************************************************************************/ /*******************************************************************************/ //______________________________________________________________________________ void TEveCalo2DGL::MakeRhoZCell(const TEveCaloData::CellData_t &cell, Float_t& offset, Bool_t phiPlus, Float_t towerH) const { // Draw cell in RhoZ projection. using namespace TMath; Float_t pnts[8]; Float_t sin1 = Sin(cell.ThetaMin()); Float_t cos1 = Cos(cell.ThetaMin()); Float_t sin2 = Sin(cell.ThetaMax()); Float_t cos2 = Cos(cell.ThetaMax()); if (Abs(cell.EtaMax()) < fM->GetTransitionEta()) { // barrel Float_t r1 = fM->fBarrelRadius/Abs(Sin((cell.ThetaMin()+cell.ThetaMax())*0.5)) + offset; Float_t r2 = r1 + towerH; pnts[0] = r1*sin1; pnts[1] = r1*cos1; pnts[2] = r2*sin1; pnts[3] = r2*cos1; pnts[4] = r2*sin2; pnts[5] = r2*cos2; pnts[6] = r1*sin2; pnts[7] = r1*cos2; } else { // endcap Float_t r1 =fM->GetEndCapPos()/Abs(Cos((cell.ThetaMin()+cell.ThetaMax())*0.5)) + offset; Float_t r2 = r1 + towerH; pnts[0] = r1*sin1; pnts[1] = r1*cos1; pnts[2] = r2*sin1; pnts[3] = r2*cos1; pnts[4] = r2*sin2; pnts[5] = r2*cos2; pnts[6] = r1*sin2; pnts[7] = r1*cos2; } glPushName(phiPlus); glBegin(GL_QUADS); Float_t x, y, z; for (Int_t i = 0; i < 4; ++i) { x = 0.f; y = phiPlus ? Abs(pnts[2*i]): -Abs(pnts[2*i]); z = pnts[2*i+1]; fM->fManager->GetProjection()->ProjectPoint(x, y, z); glVertex3f(x, y, fM->fDepth); } glEnd(); glPopName(); offset += towerH; } //______________________________________________________________________________ void TEveCalo2DGL::DrawRhoZ(TGLRnrCtx & rnrCtx) const { // Draw calorimeter in RhoZ projection. TEveCaloData* data = fM->GetData(); if (fM->fCacheOK == kFALSE) { fM->ResetCache(); const TAxis* ax = data->GetEtaBins(); Int_t nBins = ax->GetNbins(); for (Int_t ibin = 1; ibin <= nBins; ++ibin) { if (ax->GetBinLowEdge(ibin) > fM->fEtaMin && ax->GetBinUpEdge(ibin) <= fM->fEtaMax) { TEveCaloData::vCellId_t* aa = new TEveCaloData::vCellId_t(); data->GetCellList(ax->GetBinCenter(ibin), ax->GetBinWidth(ibin)+1e-5, fM->fPhi, fM->GetPhiRng(), *aa); if (aa->size()) fM->fCellLists.push_back(aa); else delete aa; } } fM->fCacheOK= kTRUE; } TEveCaloData::CellData_t cellData; Float_t towerH; Int_t nSlices = data->GetNSlices(); Float_t *sliceValsUp = new Float_t[nSlices]; Float_t *sliceValsLow = new Float_t[nSlices]; if (rnrCtx.SecSelection()) glPushName(0); for (UInt_t vi = 0; vi < fM->fCellLists.size(); ++vi) { // clear Float_t offUp = 0; Float_t offLow = 0; for (Int_t s = 0; s < nSlices; ++s) { sliceValsUp[s] = 0; sliceValsLow[s] = 0; } // values for (TEveCaloData::vCellId_i it = fM->fCellLists[vi]->begin(); it != fM->fCellLists[vi]->end(); ++it) { data->GetCellData(*it, cellData); if (cellData.Phi() > 0) sliceValsUp[(*it).fSlice] += cellData.Value(fM->fPlotEt); else sliceValsLow[(*it).fSlice] += cellData.Value(fM->fPlotEt); } // draw if (rnrCtx.SecSelection()) { glLoadName(vi); // phi bin glPushName(0); // slice } for (Int_t s = 0; s < nSlices; ++s) { if (rnrCtx.SecSelection()) glLoadName(s); // phi + fM->SetupColorHeight(sliceValsUp[s], s, towerH); MakeRhoZCell(cellData, offUp, kTRUE , towerH); // phi - fM->SetupColorHeight(sliceValsLow[s], s, towerH); MakeRhoZCell(cellData, offLow, kFALSE , towerH); } if (rnrCtx.SecSelection()) glPopName(); // slice } if (rnrCtx.SecSelection()) glPopName(); // phi bin delete [] sliceValsUp; delete [] sliceValsLow; } //______________________________________________________________________________ void TEveCalo2DGL::DirectDraw(TGLRnrCtx & rnrCtx) const { // Render with OpenGL. printf("TEveCalo2DGL::DirectDraw()\n"); TGLCapabilitySwitch light_off(GL_LIGHTING, kFALSE); TGLCapabilitySwitch cull_off (GL_CULL_FACE, kFALSE); TEveProjection::EPType_e pt = fM->fManager->GetProjection()->GetType(); if (pt == TEveProjection::kPT_RhoZ) DrawRhoZ(rnrCtx); else if (pt == TEveProjection::kPT_RPhi) DrawRPhi(rnrCtx); } //______________________________________________________________________________ void TEveCalo2DGL::ProcessSelection(TGLRnrCtx & /*rnrCtx*/, TGLSelectRecord & rec) { // Processes secondary selection from TGLViewer. if (rec.GetN() < 2) return; Int_t id = rec.GetItem(1); Int_t slice = rec.GetItem(2); TEveCaloData::CellData_t cellData; Int_t n = 0; for (TEveCaloData::vCellId_i it =fM->fCellLists[id]->begin(); it!=fM->fCellLists[id]->end(); it++) { if ((*it).fSlice == slice) n++; } printf("Tower selected in slice %d number of hits: %2d \n", slice, n); for (TEveCaloData::vCellId_i it =fM->fCellLists[id]->begin(); it!=fM->fCellLists[id]->end(); it++) { if ((*it).fSlice == slice) { fM->fData->GetCellData(*it, cellData); cellData.Dump(); } } // rho Z if (rec.GetN() == 4) { if(rec.GetItem(3)) printf("Cell in selected positive phi half \n"); else printf("Cell in selected negative phi half \n"); for (TEveCaloData::vCellId_i it = fM->fCellLists[id]->begin(); it != fM->fCellLists[id]->end(); ++it) { fM->fData->GetCellData(*it, cellData); if ((*it).fSlice == slice) { if ((rec.GetItem(3) && cellData.Phi() > 0) || (rec.GetItem(3) == kFALSE && cellData.Phi() < 0)) { cellData.Dump(); } } } } }
// @(#)root/eve:$Id$ // Author: Matevz Tadel 2007 /************************************************************************* * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TEveCalo2DGL.h" #include "TEveCalo.h" #include "TEveProjections.h" #include "TEveProjectionManager.h" #include "TEveRGBAPalette.h" #include "TGLRnrCtx.h" #include "TGLSelectRecord.h" #include "TGLIncludes.h" #include "TGLUtil.h" #include "TAxis.h" //______________________________________________________________________________ // OpenGL renderer class for TEveCalo2D. // ClassImp(TEveCalo2DGL); //______________________________________________________________________________ TEveCalo2DGL::TEveCalo2DGL() : TGLObject(), fM(0) { // Constructor. // fDLCache = kFALSE; // Disable display list. fMultiColor = kTRUE; } /******************************************************************************/ //______________________________________________________________________________ Bool_t TEveCalo2DGL::SetModel(TObject* obj, const Option_t* /*opt*/) { // Set model object. if (SetModelCheckClass(obj, TEveCalo2D::Class())) { fM = dynamic_cast<TEveCalo2D*>(obj); return kTRUE; } return kFALSE; } //______________________________________________________________________________ void TEveCalo2DGL::SetBBox() { // Set bounding box. SetAxisAlignedBBox(((TEveCalo2D*)fExternalObj)->AssertBBox()); } /******************************************************************************/ //______________________________________________________________________________ Float_t TEveCalo2DGL::MakeRPhiCell(Float_t phiMin, Float_t phiMax, Float_t towerH, Float_t offset) const { // Calculate vertices for the calorimeter cell in RPhi projection. // Returns outside radius of the tower. using namespace TMath; Float_t r1 = fM->fBarrelRadius + offset; Float_t r2 = r1 + towerH; Float_t pnts[8]; pnts[0] = r1*Cos(phiMin); pnts[1] = r1*Sin(phiMin); pnts[2] = r2*Cos(phiMin); pnts[3] = r2*Sin(phiMin); pnts[4] = r2*Cos(phiMax); pnts[5] = r2*Sin(phiMax); pnts[6] = r1*Cos(phiMax); pnts[7] = r1*Sin(phiMax); Float_t x, y, z; for (Int_t i = 0; i < 4; ++i) { x = pnts[2*i]; y = pnts[2*i+1]; z = 0.f; fM->fManager->GetProjection()->ProjectPoint(x, y, z); glVertex3f(x, y, fM->fDepth); } return offset + towerH; } //______________________________________________________________________________ void TEveCalo2DGL::DrawRPhi(TGLRnrCtx & rnrCtx) const { // Draw calorimeter cells in RPhi projection. TEveCaloData* data = fM->GetData(); if (fM->fCacheOK == kFALSE) { fM->ResetCache(); const TAxis* ay = data->GetPhiBins(); Int_t nBins = ay->GetNbins(); for (Int_t ibin = 1; ibin <= nBins; ++ibin) { if (TEveUtil::IsU1IntervalOverlappingByMinMax (fM->GetPhiMin(), fM->GetPhiMax(), ay->GetBinLowEdge(ibin), ay->GetBinUpEdge(ibin))) { TEveCaloData::vCellId_t* clv = new TEveCaloData::vCellId_t(); data->GetCellList(fM->GetEta(), fM->GetEtaRng(), ay->GetBinCenter(ibin), ay->GetBinWidth(ibin), *clv); if (clv->empty() == kFALSE) fM->fCellLists.push_back(clv); else delete clv; } } fM->fCacheOK = kTRUE; } Int_t nSlices = data->GetNSlices(); Float_t *sliceVal = new Float_t[nSlices]; TEveCaloData::CellData_t cellData; Float_t towerH; if (rnrCtx.SecSelection()) glPushName(0); for(UInt_t vi = 0; vi < fM->fCellLists.size(); ++vi) { // reset values Float_t off = 0; for (Int_t s = 0; s < nSlices; ++s) sliceVal[s] = 0; // loop through eta bins TEveCaloData::vCellId_t* cids = fM->fCellLists[vi]; for (TEveCaloData::vCellId_i it = cids->begin(); it != cids->end(); it++) { data->GetCellData(*it, cellData); sliceVal[(*it).fSlice] += cellData.Value(fM->fPlotEt); } // draw if (rnrCtx.SecSelection()) { glLoadName(vi); glPushName(0); } for (Int_t s = 0; s < nSlices; ++s) { fM->SetupColorHeight(sliceVal[s], s, towerH); if (rnrCtx.SecSelection()) glLoadName(s); glBegin(GL_QUADS); off = MakeRPhiCell(cellData.PhiMin(), cellData.PhiMax(), towerH, off); glEnd(); } if (rnrCtx.SecSelection()) glPopName(); // slice } if (rnrCtx.SecSelection()) glPopName(); // etha bin } /*******************************************************************************/ /*******************************************************************************/ //______________________________________________________________________________ void TEveCalo2DGL::MakeRhoZCell(const TEveCaloData::CellData_t &cell, Float_t& offset, Bool_t phiPlus, Float_t towerH) const { // Draw cell in RhoZ projection. using namespace TMath; Float_t pnts[8]; Float_t sin1 = Sin(cell.ThetaMin()); Float_t cos1 = Cos(cell.ThetaMin()); Float_t sin2 = Sin(cell.ThetaMax()); Float_t cos2 = Cos(cell.ThetaMax()); if (Abs(cell.EtaMax()) < fM->GetTransitionEta()) { // barrel Float_t r1 = fM->fBarrelRadius/Abs(Sin((cell.ThetaMin()+cell.ThetaMax())*0.5)) + offset; Float_t r2 = r1 + towerH; pnts[0] = r1*sin1; pnts[1] = r1*cos1; pnts[2] = r2*sin1; pnts[3] = r2*cos1; pnts[4] = r2*sin2; pnts[5] = r2*cos2; pnts[6] = r1*sin2; pnts[7] = r1*cos2; } else { // endcap Float_t r1 =fM->GetEndCapPos()/Abs(Cos((cell.ThetaMin()+cell.ThetaMax())*0.5)) + offset; Float_t r2 = r1 + towerH; pnts[0] = r1*sin1; pnts[1] = r1*cos1; pnts[2] = r2*sin1; pnts[3] = r2*cos1; pnts[4] = r2*sin2; pnts[5] = r2*cos2; pnts[6] = r1*sin2; pnts[7] = r1*cos2; } glPushName(phiPlus); glBegin(GL_QUADS); Float_t x, y, z; for (Int_t i = 0; i < 4; ++i) { x = 0.f; y = phiPlus ? Abs(pnts[2*i]): -Abs(pnts[2*i]); z = pnts[2*i+1]; fM->fManager->GetProjection()->ProjectPoint(x, y, z); glVertex3f(x, y, fM->fDepth); } glEnd(); glPopName(); offset += towerH; } //______________________________________________________________________________ void TEveCalo2DGL::DrawRhoZ(TGLRnrCtx & rnrCtx) const { // Draw calorimeter in RhoZ projection. TEveCaloData* data = fM->GetData(); if (fM->fCacheOK == kFALSE) { fM->ResetCache(); const TAxis* ax = data->GetEtaBins(); Int_t nBins = ax->GetNbins(); for (Int_t ibin = 1; ibin <= nBins; ++ibin) { if (ax->GetBinLowEdge(ibin) > fM->fEtaMin && ax->GetBinUpEdge(ibin) <= fM->fEtaMax) { TEveCaloData::vCellId_t* aa = new TEveCaloData::vCellId_t(); data->GetCellList(ax->GetBinCenter(ibin), ax->GetBinWidth(ibin)+1e-5, fM->fPhi, fM->GetPhiRng(), *aa); if (aa->size()) fM->fCellLists.push_back(aa); else delete aa; } } fM->fCacheOK= kTRUE; } TEveCaloData::CellData_t cellData; Float_t towerH; Int_t nSlices = data->GetNSlices(); Float_t *sliceValsUp = new Float_t[nSlices]; Float_t *sliceValsLow = new Float_t[nSlices]; if (rnrCtx.SecSelection()) glPushName(0); for (UInt_t vi = 0; vi < fM->fCellLists.size(); ++vi) { // clear Float_t offUp = 0; Float_t offLow = 0; for (Int_t s = 0; s < nSlices; ++s) { sliceValsUp[s] = 0; sliceValsLow[s] = 0; } // values for (TEveCaloData::vCellId_i it = fM->fCellLists[vi]->begin(); it != fM->fCellLists[vi]->end(); ++it) { data->GetCellData(*it, cellData); if (cellData.Phi() > 0) sliceValsUp[(*it).fSlice] += cellData.Value(fM->fPlotEt); else sliceValsLow[(*it).fSlice] += cellData.Value(fM->fPlotEt); } // draw if (rnrCtx.SecSelection()) { glLoadName(vi); // phi bin glPushName(0); // slice } for (Int_t s = 0; s < nSlices; ++s) { if (rnrCtx.SecSelection()) glLoadName(s); // phi + fM->SetupColorHeight(sliceValsUp[s], s, towerH); MakeRhoZCell(cellData, offUp, kTRUE , towerH); // phi - fM->SetupColorHeight(sliceValsLow[s], s, towerH); MakeRhoZCell(cellData, offLow, kFALSE , towerH); } if (rnrCtx.SecSelection()) glPopName(); // slice } if (rnrCtx.SecSelection()) glPopName(); // phi bin delete [] sliceValsUp; delete [] sliceValsLow; } //______________________________________________________________________________ void TEveCalo2DGL::DirectDraw(TGLRnrCtx & rnrCtx) const { // Render with OpenGL. TGLCapabilitySwitch light_off(GL_LIGHTING, kFALSE); TGLCapabilitySwitch cull_off (GL_CULL_FACE, kFALSE); TEveProjection::EPType_e pt = fM->fManager->GetProjection()->GetType(); if (pt == TEveProjection::kPT_RhoZ) DrawRhoZ(rnrCtx); else if (pt == TEveProjection::kPT_RPhi) DrawRPhi(rnrCtx); } //______________________________________________________________________________ void TEveCalo2DGL::ProcessSelection(TGLRnrCtx & /*rnrCtx*/, TGLSelectRecord & rec) { // Processes secondary selection from TGLViewer. if (rec.GetN() < 2) return; Int_t id = rec.GetItem(1); Int_t slice = rec.GetItem(2); TEveCaloData::CellData_t cellData; Int_t n = 0; for (TEveCaloData::vCellId_i it =fM->fCellLists[id]->begin(); it!=fM->fCellLists[id]->end(); it++) { if ((*it).fSlice == slice) n++; } printf("Tower selected in slice %d number of hits: %2d \n", slice, n); for (TEveCaloData::vCellId_i it =fM->fCellLists[id]->begin(); it!=fM->fCellLists[id]->end(); it++) { if ((*it).fSlice == slice) { fM->fData->GetCellData(*it, cellData); cellData.Dump(); } } // rho Z if (rec.GetN() == 4) { if(rec.GetItem(3)) printf("Cell in selected positive phi half \n"); else printf("Cell in selected negative phi half \n"); for (TEveCaloData::vCellId_i it = fM->fCellLists[id]->begin(); it != fM->fCellLists[id]->end(); ++it) { fM->fData->GetCellData(*it, cellData); if ((*it).fSlice == slice) { if ((rec.GetItem(3) && cellData.Phi() > 0) || (rec.GetItem(3) == kFALSE && cellData.Phi() < 0)) { cellData.Dump(); } } } } }
Remove debug printout.
Remove debug printout. git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@24216 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,bbannier/ROOT,dawehner/root,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,dawehner/root,bbannier/ROOT,bbannier/ROOT,dawehner/root,dawehner/root,dawehner/root
9bf090abd626fc10c0533eedd39be40e7ce85f26
src/istream/istream_dechunk.cxx
src/istream/istream_dechunk.cxx
/* * This istream filter removes HTTP chunking. * * author: Max Kellermann <[email protected]> */ #include "istream_dechunk.hxx" #include "http/ChunkParser.hxx" #include "FacadeIstream.hxx" #include "pool.hxx" #include <algorithm> #include <glib.h> #include <assert.h> #include <string.h> class DechunkIstream final : public FacadeIstream { HttpChunkParser parser; bool eof = false, closed = false; bool had_input, had_output; /** * Copy chunked data verbatim to handler? * * @see istream_dechunk_check_verbatim() */ bool verbatim = false; /** * Was the end-of-file chunk seen at the end of #pending_verbatim? */ bool eof_verbatim; /** * Number of bytes to be passed to handler verbatim, which have * already been parsed but have not yet been consumed by the * handler. */ size_t pending_verbatim; DechunkHandler &dechunk_handler; public: DechunkIstream(struct pool &p, Istream &_input, DechunkHandler &_dechunk_handler) :FacadeIstream(p, _input), dechunk_handler(_dechunk_handler) { } static DechunkIstream *CheckCast(Istream &i) { return dynamic_cast<DechunkIstream *>(&i); } void SetVerbatim() { verbatim = true; eof_verbatim = false; pending_verbatim = 0; } private: void Abort(GError *error); /** * @return false if the istream_dechunk has been aborted * indirectly (by a callback) */ bool EofDetected(); size_t Feed(const void *data, size_t length); public: /* virtual methods from class Istream */ off_t _GetAvailable(bool partial) override; void _Read() override; void _Close() override; protected: /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override; void OnEof() override; void OnError(GError *error) override; }; void DechunkIstream::Abort(GError *error) { assert(!closed); assert(!parser.HasEnded()); assert(input.IsDefined()); closed = true; input.ClearAndClose(); DestroyError(error); } bool DechunkIstream::EofDetected() { assert(input.IsDefined()); assert(parser.HasEnded()); assert(!eof); eof = true; dechunk_handler.OnDechunkEnd(); assert(input.IsDefined()); assert(parser.HasEnded()); const ScopePoolRef ref(GetPool() TRACE_ARGS); DestroyEof(); if (closed) { assert(!input.IsDefined()); return false; } else { /* we must deinitialize the "input" after emitting "eof", because we must give the callback a chance to call dechunk_input_abort() on us; if we'd clear the handler too early, we wouldn't receive that event, and dechunk_input_data() couldn't change its return value to 0 */ assert(input.IsDefined()); input.ClearHandler(); return true; } } size_t DechunkIstream::Feed(const void *data0, size_t length) { assert(!closed); assert(input.IsDefined()); assert(!verbatim || !eof_verbatim); had_input = true; const auto src_begin = (const char *)data0; const auto src_end = src_begin + length; auto src = src_begin; if (verbatim) /* skip the part that has already been parsed in the last invocation, but could not be consumed by the handler */ src += pending_verbatim; while (src != src_end) { GError *error = nullptr; const ConstBuffer<char> src_remaining(src, src_end - src); auto data = ConstBuffer<char>::FromVoid(parser.Parse(src_remaining.ToVoid(), &error)); if (data.IsNull()) { Abort(error); return 0; } assert(data.data >= src); assert(data.data <= src_end); assert(data.end() <= src_end); src = data.data; if (!data.IsEmpty()) { assert(!parser.HasEnded()); size_t nbytes; if (verbatim) { /* postpone this data chunk; try to send it all later in one big block */ nbytes = data.size; } else { had_output = true; nbytes = InvokeData(src, data.size); assert(nbytes <= data.size); if (nbytes == 0) { if (closed) return 0; else break; } } src += nbytes; bool finished = parser.Consume(nbytes); if (!finished && !verbatim) break; } else if (parser.HasEnded()) { break; } else { assert(src == src_end); } } const size_t position = src - src_begin; if (verbatim && position > 0) { /* send all chunks in one big block */ had_output = true; size_t nbytes = InvokeData(src_begin, position); if (closed) return 0; /* postpone the rest that was not handled; it will not be parsed again */ pending_verbatim = position - nbytes; if (parser.HasEnded()) { if (pending_verbatim > 0) /* not everything could be sent; postpone to next call */ eof_verbatim = true; else if (!EofDetected()) return 0; } return nbytes; } else if (parser.HasEnded() && !EofDetected()) return 0; return position; } /* * istream handler * */ size_t DechunkIstream::OnData(const void *data, size_t length) { assert(!verbatim || length >= pending_verbatim); if (verbatim && eof_verbatim) { /* during the last call, the EOF chunk was parsed, but we could not handle it yet, because the handler did not consume all data yet; try to send the remaining pre-EOF data again and then handle the EOF chunk */ assert(pending_verbatim > 0); assert(length >= pending_verbatim); had_output = true; size_t nbytes = InvokeData(data, pending_verbatim); if (nbytes == 0) return 0; pending_verbatim -= nbytes; if (pending_verbatim > 0) /* more data needed */ return nbytes; return EofDetected() ? nbytes : 0; } const ScopePoolRef ref(GetPool() TRACE_ARGS); return Feed(data, length); } void DechunkIstream::OnEof() { assert(!closed); input.Clear(); closed = true; if (eof) return; GError *error = g_error_new_literal(dechunk_quark(), 0, "premature EOF in dechunker"); DestroyError(error); } void DechunkIstream::OnError(GError *error) { input.Clear(); closed = true; if (eof) g_error_free(error); else DestroyError(error); } /* * istream implementation * */ off_t DechunkIstream::_GetAvailable(bool partial) { if (partial) return (off_t)parser.GetAvailable(); return (off_t)-1; } void DechunkIstream::_Read() { const ScopePoolRef ref(GetPool() TRACE_ARGS); had_output = false; do { had_input = false; input.Read(); } while (input.IsDefined() && had_input && !had_output); } void DechunkIstream::_Close() { assert(!eof); assert(!closed); closed = true; input.ClearAndClose(); Destroy(); } /* * constructor * */ Istream * istream_dechunk_new(struct pool *pool, Istream &input, DechunkHandler &dechunk_handler) { return NewIstream<DechunkIstream>(*pool, input, dechunk_handler); } bool istream_dechunk_check_verbatim(Istream &i) { auto *dechunk = DechunkIstream::CheckCast(i); if (dechunk == nullptr) /* not a DechunkIstream instance */ return false; dechunk->SetVerbatim(); return true; }
/* * This istream filter removes HTTP chunking. * * author: Max Kellermann <[email protected]> */ #include "istream_dechunk.hxx" #include "http/ChunkParser.hxx" #include "FacadeIstream.hxx" #include "pool.hxx" #include <algorithm> #include <glib.h> #include <assert.h> #include <string.h> class DechunkIstream final : public FacadeIstream { HttpChunkParser parser; bool eof = false, closed = false; bool had_input, had_output; /** * Copy chunked data verbatim to handler? * * @see istream_dechunk_check_verbatim() */ bool verbatim = false; /** * Was the end-of-file chunk seen at the end of #pending_verbatim? */ bool eof_verbatim; /** * Number of bytes to be passed to handler verbatim, which have * already been parsed but have not yet been consumed by the * handler. */ size_t pending_verbatim; DechunkHandler &dechunk_handler; public: DechunkIstream(struct pool &p, Istream &_input, DechunkHandler &_dechunk_handler) :FacadeIstream(p, _input), dechunk_handler(_dechunk_handler) { } static DechunkIstream *CheckCast(Istream &i) { return dynamic_cast<DechunkIstream *>(&i); } void SetVerbatim() { verbatim = true; eof_verbatim = false; pending_verbatim = 0; } private: void Abort(GError *error); /** * @return false if the istream_dechunk has been aborted * indirectly (by a callback) */ bool EofDetected(); size_t Feed(const void *data, size_t length); public: /* virtual methods from class Istream */ off_t _GetAvailable(bool partial) override; void _Read() override; void _Close() override; protected: /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override; void OnEof() override; void OnError(GError *error) override; }; void DechunkIstream::Abort(GError *error) { assert(!closed); assert(!parser.HasEnded()); assert(input.IsDefined()); closed = true; input.ClearAndClose(); DestroyError(error); } bool DechunkIstream::EofDetected() { assert(input.IsDefined()); assert(parser.HasEnded()); assert(!eof); eof = true; dechunk_handler.OnDechunkEnd(); assert(input.IsDefined()); assert(parser.HasEnded()); const ScopePoolRef ref(GetPool() TRACE_ARGS); DestroyEof(); if (closed) { assert(!input.IsDefined()); return false; } else { /* we must deinitialize the "input" after emitting "eof", because we must give the callback a chance to call dechunk_input_abort() on us; if we'd clear the handler too early, we wouldn't receive that event, and dechunk_input_data() couldn't change its return value to 0 */ assert(input.IsDefined()); input.ClearHandler(); return true; } } size_t DechunkIstream::Feed(const void *data0, size_t length) { assert(!closed); assert(input.IsDefined()); assert(!verbatim || !eof_verbatim); had_input = true; const auto src_begin = (const char *)data0; const auto src_end = src_begin + length; auto src = src_begin; if (verbatim) /* skip the part that has already been parsed in the last invocation, but could not be consumed by the handler */ src += pending_verbatim; while (src != src_end) { GError *error = nullptr; const ConstBuffer<char> src_remaining(src, src_end - src); auto data = ConstBuffer<char>::FromVoid(parser.Parse(src_remaining.ToVoid(), &error)); if (data.IsNull()) { Abort(error); return 0; } assert(data.data >= src); assert(data.data <= src_end); assert(data.end() <= src_end); src = data.data; if (!data.IsEmpty()) { assert(!parser.HasEnded()); size_t nbytes; if (verbatim) { /* postpone this data chunk; try to send it all later in one big block */ nbytes = data.size; } else { had_output = true; nbytes = InvokeData(src, data.size); assert(nbytes <= data.size); if (nbytes == 0) { if (closed) return 0; else break; } } src += nbytes; bool finished = parser.Consume(nbytes); if (!finished && !verbatim) break; } else if (parser.HasEnded()) { break; } else { assert(src == src_end); } } const size_t position = src - src_begin; if (verbatim && position > 0) { /* send all chunks in one big block */ had_output = true; size_t nbytes = InvokeData(src_begin, position); if (closed) return 0; /* postpone the rest that was not handled; it will not be parsed again */ pending_verbatim = position - nbytes; if (parser.HasEnded()) { if (pending_verbatim > 0) /* not everything could be sent; postpone to next call */ eof_verbatim = true; else if (!EofDetected()) return 0; } return nbytes; } else if (parser.HasEnded() && !EofDetected()) return 0; return position; } /* * istream handler * */ size_t DechunkIstream::OnData(const void *data, size_t length) { assert(!verbatim || length >= pending_verbatim); if (verbatim && eof_verbatim) { /* during the last call, the EOF chunk was parsed, but we could not handle it yet, because the handler did not consume all data yet; try to send the remaining pre-EOF data again and then handle the EOF chunk */ assert(pending_verbatim > 0); assert(length >= pending_verbatim); had_output = true; size_t nbytes = InvokeData(data, pending_verbatim); if (nbytes == 0) return 0; pending_verbatim -= nbytes; if (pending_verbatim > 0) /* more data needed */ return nbytes; return EofDetected() ? nbytes : 0; } const ScopePoolRef ref(GetPool() TRACE_ARGS); return Feed(data, length); } void DechunkIstream::OnEof() { assert(!closed); input.Clear(); closed = true; if (eof) return; GError *error = g_error_new_literal(dechunk_quark(), 0, "premature EOF in dechunker"); DestroyError(error); } void DechunkIstream::OnError(GError *error) { input.Clear(); closed = true; if (eof) g_error_free(error); else DestroyError(error); } /* * istream implementation * */ off_t DechunkIstream::_GetAvailable(bool partial) { if (verbatim) { if (!partial && !eof_verbatim) return -1; return pending_verbatim; } if (partial) return (off_t)parser.GetAvailable(); return (off_t)-1; } void DechunkIstream::_Read() { const ScopePoolRef ref(GetPool() TRACE_ARGS); had_output = false; do { had_input = false; input.Read(); } while (input.IsDefined() && had_input && !had_output); } void DechunkIstream::_Close() { assert(!eof); assert(!closed); closed = true; input.ClearAndClose(); Destroy(); } /* * constructor * */ Istream * istream_dechunk_new(struct pool *pool, Istream &input, DechunkHandler &dechunk_handler) { return NewIstream<DechunkIstream>(*pool, input, dechunk_handler); } bool istream_dechunk_check_verbatim(Istream &i) { auto *dechunk = DechunkIstream::CheckCast(i); if (dechunk == nullptr) /* not a DechunkIstream instance */ return false; dechunk->SetVerbatim(); return true; }
implement _GetAvailable() in verbatim mode
istream/dechunk: implement _GetAvailable() in verbatim mode
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
8fc6edac3ac85603145b89af614151db85cbd8bd
src/booru/page.cc
src/booru/page.cc
#include <glibmm/i18n.h> #include <iostream> #include "page.h" using namespace AhoViewer::Booru; #include "curler.h" #include "image.h" #include "settings.h" Page::Page(Gtk::Menu *menu) : Gtk::ScrolledWindow(), m_PopupMenu(menu), m_ImageFetcher(std::unique_ptr<ImageFetcher>(new ImageFetcher())), m_IconView(Gtk::manage(new Gtk::IconView())), m_Tab(Gtk::manage(new Gtk::EventBox())), m_TabIcon(Gtk::manage(new Gtk::Image(Gtk::Stock::NEW, Gtk::ICON_SIZE_MENU))), m_TabLabel(Gtk::manage(new Gtk::Label(_("New Tab")))), m_TabButton(Gtk::manage(new Gtk::Button())), m_ImageList(std::make_shared<ImageList>(this)), m_Page(0), m_NumPosts(0), m_LastPage(false), m_Saving(false), m_SaveCancel(Gio::Cancellable::create()), m_GetPostsThread(nullptr), m_SaveImagesThread(nullptr) { set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); set_shadow_type(Gtk::SHADOW_ETCHED_IN); // Create page tab {{{ Glib::RefPtr<Gtk::RcStyle> style = m_TabButton->get_modifier_style(); style->set_ythickness(0); style->set_xthickness(0); m_TabButton->modify_style(style); m_TabButton->add(*(Gtk::manage(new Gtk::Image(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_MENU)))); m_TabButton->property_relief() = Gtk::RELIEF_NONE; m_TabButton->set_focus_on_click(false); m_TabButton->set_tooltip_text(_("Close Tab")); m_TabButton->signal_clicked().connect([ this ]() { m_SignalClosed(this); }); m_TabLabel->set_alignment(0.0, 0.5); m_TabLabel->set_ellipsize(Pango::ELLIPSIZE_END); Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); hbox->pack_start(*m_TabIcon, false, false); hbox->pack_start(*m_TabLabel, true, true, 2); hbox->pack_start(*m_TabButton, false, false); hbox->show_all(); m_Tab->set_visible_window(false); m_Tab->add(*hbox); m_Tab->signal_button_release_event().connect(sigc::mem_fun(*this, &Page::on_tab_button_release_event)); // }}} get_vadjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &Page::on_value_changed)); ModelColumns columns; m_ListStore = Gtk::ListStore::create(columns); m_IconView->set_model(m_ListStore); m_IconView->set_selection_mode(Gtk::SELECTION_BROWSE); m_IconView->set_item_width(Image::BooruThumbnailSize - m_IconView->get_margin() - m_IconView->property_item_padding().get_value()); m_IconView->signal_selection_changed().connect(sigc::mem_fun(*this, &Page::on_selection_changed)); m_IconView->signal_button_press_event().connect(sigc::mem_fun(*this, &Page::on_button_press_event)); // Workaround to have fully centered pixbufs Gtk::CellRendererPixbuf *cell = Gtk::manage(new Gtk::CellRendererPixbuf()); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(m_IconView->gobj()), GTK_CELL_RENDERER(cell->gobj()), TRUE); gtk_cell_layout_add_attribute(GTK_CELL_LAYOUT(m_IconView->gobj()), GTK_CELL_RENDERER(cell->gobj()), "pixbuf", 0); m_SignalPostsDownloaded.connect(sigc::mem_fun(*this, &Page::on_posts_downloaded)); m_SignalSaveProgressDisp.connect([ this ]() { m_SignalSaveProgress(m_SaveImagesCurrent, m_SaveImagesTotal); }); add(*m_IconView); show_all(); } Page::~Page() { m_Curler.cancel(); m_CountsCurler.cancel(); if (m_GetPostsThread) { m_GetPostsThread->join(); m_GetPostsThread = nullptr; } cancel_save(); } void Page::set_selected(const size_t index) { get_window()->freeze_updates(); Gtk::TreePath path(std::to_string(index)); m_IconView->select_path(path); scroll_to_selected(); get_window()->thaw_updates(); } void Page::scroll_to_selected() { std::vector<Gtk::TreePath> paths = m_IconView->get_selected_items(); if (!paths.empty()) { Gtk::TreePath path = paths[0]; if (path) m_IconView->scroll_to_path(path, false, 0, 0); } } void Page::search(const std::shared_ptr<Site> &site) { if (!ask_cancel_save()) return; m_Curler.cancel(); m_CountsCurler.cancel(); cancel_save(); m_ImageList->clear(); if (m_GetPostsThread) m_GetPostsThread->join(); m_Site = site; m_Page = 1; m_LastPage = false; std::string tags = m_Tags; // Trim whitespace for the tab label text if (!tags.empty()) { size_t f = tags.find_first_not_of(' '), l = tags.find_last_not_of(' '); tags = f == std::string::npos ? "" : " - " + tags.substr(f, l - f + 1); } m_TabLabel->set_text(site->get_name() + tags); m_TabIcon->set(site->get_icon_pixbuf()); get_posts(); } void Page::save_image(const std::string &path, const std::shared_ptr<Image> &img) { m_SaveCancel->reset(); m_Saving = true; m_SaveImagesThread = Glib::Threads::Thread::create([ this, path, img ]() { img->save(path); m_Saving = false; }); } void Page::save_images(const std::string &path) { m_SaveCancel->reset(); m_Saving = true; m_SaveImagesCurrent = 0; m_SaveImagesTotal = m_ImageList->get_vector_size(); m_SaveImagesThread = Glib::Threads::Thread::create([ this, path ]() { // 2 if cachesize is 0, 8 if cachesize > 2 Glib::ThreadPool pool(std::max(std::min(Settings.get_int("CacheSize") * 4, 8), 2)); for (const std::shared_ptr<AhoViewer::Image> &img : *m_ImageList) { pool.push([ this, path, img ]() { if (m_SaveCancel->is_cancelled()) return; std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->save(Glib::build_filename(path, Glib::path_get_basename(bimage->get_filename()))); ++m_SaveImagesCurrent; if (!m_SaveCancel->is_cancelled()) m_SignalSaveProgressDisp(); }); } pool.shutdown(m_SaveCancel->is_cancelled()); m_Saving = false; }); } /** * Returns true if we want to cancel or we're not saving **/ bool Page::ask_cancel_save() { if (!m_Saving) return true; Gtk::Window *window = static_cast<Gtk::Window*>(get_toplevel()); Gtk::MessageDialog dialog(*window, _("Are you sure that you want to stop saving images?"), false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true); dialog.set_secondary_text(_("Closing this tab will stop the save operation.")); return dialog.run() == Gtk::RESPONSE_YES; } void Page::cancel_save() { m_SaveCancel->cancel(); for (const std::shared_ptr<AhoViewer::Image> &img : *m_ImageList) { std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->cancel_download(); } if (m_SaveImagesThread) { m_SaveImagesThread->join(); m_SaveImagesThread = nullptr; } } void Page::get_posts() { std::string tags(m_Tags); if (m_Tags.find("rating:") == std::string::npos) { if (Settings.get_booru_max_rating() == Site::Rating::SAFE) { tags += " rating:safe"; } else if (Settings.get_booru_max_rating() == Site::Rating::QUESTIONABLE) { tags += " -rating:explicit"; } } tags = m_Curler.escape(tags); m_Curler.set_url(m_Site->get_posts_url(tags, m_Page)); m_GetPostsThread = Glib::Threads::Thread::create([ this, tags ]() { size_t postsCount = 0; // Danbooru doesn't give the post count with the posts // Get it from thier counts api if (m_Page == 1 && m_Site->get_type() == Site::Type::DANBOORU) { m_CountsCurler.set_url(m_Site->get_url() + "/counts/posts.xml?tags=" + tags); if (m_CountsCurler.perform()) { xmlDocument doc(reinterpret_cast<char*>(m_CountsCurler.get_data()), m_CountsCurler.get_data_size()); postsCount = std::stoul(doc.get_children()[0].get_value()); } } if (m_Site->get_type() == Site::Type::GELBOORU) m_Curler.set_cookie_file(m_Site->get_cookie()); else m_Curler.set_http_auth(m_Site->get_username(), m_Site->get_password()); if (m_Curler.perform()) { m_Posts = std::unique_ptr<xmlDocument>( new xmlDocument(reinterpret_cast<char*>(m_Curler.get_data()), m_Curler.get_data_size())); m_NumPosts = m_Posts->get_n_nodes(); if (postsCount) m_Posts->set_attribute("count", std::to_string(postsCount)); } else { m_NumPosts = 0; std::cerr << "Error while downloading posts on " << m_Curler.get_url() << std::endl << " " << m_Curler.get_error() << std::endl; } if (!m_Curler.is_cancelled()) m_SignalPostsDownloaded(); }); } bool Page::get_next_page() { // Do not fetch the next page if this is the last // or the current page is still loading if (m_LastPage || m_GetPostsThread) return false; if (!m_Saving) { ++m_Page; get_posts(); return false; } else if (!m_GetNextPageConn) { m_GetNextPageConn = Glib::signal_timeout().connect(sigc::mem_fun(*this, &Page::get_next_page), 1000); } return true; } /** * Adds the downloaded posts to the image list. **/ void Page::on_posts_downloaded() { if (m_Posts && m_Posts->get_attribute("success") == "false" && !m_Posts->get_attribute("reason").empty()) { m_SignalDownloadError(m_Posts->get_attribute("reason")); } else if (m_NumPosts > 0) { reserve(m_NumPosts); m_ImageList->load(*m_Posts, *this); } else if (m_Page == 1) { m_SignalDownloadError(_("No results found")); } if (m_NumPosts < static_cast<size_t>(Settings.get_int("BooruLimit"))) m_LastPage = true; m_Posts = nullptr; m_GetPostsThread->join(); m_GetPostsThread = nullptr; } void Page::on_selection_changed() { std::vector<Gtk::TreePath> paths = m_IconView->get_selected_items(); if (!paths.empty()) { Gtk::TreePath path = paths[0]; if (path) { size_t index = path[0]; if (index + Settings.get_int("CacheSize") >= m_ImageList->get_vector_size() - 1) get_next_page(); m_SignalSelectedChanged(index); } } } /** * Vertical scrollbar value changed **/ void Page::on_value_changed() { double value = get_vadjustment()->get_value(), limit = get_vadjustment()->get_upper() - get_vadjustment()->get_page_size() - get_vadjustment()->get_step_increment(); if (value >= limit) get_next_page(); } bool Page::on_button_press_event(GdkEventButton *e) { if (e->type == GDK_BUTTON_PRESS && e->button == 3) { Gtk::TreePath path = m_IconView->get_path_at_pos(e->x, e->y); if (path) { m_IconView->select_path(path); m_IconView->scroll_to_path(path, false, 0, 0); m_PopupMenu->popup(e->button, e->time); return true; } } return false; } bool Page::on_tab_button_release_event(GdkEventButton *e) { if (e->type == GDK_BUTTON_RELEASE && e->button == 2) m_SignalClosed(this); return false; }
#include <glibmm/i18n.h> #include <iostream> #include "page.h" using namespace AhoViewer::Booru; #include "curler.h" #include "image.h" #include "settings.h" Page::Page(Gtk::Menu *menu) : Gtk::ScrolledWindow(), m_PopupMenu(menu), m_ImageFetcher(std::unique_ptr<ImageFetcher>(new ImageFetcher())), m_IconView(Gtk::manage(new Gtk::IconView())), m_Tab(Gtk::manage(new Gtk::EventBox())), m_TabIcon(Gtk::manage(new Gtk::Image(Gtk::Stock::NEW, Gtk::ICON_SIZE_MENU))), m_TabLabel(Gtk::manage(new Gtk::Label(_("New Tab")))), m_TabButton(Gtk::manage(new Gtk::Button())), m_ImageList(std::make_shared<ImageList>(this)), m_Page(0), m_NumPosts(0), m_LastPage(false), m_Saving(false), m_SaveCancel(Gio::Cancellable::create()), m_GetPostsThread(nullptr), m_SaveImagesThread(nullptr) { set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); set_shadow_type(Gtk::SHADOW_ETCHED_IN); // Create page tab {{{ Glib::RefPtr<Gtk::RcStyle> style = m_TabButton->get_modifier_style(); style->set_ythickness(0); style->set_xthickness(0); m_TabButton->modify_style(style); m_TabButton->add(*(Gtk::manage(new Gtk::Image(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_MENU)))); m_TabButton->property_relief() = Gtk::RELIEF_NONE; m_TabButton->set_focus_on_click(false); m_TabButton->set_tooltip_text(_("Close Tab")); m_TabButton->signal_clicked().connect([ this ]() { m_SignalClosed(this); }); m_TabLabel->set_alignment(0.0, 0.5); m_TabLabel->set_ellipsize(Pango::ELLIPSIZE_END); Gtk::HBox *hbox = Gtk::manage(new Gtk::HBox()); hbox->pack_start(*m_TabIcon, false, false); hbox->pack_start(*m_TabLabel, true, true, 2); hbox->pack_start(*m_TabButton, false, false); hbox->show_all(); m_Tab->set_visible_window(false); m_Tab->add(*hbox); m_Tab->signal_button_release_event().connect(sigc::mem_fun(*this, &Page::on_tab_button_release_event)); // }}} get_vadjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &Page::on_value_changed)); ModelColumns columns; m_ListStore = Gtk::ListStore::create(columns); m_IconView->set_model(m_ListStore); m_IconView->set_selection_mode(Gtk::SELECTION_BROWSE); m_IconView->set_item_width(Image::BooruThumbnailSize - m_IconView->get_margin() - m_IconView->property_item_padding().get_value()); m_IconView->signal_selection_changed().connect(sigc::mem_fun(*this, &Page::on_selection_changed)); m_IconView->signal_button_press_event().connect(sigc::mem_fun(*this, &Page::on_button_press_event)); // Workaround to have fully centered pixbufs Gtk::CellRendererPixbuf *cell = Gtk::manage(new Gtk::CellRendererPixbuf()); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(m_IconView->gobj()), GTK_CELL_RENDERER(cell->gobj()), TRUE); gtk_cell_layout_add_attribute(GTK_CELL_LAYOUT(m_IconView->gobj()), GTK_CELL_RENDERER(cell->gobj()), "pixbuf", 0); m_SignalPostsDownloaded.connect(sigc::mem_fun(*this, &Page::on_posts_downloaded)); m_SignalSaveProgressDisp.connect([ this ]() { m_SignalSaveProgress(m_SaveImagesCurrent, m_SaveImagesTotal); }); add(*m_IconView); show_all(); } Page::~Page() { m_Curler.cancel(); m_CountsCurler.cancel(); if (m_GetPostsThread) { m_GetPostsThread->join(); m_GetPostsThread = nullptr; } cancel_save(); } void Page::set_selected(const size_t index) { get_window()->freeze_updates(); Gtk::TreePath path(std::to_string(index)); m_IconView->select_path(path); scroll_to_selected(); get_window()->thaw_updates(); } void Page::scroll_to_selected() { std::vector<Gtk::TreePath> paths = m_IconView->get_selected_items(); if (!paths.empty()) { Gtk::TreePath path = paths[0]; if (path) m_IconView->scroll_to_path(path, false, 0, 0); } } void Page::search(const std::shared_ptr<Site> &site) { if (!ask_cancel_save()) return; m_Curler.cancel(); m_CountsCurler.cancel(); cancel_save(); m_ImageList->clear(); if (m_GetPostsThread) m_GetPostsThread->join(); m_Site = site; m_Page = 1; m_LastPage = false; std::string tags = m_Tags; // Trim whitespace for the tab label text if (!tags.empty()) { size_t f = tags.find_first_not_of(' '), l = tags.find_last_not_of(' '); tags = f == std::string::npos ? "" : " - " + tags.substr(f, l - f + 1); } m_TabLabel->set_text(m_Site->get_name() + tags); m_TabIcon->set(m_Site->get_icon_pixbuf()); m_Curler.set_referer(m_Site->get_url()); m_CountsCurler.set_referer(m_Site->get_url()); get_posts(); } void Page::save_image(const std::string &path, const std::shared_ptr<Image> &img) { m_SaveCancel->reset(); m_Saving = true; m_SaveImagesThread = Glib::Threads::Thread::create([ this, path, img ]() { img->save(path); m_Saving = false; }); } void Page::save_images(const std::string &path) { m_SaveCancel->reset(); m_Saving = true; m_SaveImagesCurrent = 0; m_SaveImagesTotal = m_ImageList->get_vector_size(); m_SaveImagesThread = Glib::Threads::Thread::create([ this, path ]() { // 2 if cachesize is 0, 8 if cachesize > 2 Glib::ThreadPool pool(std::max(std::min(Settings.get_int("CacheSize") * 4, 8), 2)); for (const std::shared_ptr<AhoViewer::Image> &img : *m_ImageList) { pool.push([ this, path, img ]() { if (m_SaveCancel->is_cancelled()) return; std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->save(Glib::build_filename(path, Glib::path_get_basename(bimage->get_filename()))); ++m_SaveImagesCurrent; if (!m_SaveCancel->is_cancelled()) m_SignalSaveProgressDisp(); }); } pool.shutdown(m_SaveCancel->is_cancelled()); m_Saving = false; }); } /** * Returns true if we want to cancel or we're not saving **/ bool Page::ask_cancel_save() { if (!m_Saving) return true; Gtk::Window *window = static_cast<Gtk::Window*>(get_toplevel()); Gtk::MessageDialog dialog(*window, _("Are you sure that you want to stop saving images?"), false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true); dialog.set_secondary_text(_("Closing this tab will stop the save operation.")); return dialog.run() == Gtk::RESPONSE_YES; } void Page::cancel_save() { m_SaveCancel->cancel(); for (const std::shared_ptr<AhoViewer::Image> &img : *m_ImageList) { std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->cancel_download(); } if (m_SaveImagesThread) { m_SaveImagesThread->join(); m_SaveImagesThread = nullptr; } } void Page::get_posts() { std::string tags(m_Tags); if (m_Tags.find("rating:") == std::string::npos) { if (Settings.get_booru_max_rating() == Site::Rating::SAFE) { tags += " rating:safe"; } else if (Settings.get_booru_max_rating() == Site::Rating::QUESTIONABLE) { tags += " -rating:explicit"; } } tags = m_Curler.escape(tags); m_Curler.set_url(m_Site->get_posts_url(tags, m_Page)); m_GetPostsThread = Glib::Threads::Thread::create([ this, tags ]() { size_t postsCount = 0; // Danbooru doesn't give the post count with the posts // Get it from thier counts api if (m_Page == 1 && m_Site->get_type() == Site::Type::DANBOORU) { m_CountsCurler.set_url(m_Site->get_url() + "/counts/posts.xml?tags=" + tags); if (m_CountsCurler.perform()) { xmlDocument doc(reinterpret_cast<char*>(m_CountsCurler.get_data()), m_CountsCurler.get_data_size()); postsCount = std::stoul(doc.get_children()[0].get_value()); } } if (m_Site->get_type() == Site::Type::GELBOORU) m_Curler.set_cookie_file(m_Site->get_cookie()); else m_Curler.set_http_auth(m_Site->get_username(), m_Site->get_password()); if (m_Curler.perform()) { m_Posts = std::unique_ptr<xmlDocument>( new xmlDocument(reinterpret_cast<char*>(m_Curler.get_data()), m_Curler.get_data_size())); m_NumPosts = m_Posts->get_n_nodes(); if (postsCount) m_Posts->set_attribute("count", std::to_string(postsCount)); } else { m_NumPosts = 0; std::cerr << "Error while downloading posts on " << m_Curler.get_url() << std::endl << " " << m_Curler.get_error() << std::endl; } if (!m_Curler.is_cancelled()) m_SignalPostsDownloaded(); }); } bool Page::get_next_page() { // Do not fetch the next page if this is the last // or the current page is still loading if (m_LastPage || m_GetPostsThread) return false; if (!m_Saving) { ++m_Page; get_posts(); return false; } else if (!m_GetNextPageConn) { m_GetNextPageConn = Glib::signal_timeout().connect(sigc::mem_fun(*this, &Page::get_next_page), 1000); } return true; } /** * Adds the downloaded posts to the image list. **/ void Page::on_posts_downloaded() { if (m_Posts && m_Posts->get_attribute("success") == "false" && !m_Posts->get_attribute("reason").empty()) { m_SignalDownloadError(m_Posts->get_attribute("reason")); } else if (m_NumPosts > 0) { reserve(m_NumPosts); m_ImageList->load(*m_Posts, *this); } else if (m_Page == 1) { m_SignalDownloadError(_("No results found")); } if (m_NumPosts < static_cast<size_t>(Settings.get_int("BooruLimit"))) m_LastPage = true; m_Posts = nullptr; m_GetPostsThread->join(); m_GetPostsThread = nullptr; } void Page::on_selection_changed() { std::vector<Gtk::TreePath> paths = m_IconView->get_selected_items(); if (!paths.empty()) { Gtk::TreePath path = paths[0]; if (path) { size_t index = path[0]; if (index + Settings.get_int("CacheSize") >= m_ImageList->get_vector_size() - 1) get_next_page(); m_SignalSelectedChanged(index); } } } /** * Vertical scrollbar value changed **/ void Page::on_value_changed() { double value = get_vadjustment()->get_value(), limit = get_vadjustment()->get_upper() - get_vadjustment()->get_page_size() - get_vadjustment()->get_step_increment(); if (value >= limit) get_next_page(); } bool Page::on_button_press_event(GdkEventButton *e) { if (e->type == GDK_BUTTON_PRESS && e->button == 3) { Gtk::TreePath path = m_IconView->get_path_at_pos(e->x, e->y); if (path) { m_IconView->select_path(path); m_IconView->scroll_to_path(path, false, 0, 0); m_PopupMenu->popup(e->button, e->time); return true; } } return false; } bool Page::on_tab_button_release_event(GdkEventButton *e) { if (e->type == GDK_BUTTON_RELEASE && e->button == 2) m_SignalClosed(this); return false; }
Set curl referer when searching
booru/page: Set curl referer when searching
C++
mit
ahodesuka/ahoviewer,ahodesuka/ahoviewer,ahodesuka/ahoviewer
58ac6243bcef94d69268992ab2b064214fad37a3
src/lib/MarbleRunnerManager.cpp
src/lib/MarbleRunnerManager.cpp
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Henry de Valence <[email protected]> // Copyright 2010 Dennis Nienhüser <[email protected]> // Copyright 2011 Thibaut Gridel <[email protected]> #include "MarbleRunnerManager.h" #include "MarblePlacemarkModel.h" #include "MarbleDebug.h" #include "MarbleModel.h" #include "Planet.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "PluginManager.h" #include "RunnerPlugin.h" #include "RunnerTask.h" #include "routing/RouteRequest.h" #include "routing/RoutingProfilesModel.h" #include <QtCore/QObject> #include <QtCore/QString> #include <QtCore/QVector> #include <QtCore/QThreadPool> #include <QtCore/QTimer> namespace Marble { class MarbleModel; class MarbleRunnerManagerPrivate { public: MarbleRunnerManager* q; QString m_lastSearchTerm; QMutex m_modelMutex; MarblePlacemarkModel *m_model; QVector<GeoDataPlacemark*> m_placemarkContainer; QList<GeoDataCoordinates> m_reverseGeocodingResults; QString m_reverseGeocodingResult; QVector<GeoDataDocument*> m_routingResult; GeoDataDocument* m_fileResult; MarbleModel * m_marbleModel; const PluginManager* m_pluginManager; MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager ); ~MarbleRunnerManagerPrivate(); QList<RunnerPlugin*> plugins( RunnerPlugin::Capability capability ); QList<RunnerTask*> m_searchTasks; QList<RunnerTask*> m_reverseTasks; QList<RunnerTask*> m_routingTasks; QList<RunnerTask*> m_parsingTasks; int m_watchdogTimer; void addSearchResult( QVector<GeoDataPlacemark*> result ); void addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark ); void addRoutingResult( GeoDataDocument* route ); void addParsingResult( GeoDataDocument* document, const QString& error = QString() ); void cleanupSearchTask( RunnerTask* task ); void cleanupReverseGeocodingTask( RunnerTask* task ); void cleanupRoutingTask( RunnerTask* task ); void cleanupParsingTask( RunnerTask* task ); }; MarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager ) : q( parent ), m_model( new MarblePlacemarkModel( parent ) ), m_fileResult( 0 ), m_marbleModel( 0 ), m_pluginManager( pluginManager ), m_watchdogTimer( 30000 ) { m_model->setPlacemarkContainer( &m_placemarkContainer ); qRegisterMetaType<GeoDataDocument*>( "GeoDataDocument*" ); qRegisterMetaType<GeoDataPlacemark>( "GeoDataPlacemark" ); qRegisterMetaType<GeoDataCoordinates>( "GeoDataCoordinates" ); qRegisterMetaType<QVector<GeoDataPlacemark*> >( "QVector<GeoDataPlacemark*>" ); } MarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate() { // nothing to do } QList<RunnerPlugin*> MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability ) { QList<RunnerPlugin*> result; QList<RunnerPlugin*> plugins = m_pluginManager->runnerPlugins(); foreach( RunnerPlugin* plugin, plugins ) { if ( !plugin->supports( capability ) ) { continue; } if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) { continue; } if ( !plugin->canWork( capability ) ) { continue; } if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) ) { continue; } result << plugin; } return result; } void MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task ) { m_searchTasks.removeAll( task ); mDebug() << "removing task " << m_searchTasks.size() << " " << (int)task; if ( m_searchTasks.isEmpty() ) { emit q->searchFinished( m_lastSearchTerm ); emit q->placemarkSearchFinished(); } } void MarbleRunnerManagerPrivate::cleanupReverseGeocodingTask( RunnerTask* task ) { m_reverseTasks.removeAll( task ); mDebug() << "removing task " << m_reverseTasks.size() << " " << (int)task; if ( m_reverseTasks.isEmpty() ) { emit q->reverseGeocodingFinished(); } } void MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task ) { m_routingTasks.removeAll( task ); mDebug() << "removing task " << m_routingTasks.size() << " " << (int)task; if ( m_routingTasks.isEmpty() ) { if ( m_routingResult.isEmpty() ) { emit q->routeRetrieved( 0 ); } emit q->routingFinished(); } } void MarbleRunnerManagerPrivate::cleanupParsingTask( RunnerTask* task ) { m_parsingTasks.removeAll( task ); mDebug() << "removing task " << m_parsingTasks.size() << " " << (int)task; if ( m_parsingTasks.isEmpty() ) { emit q->parsingFinished(); } } MarbleRunnerManager::MarbleRunnerManager( const PluginManager* pluginManager, QObject *parent ) : QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) ) { if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) { QThreadPool::globalInstance()->setMaxThreadCount( 4 ); } } MarbleRunnerManager::~MarbleRunnerManager() { delete d; } void MarbleRunnerManager::findPlacemarks( const QString &searchTerm ) { if ( searchTerm == d->m_lastSearchTerm ) { emit searchResultChanged( d->m_model ); emit searchResultChanged( d->m_placemarkContainer ); emit searchFinished( searchTerm ); emit placemarkSearchFinished(); return; } d->m_lastSearchTerm = searchTerm; d->m_searchTasks.clear(); d->m_modelMutex.lock(); d->m_model->removePlacemarks( "MarbleRunnerManager", 0, d->m_placemarkContainer.size() ); qDeleteAll( d->m_placemarkContainer ); d->m_placemarkContainer.clear(); d->m_modelMutex.unlock(); emit searchResultChanged( d->m_model ); if ( searchTerm.trimmed().isEmpty() ) { emit searchFinished( searchTerm ); emit placemarkSearchFinished(); return; } QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Search ); foreach( RunnerPlugin* plugin, plugins ) { MarbleAbstractRunner* runner = plugin->newRunner(); runner->setParent( this ); connect( runner, SIGNAL( searchFinished( QVector<GeoDataPlacemark*> ) ), this, SLOT( addSearchResult( QVector<GeoDataPlacemark*> ) ) ); runner->setModel( d->m_marbleModel ); SearchTask* task = new SearchTask( runner, searchTerm ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) ); d->m_searchTasks << task; mDebug() << "search task " << plugin->nameId() << " " << (int)task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { d->cleanupSearchTask( 0 ); } } void MarbleRunnerManagerPrivate::addSearchResult( QVector<GeoDataPlacemark*> result ) { mDebug() << "Runner reports" << result.size() << " search results"; if( result.isEmpty() ) return; m_modelMutex.lock(); int start = m_placemarkContainer.size(); m_placemarkContainer << result; m_model->addPlacemarks( start, result.size() ); m_modelMutex.unlock(); emit q->searchResultChanged( m_model ); emit q->searchResultChanged( m_placemarkContainer ); } QVector<GeoDataPlacemark*> MarbleRunnerManager::searchPlacemarks( const QString &searchTerm ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(placemarkSearchFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); findPlacemarks( searchTerm ); localEventLoop.exec(); return d->m_placemarkContainer; } void MarbleRunnerManager::setModel( MarbleModel * model ) { // TODO: Terminate runners which are making use of the map. d->m_marbleModel = model; } void MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates ) { d->m_reverseTasks.clear(); d->m_reverseGeocodingResult.clear(); d->m_reverseGeocodingResults.removeAll( coordinates ); QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::ReverseGeocoding ); foreach( RunnerPlugin* plugin, plugins ) { MarbleAbstractRunner* runner = plugin->newRunner(); runner->setParent( this ); connect( runner, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark ) ), this, SLOT( addReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) ); runner->setModel( d->m_marbleModel ); ReverseGeocodingTask* task = new ReverseGeocodingTask( runner, coordinates ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupReverseGeocodingTask(RunnerTask*) ) ); mDebug() << "reverse task " << plugin->nameId() << " " << (int)task; d->m_reverseTasks << task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() ); d->cleanupReverseGeocodingTask( 0 ); } } void MarbleRunnerManagerPrivate::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark ) { if ( !m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) { m_reverseGeocodingResults.push_back( coordinates ); m_reverseGeocodingResult = placemark.address(); emit q->reverseGeocodingFinished( coordinates, placemark ); } } QString MarbleRunnerManager::searchReverseGeocoding( const GeoDataCoordinates &coordinates ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(reverseGeocodingFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); reverseGeocoding( coordinates ); localEventLoop.exec(); return d->m_reverseGeocodingResult; } void MarbleRunnerManager::retrieveRoute( const RouteRequest *request ) { RoutingProfile profile = request->routingProfile(); d->m_routingTasks.clear(); d->m_routingResult.clear(); QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Routing ); foreach( RunnerPlugin* plugin, plugins ) { if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) { continue; } MarbleAbstractRunner* runner = plugin->newRunner(); runner->setParent( this ); connect( runner, SIGNAL( routeCalculated( GeoDataDocument* ) ), this, SLOT( addRoutingResult( GeoDataDocument* ) ) ); runner->setModel( d->m_marbleModel ); RoutingTask* task = new RoutingTask( runner, request ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) ); mDebug() << "route task " << plugin->nameId() << " " << (int)task; d->m_routingTasks << task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { mDebug() << "No routing plugins found, cannot retrieve a route"; d->cleanupRoutingTask( 0 ); } } void MarbleRunnerManagerPrivate::addRoutingResult( GeoDataDocument* route ) { if ( route ) { mDebug() << "route retrieved"; m_routingResult.push_back( route ); emit q->routeRetrieved( route ); } } QVector<GeoDataDocument*> MarbleRunnerManager::searchRoute( const RouteRequest *request ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(routingFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); retrieveRoute( request ); localEventLoop.exec(); return d->m_routingResult; } void MarbleRunnerManager::parseFile( const QString &fileName, DocumentRole role ) { QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Parsing ); foreach( RunnerPlugin *plugin, plugins ) { MarbleAbstractRunner* runner = plugin->newRunner(); connect( runner, SIGNAL( parsingFinished( GeoDataDocument*, QString ) ), this, SLOT( addParsingResult( GeoDataDocument*, QString )) ); ParsingTask *task = new ParsingTask( runner, fileName, role ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupParsingTask(RunnerTask*) ) ); mDebug() << "parse task " << plugin->nameId() << " " << (int)task; d->m_parsingTasks << task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { emit parsingFinished( 0, "No plugin found"); d->cleanupParsingTask( 0 ); } } void MarbleRunnerManagerPrivate::addParsingResult( GeoDataDocument *document, const QString& error ) { if ( document || !error.isEmpty() ) { m_fileResult = document; emit q->parsingFinished( document, error ); } } GeoDataDocument* MarbleRunnerManager::openFile( const QString &fileName, DocumentRole role ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(parsingFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); parseFile( fileName, role); localEventLoop.exec(); return d->m_fileResult; } } #include "MarbleRunnerManager.moc"
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Henry de Valence <[email protected]> // Copyright 2010 Dennis Nienhüser <[email protected]> // Copyright 2011 Thibaut Gridel <[email protected]> #include "MarbleRunnerManager.h" #include "MarblePlacemarkModel.h" #include "MarbleDebug.h" #include "MarbleModel.h" #include "Planet.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "PluginManager.h" #include "RunnerPlugin.h" #include "RunnerTask.h" #include "routing/RouteRequest.h" #include "routing/RoutingProfilesModel.h" #include <QtCore/QObject> #include <QtCore/QString> #include <QtCore/QVector> #include <QtCore/QThreadPool> #include <QtCore/QTimer> namespace Marble { class MarbleModel; class MarbleRunnerManagerPrivate { public: MarbleRunnerManager* q; QString m_lastSearchTerm; QMutex m_modelMutex; MarblePlacemarkModel *m_model; QVector<GeoDataPlacemark*> m_placemarkContainer; QList<GeoDataCoordinates> m_reverseGeocodingResults; QString m_reverseGeocodingResult; QVector<GeoDataDocument*> m_routingResult; GeoDataDocument* m_fileResult; MarbleModel * m_marbleModel; const PluginManager* m_pluginManager; MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager ); ~MarbleRunnerManagerPrivate(); QList<RunnerPlugin*> plugins( RunnerPlugin::Capability capability ); QList<RunnerTask*> m_searchTasks; QList<RunnerTask*> m_reverseTasks; QList<RunnerTask*> m_routingTasks; QList<RunnerTask*> m_parsingTasks; int m_watchdogTimer; void addSearchResult( QVector<GeoDataPlacemark*> result ); void addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark ); void addRoutingResult( GeoDataDocument* route ); void addParsingResult( GeoDataDocument* document, const QString& error = QString() ); void cleanupSearchTask( RunnerTask* task ); void cleanupReverseGeocodingTask( RunnerTask* task ); void cleanupRoutingTask( RunnerTask* task ); void cleanupParsingTask( RunnerTask* task ); }; MarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager ) : q( parent ), m_model( new MarblePlacemarkModel( parent ) ), m_fileResult( 0 ), m_marbleModel( 0 ), m_pluginManager( pluginManager ), m_watchdogTimer( 30000 ) { m_model->setPlacemarkContainer( &m_placemarkContainer ); qRegisterMetaType<GeoDataDocument*>( "GeoDataDocument*" ); qRegisterMetaType<GeoDataPlacemark>( "GeoDataPlacemark" ); qRegisterMetaType<GeoDataCoordinates>( "GeoDataCoordinates" ); qRegisterMetaType<QVector<GeoDataPlacemark*> >( "QVector<GeoDataPlacemark*>" ); } MarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate() { // nothing to do } QList<RunnerPlugin*> MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability ) { QList<RunnerPlugin*> result; QList<RunnerPlugin*> plugins = m_pluginManager->runnerPlugins(); foreach( RunnerPlugin* plugin, plugins ) { if ( !plugin->supports( capability ) ) { continue; } if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) { continue; } if ( !plugin->canWork( capability ) ) { continue; } if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) ) { continue; } result << plugin; } return result; } void MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task ) { m_searchTasks.removeAll( task ); mDebug() << "removing task " << m_searchTasks.size() << " " << (long)task; if ( m_searchTasks.isEmpty() ) { emit q->searchFinished( m_lastSearchTerm ); emit q->placemarkSearchFinished(); } } void MarbleRunnerManagerPrivate::cleanupReverseGeocodingTask( RunnerTask* task ) { m_reverseTasks.removeAll( task ); mDebug() << "removing task " << m_reverseTasks.size() << " " << (long)task; if ( m_reverseTasks.isEmpty() ) { emit q->reverseGeocodingFinished(); } } void MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task ) { m_routingTasks.removeAll( task ); mDebug() << "removing task " << m_routingTasks.size() << " " << (long)task; if ( m_routingTasks.isEmpty() ) { if ( m_routingResult.isEmpty() ) { emit q->routeRetrieved( 0 ); } emit q->routingFinished(); } } void MarbleRunnerManagerPrivate::cleanupParsingTask( RunnerTask* task ) { m_parsingTasks.removeAll( task ); mDebug() << "removing task " << m_parsingTasks.size() << " " << (long)task; if ( m_parsingTasks.isEmpty() ) { emit q->parsingFinished(); } } MarbleRunnerManager::MarbleRunnerManager( const PluginManager* pluginManager, QObject *parent ) : QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) ) { if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) { QThreadPool::globalInstance()->setMaxThreadCount( 4 ); } } MarbleRunnerManager::~MarbleRunnerManager() { delete d; } void MarbleRunnerManager::findPlacemarks( const QString &searchTerm ) { if ( searchTerm == d->m_lastSearchTerm ) { emit searchResultChanged( d->m_model ); emit searchResultChanged( d->m_placemarkContainer ); emit searchFinished( searchTerm ); emit placemarkSearchFinished(); return; } d->m_lastSearchTerm = searchTerm; d->m_searchTasks.clear(); d->m_modelMutex.lock(); d->m_model->removePlacemarks( "MarbleRunnerManager", 0, d->m_placemarkContainer.size() ); qDeleteAll( d->m_placemarkContainer ); d->m_placemarkContainer.clear(); d->m_modelMutex.unlock(); emit searchResultChanged( d->m_model ); if ( searchTerm.trimmed().isEmpty() ) { emit searchFinished( searchTerm ); emit placemarkSearchFinished(); return; } QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Search ); foreach( RunnerPlugin* plugin, plugins ) { MarbleAbstractRunner* runner = plugin->newRunner(); runner->setParent( this ); connect( runner, SIGNAL( searchFinished( QVector<GeoDataPlacemark*> ) ), this, SLOT( addSearchResult( QVector<GeoDataPlacemark*> ) ) ); runner->setModel( d->m_marbleModel ); SearchTask* task = new SearchTask( runner, searchTerm ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) ); d->m_searchTasks << task; mDebug() << "search task " << plugin->nameId() << " " << (long)task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { d->cleanupSearchTask( 0 ); } } void MarbleRunnerManagerPrivate::addSearchResult( QVector<GeoDataPlacemark*> result ) { mDebug() << "Runner reports" << result.size() << " search results"; if( result.isEmpty() ) return; m_modelMutex.lock(); int start = m_placemarkContainer.size(); m_placemarkContainer << result; m_model->addPlacemarks( start, result.size() ); m_modelMutex.unlock(); emit q->searchResultChanged( m_model ); emit q->searchResultChanged( m_placemarkContainer ); } QVector<GeoDataPlacemark*> MarbleRunnerManager::searchPlacemarks( const QString &searchTerm ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(placemarkSearchFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); findPlacemarks( searchTerm ); localEventLoop.exec(); return d->m_placemarkContainer; } void MarbleRunnerManager::setModel( MarbleModel * model ) { // TODO: Terminate runners which are making use of the map. d->m_marbleModel = model; } void MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates ) { d->m_reverseTasks.clear(); d->m_reverseGeocodingResult.clear(); d->m_reverseGeocodingResults.removeAll( coordinates ); QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::ReverseGeocoding ); foreach( RunnerPlugin* plugin, plugins ) { MarbleAbstractRunner* runner = plugin->newRunner(); runner->setParent( this ); connect( runner, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark ) ), this, SLOT( addReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) ); runner->setModel( d->m_marbleModel ); ReverseGeocodingTask* task = new ReverseGeocodingTask( runner, coordinates ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupReverseGeocodingTask(RunnerTask*) ) ); mDebug() << "reverse task " << plugin->nameId() << " " << (long)task; d->m_reverseTasks << task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() ); d->cleanupReverseGeocodingTask( 0 ); } } void MarbleRunnerManagerPrivate::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark ) { if ( !m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) { m_reverseGeocodingResults.push_back( coordinates ); m_reverseGeocodingResult = placemark.address(); emit q->reverseGeocodingFinished( coordinates, placemark ); } } QString MarbleRunnerManager::searchReverseGeocoding( const GeoDataCoordinates &coordinates ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(reverseGeocodingFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); reverseGeocoding( coordinates ); localEventLoop.exec(); return d->m_reverseGeocodingResult; } void MarbleRunnerManager::retrieveRoute( const RouteRequest *request ) { RoutingProfile profile = request->routingProfile(); d->m_routingTasks.clear(); d->m_routingResult.clear(); QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Routing ); foreach( RunnerPlugin* plugin, plugins ) { if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) { continue; } MarbleAbstractRunner* runner = plugin->newRunner(); runner->setParent( this ); connect( runner, SIGNAL( routeCalculated( GeoDataDocument* ) ), this, SLOT( addRoutingResult( GeoDataDocument* ) ) ); runner->setModel( d->m_marbleModel ); RoutingTask* task = new RoutingTask( runner, request ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) ); mDebug() << "route task " << plugin->nameId() << " " << (long)task; d->m_routingTasks << task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { mDebug() << "No routing plugins found, cannot retrieve a route"; d->cleanupRoutingTask( 0 ); } } void MarbleRunnerManagerPrivate::addRoutingResult( GeoDataDocument* route ) { if ( route ) { mDebug() << "route retrieved"; m_routingResult.push_back( route ); emit q->routeRetrieved( route ); } } QVector<GeoDataDocument*> MarbleRunnerManager::searchRoute( const RouteRequest *request ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(routingFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); retrieveRoute( request ); localEventLoop.exec(); return d->m_routingResult; } void MarbleRunnerManager::parseFile( const QString &fileName, DocumentRole role ) { QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Parsing ); foreach( RunnerPlugin *plugin, plugins ) { MarbleAbstractRunner* runner = plugin->newRunner(); connect( runner, SIGNAL( parsingFinished( GeoDataDocument*, QString ) ), this, SLOT( addParsingResult( GeoDataDocument*, QString )) ); ParsingTask *task = new ParsingTask( runner, fileName, role ); connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupParsingTask(RunnerTask*) ) ); mDebug() << "parse task " << plugin->nameId() << " " << (long)task; d->m_parsingTasks << task; QThreadPool::globalInstance()->start( task ); } if ( plugins.isEmpty() ) { emit parsingFinished( 0, "No plugin found"); d->cleanupParsingTask( 0 ); } } void MarbleRunnerManagerPrivate::addParsingResult( GeoDataDocument *document, const QString& error ) { if ( document || !error.isEmpty() ) { m_fileResult = document; emit q->parsingFinished( document, error ); } } GeoDataDocument* MarbleRunnerManager::openFile( const QString &fileName, DocumentRole role ) { QEventLoop localEventLoop; QTimer watchdog; watchdog.setSingleShot(true); connect( &watchdog, SIGNAL(timeout()), &localEventLoop, SLOT(quit())); connect(this, SIGNAL(parsingFinished()), &localEventLoop, SLOT(quit()), Qt::QueuedConnection ); watchdog.start( d->m_watchdogTimer ); parseFile( fileName, role); localEventLoop.exec(); return d->m_fileResult; } } #include "MarbleRunnerManager.moc"
Fix compilation on 64 bit...
Fix compilation on 64 bit...
C++
lgpl-2.1
probonopd/marble,Earthwings/marble,rku/marble,adraghici/marble,probonopd/marble,oberluz/marble,tzapzoor/marble,utkuaydin/marble,oberluz/marble,AndreiDuma/marble,David-Gil/marble-dev,tucnak/marble,rku/marble,tucnak/marble,probonopd/marble,probonopd/marble,adraghici/marble,quannt24/marble,utkuaydin/marble,oberluz/marble,rku/marble,quannt24/marble,AndreiDuma/marble,AndreiDuma/marble,adraghici/marble,adraghici/marble,adraghici/marble,rku/marble,David-Gil/marble-dev,quannt24/marble,quannt24/marble,adraghici/marble,probonopd/marble,Earthwings/marble,rku/marble,David-Gil/marble-dev,AndreiDuma/marble,rku/marble,Earthwings/marble,AndreiDuma/marble,tucnak/marble,utkuaydin/marble,oberluz/marble,tzapzoor/marble,oberluz/marble,David-Gil/marble-dev,tucnak/marble,David-Gil/marble-dev,quannt24/marble,quannt24/marble,utkuaydin/marble,tzapzoor/marble,tzapzoor/marble,tzapzoor/marble,utkuaydin/marble,tzapzoor/marble,quannt24/marble,tucnak/marble,AndreiDuma/marble,tucnak/marble,tzapzoor/marble,oberluz/marble,Earthwings/marble,tucnak/marble,David-Gil/marble-dev,Earthwings/marble,probonopd/marble,Earthwings/marble,utkuaydin/marble,tzapzoor/marble,probonopd/marble
6b83c81572b1c468486c804d5228b68d0cc4e2fb
caffe2/share/contrib/binaries/caffe2_benchmark/caffe2_benchmark.cc
caffe2/share/contrib/binaries/caffe2_benchmark/caffe2_benchmark.cc
#include <fstream> #include <iterator> #include <string> #include "caffe2/core/blob_serialization.h" #include "caffe2/core/init.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/proto/caffe2.pb.h" #include "caffe2/share/contrib/observers/observer_config.h" #include "caffe2/utils/proto_utils.h" #include "caffe2/utils/string_utils.h" #if CAFFE2_MOBILE && (CAFFE2_ANDROID || CAFFE2_IOS) #include "caffe2/mobile/contrib/opengl/core/rewrite_net.h" #endif CAFFE2_DEFINE_string( backend, "default", "The backend to use when running the model. The allowed " "backend choices are: default, nnpack, opengl"); CAFFE2_DEFINE_string( init_net, "", "The given net to initialize any parameters."); CAFFE2_DEFINE_string( input, "", "Input that is needed for running the network. If " "multiple input needed, use comma separated string."); CAFFE2_DEFINE_string( input_dims, "", "Alternate to input_files, if all inputs are simple " "float TensorCPUs, specify the dimension using comma " "separated numbers. If multiple input needed, use " "semicolon to separate the dimension of different " "tensors."); CAFFE2_DEFINE_string( input_file, "", "Input file that contain the serialized protobuf for " "the input blobs. If multiple input needed, use comma " "separated string. Must have the same number of items " "as input does."); CAFFE2_DEFINE_string( input_type, "float", "Input type when specifying the input dimension." "The supported types are float, uint8_t."); CAFFE2_DEFINE_int(iter, 10, "The number of iterations to run."); CAFFE2_DEFINE_string(net, "", "The given net to benchmark."); CAFFE2_DEFINE_string( output, "", "Output that should be dumped after the execution " "finishes. If multiple outputs are needed, use comma " "separated string. If you want to dump everything, pass " "'*' as the output value."); CAFFE2_DEFINE_string( output_folder, "", "The folder that the output should be written to. This " "folder must already exist in the file system."); CAFFE2_DEFINE_bool( run_individual, false, "Whether to benchmark individual operators."); CAFFE2_DEFINE_bool( text_output, false, "Whether to write out output in text format for regression purpose."); CAFFE2_DEFINE_int(warmup, 0, "The number of iterations to warm up."); using std::string; using std::unique_ptr; using std::vector; static void writeTextOutput( caffe2::TensorCPU* tensor, const string& output_prefix, const string& name) { string output_name = output_prefix + "/" + name + ".txt"; caffe2::TensorSerializer<caffe2::CPUContext> ser; caffe2::BlobProto blob_proto; ser.Serialize( *tensor, output_name, blob_proto.mutable_tensor(), 0, tensor->size()); blob_proto.set_name(output_name); blob_proto.set_type("Tensor"); CAFFE_ENFORCE(blob_proto.has_tensor()); caffe2::TensorProto tensor_proto = blob_proto.tensor(); vector<float> data; switch (tensor_proto.data_type()) { case caffe2::TensorProto::FLOAT: { std::copy( tensor_proto.float_data().begin(), tensor_proto.float_data().end(), std::back_inserter(data)); break; } case caffe2::TensorProto::INT32: { std::copy( tensor_proto.int32_data().begin(), tensor_proto.int32_data().end(), std::back_inserter(data)); break; } default: CAFFE_THROW("Unimplemented Blob type."); } std::ofstream output_file(output_name); std::ostream_iterator<float> output_iterator(output_file, "\n"); std::copy(data.begin(), data.end(), output_iterator); } int main(int argc, char** argv) { caffe2::GlobalInit(&argc, &argv); caffe2::ShowLogInfoToStderr(); unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace()); // Run initialization network. caffe2::NetDef init_net_def; CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_init_net, &init_net_def)); CAFFE_ENFORCE(workspace->RunNetOnce(init_net_def)); // Load input. if (caffe2::FLAGS_input.size()) { vector<string> input_names = caffe2::split(',', caffe2::FLAGS_input); if (caffe2::FLAGS_input_file.size()) { vector<string> input_files = caffe2::split(',', caffe2::FLAGS_input_file); CAFFE_ENFORCE_EQ( input_names.size(), input_files.size(), "Input name and file should have the same number."); for (int i = 0; i < input_names.size(); ++i) { caffe2::BlobProto blob_proto; CAFFE_ENFORCE(caffe2::ReadProtoFromFile(input_files[i], &blob_proto)); workspace->CreateBlob(input_names[i])->Deserialize(blob_proto); } } else if (caffe2::FLAGS_input_dims.size()) { vector<string> input_dims_list = caffe2::split(';', caffe2::FLAGS_input_dims); CAFFE_ENFORCE_EQ( input_names.size(), input_dims_list.size(), "Input name and dims should have the same number of items."); for (int i = 0; i < input_names.size(); ++i) { vector<string> input_dims_str = caffe2::split(',', input_dims_list[i]); vector<int> input_dims; for (const string& s : input_dims_str) { input_dims.push_back(caffe2::stoi(s)); } caffe2::TensorCPU* tensor = workspace->GetBlob(input_names[i])->GetMutable<caffe2::TensorCPU>(); tensor->Resize(input_dims); if (caffe2::FLAGS_input_type == "float") { tensor->mutable_data<float>(); } else { CAFFE_ENFORCE( caffe2::FLAGS_input_type == "uint8_t", "Only supported input types are: float, uint8_t"); tensor->mutable_data<uint8_t>(); } } } else { CAFFE_THROW( "You requested input tensors, but neither input_file nor " "input_dims is set."); } } // Run main network. caffe2::NetDef net_def; CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_net, &net_def)); if (caffe2::FLAGS_backend == "opengl") { #if CAFFE2_MOBILE && (CAFFE2_ANDROID || CAFFE2_IOS) caffe2::NetDef opengl_net_def; if (caffe2::tryConvertToOpenGL(init_net_def, net_def, &opengl_net_def)) { net_def = opengl_net_def; if (caffe2::FLAGS_run_individual) { caffe2::FLAGS_run_individual = false; LOG(INFO) << "OpenGL implementation does not support individual operator delay. Run net delay only"; } } else { LOG(ERROR) << "Net cannot be converted to OpenGL format, use original model instead"; } #else LOG(ERROR) << "OpenGL build can only be used in mobile platform"; #endif } else if (caffe2::FLAGS_backend == "nnpack") { for (int i = 0; i < net_def.op_size(); i++) { caffe2::OperatorDef* op_def = net_def.mutable_op(i); op_def->set_engine("NNPACK"); } } else { CAFFE_ENFORCE( caffe2::FLAGS_backend == "default", "Backend is not supported"); } caffe2::NetBase* net = workspace->CreateNet(net_def); CHECK_NOTNULL(net); LOG(INFO) << "Starting benchmark."; caffe2::ObserverConfig::initSampleRate( 1, 1, 1, caffe2::FLAGS_run_individual, caffe2::FLAGS_warmup); LOG(INFO) << "Running warmup runs."; for (int i = 0; i < caffe2::FLAGS_warmup; ++i) { CAFFE_ENFORCE(net->Run(), "Warmup run ", i, " has failed."); } LOG(INFO) << "Main runs."; CAFFE_ENFORCE( caffe2::FLAGS_iter >= 0, "Number of main runs should be non negative, provided ", caffe2::FLAGS_iter, "."); for (int i = 0; i < caffe2::FLAGS_iter; ++i) { caffe2::ObserverConfig::initSampleRate(1, 1, 1, 0, caffe2::FLAGS_warmup); CAFFE_ENFORCE(net->Run(), "Main run ", i, " has failed."); if (caffe2::FLAGS_run_individual) { caffe2::ObserverConfig::initSampleRate(1, 1, 1, 1, caffe2::FLAGS_warmup); CAFFE_ENFORCE(net->Run(), "Main run ", i, " with operator has failed."); } } string output_prefix = caffe2::FLAGS_output_folder.size() ? caffe2::FLAGS_output_folder + "/" : ""; if (caffe2::FLAGS_output.size()) { vector<string> output_names = caffe2::split(',', caffe2::FLAGS_output); if (caffe2::FLAGS_output == "*") { output_names = workspace->Blobs(); } for (const string& name : output_names) { CAFFE_ENFORCE( workspace->HasBlob(name), "You requested a non-existing blob: ", name); if (caffe2::FLAGS_text_output) { auto blob = workspace->GetBlob(name)->GetMutable<caffe2::TensorCPU>(); writeTextOutput(blob, output_prefix, name); } else { string serialized = workspace->GetBlob(name)->Serialize(name); string output_filename = output_prefix + name; caffe2::WriteStringToFile(serialized, output_filename.c_str()); } } } return 0; }
#include <fstream> #include <iterator> #include <string> #include "caffe2/core/blob_serialization.h" #include "caffe2/core/init.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/proto/caffe2.pb.h" #include "caffe2/share/contrib/observers/observer_config.h" #include "caffe2/utils/proto_utils.h" #include "caffe2/utils/string_utils.h" CAFFE2_DEFINE_string( backend, "default", "The backend to use when running the model. The allowed " "backend choices are: default, nnpack"); CAFFE2_DEFINE_string( init_net, "", "The given net to initialize any parameters."); CAFFE2_DEFINE_string( input, "", "Input that is needed for running the network. If " "multiple input needed, use comma separated string."); CAFFE2_DEFINE_string( input_dims, "", "Alternate to input_files, if all inputs are simple " "float TensorCPUs, specify the dimension using comma " "separated numbers. If multiple input needed, use " "semicolon to separate the dimension of different " "tensors."); CAFFE2_DEFINE_string( input_file, "", "Input file that contain the serialized protobuf for " "the input blobs. If multiple input needed, use comma " "separated string. Must have the same number of items " "as input does."); CAFFE2_DEFINE_string( input_type, "float", "Input type when specifying the input dimension." "The supported types are float, uint8_t."); CAFFE2_DEFINE_int(iter, 10, "The number of iterations to run."); CAFFE2_DEFINE_string(net, "", "The given net to benchmark."); CAFFE2_DEFINE_string( output, "", "Output that should be dumped after the execution " "finishes. If multiple outputs are needed, use comma " "separated string. If you want to dump everything, pass " "'*' as the output value."); CAFFE2_DEFINE_string( output_folder, "", "The folder that the output should be written to. This " "folder must already exist in the file system."); CAFFE2_DEFINE_bool( run_individual, false, "Whether to benchmark individual operators."); CAFFE2_DEFINE_bool( text_output, false, "Whether to write out output in text format for regression purpose."); CAFFE2_DEFINE_int(warmup, 0, "The number of iterations to warm up."); using std::string; using std::unique_ptr; using std::vector; static void writeTextOutput( caffe2::TensorCPU* tensor, const string& output_prefix, const string& name) { string output_name = output_prefix + "/" + name + ".txt"; caffe2::TensorSerializer<caffe2::CPUContext> ser; caffe2::BlobProto blob_proto; ser.Serialize( *tensor, output_name, blob_proto.mutable_tensor(), 0, tensor->size()); blob_proto.set_name(output_name); blob_proto.set_type("Tensor"); CAFFE_ENFORCE(blob_proto.has_tensor()); caffe2::TensorProto tensor_proto = blob_proto.tensor(); vector<float> data; switch (tensor_proto.data_type()) { case caffe2::TensorProto::FLOAT: { std::copy( tensor_proto.float_data().begin(), tensor_proto.float_data().end(), std::back_inserter(data)); break; } case caffe2::TensorProto::INT32: { std::copy( tensor_proto.int32_data().begin(), tensor_proto.int32_data().end(), std::back_inserter(data)); break; } default: CAFFE_THROW("Unimplemented Blob type."); } std::ofstream output_file(output_name); std::ostream_iterator<float> output_iterator(output_file, "\n"); std::copy(data.begin(), data.end(), output_iterator); } int main(int argc, char** argv) { caffe2::GlobalInit(&argc, &argv); caffe2::ShowLogInfoToStderr(); unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace()); // Run initialization network. caffe2::NetDef init_net_def; CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_init_net, &init_net_def)); CAFFE_ENFORCE(workspace->RunNetOnce(init_net_def)); // Load input. if (caffe2::FLAGS_input.size()) { vector<string> input_names = caffe2::split(',', caffe2::FLAGS_input); if (caffe2::FLAGS_input_file.size()) { vector<string> input_files = caffe2::split(',', caffe2::FLAGS_input_file); CAFFE_ENFORCE_EQ( input_names.size(), input_files.size(), "Input name and file should have the same number."); for (int i = 0; i < input_names.size(); ++i) { caffe2::BlobProto blob_proto; CAFFE_ENFORCE(caffe2::ReadProtoFromFile(input_files[i], &blob_proto)); workspace->CreateBlob(input_names[i])->Deserialize(blob_proto); } } else if (caffe2::FLAGS_input_dims.size()) { vector<string> input_dims_list = caffe2::split(';', caffe2::FLAGS_input_dims); CAFFE_ENFORCE_EQ( input_names.size(), input_dims_list.size(), "Input name and dims should have the same number of items."); for (int i = 0; i < input_names.size(); ++i) { vector<string> input_dims_str = caffe2::split(',', input_dims_list[i]); vector<int> input_dims; for (const string& s : input_dims_str) { input_dims.push_back(caffe2::stoi(s)); } caffe2::TensorCPU* tensor = workspace->GetBlob(input_names[i])->GetMutable<caffe2::TensorCPU>(); tensor->Resize(input_dims); if (caffe2::FLAGS_input_type == "float") { tensor->mutable_data<float>(); } else { CAFFE_ENFORCE( caffe2::FLAGS_input_type == "uint8_t", "Only supported input types are: float, uint8_t"); tensor->mutable_data<uint8_t>(); } } } else { CAFFE_THROW( "You requested input tensors, but neither input_file nor " "input_dims is set."); } } // Run main network. caffe2::NetDef net_def; CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_net, &net_def)); if (caffe2::FLAGS_backend == "nnpack") { for (int i = 0; i < net_def.op_size(); i++) { caffe2::OperatorDef* op_def = net_def.mutable_op(i); op_def->set_engine("NNPACK"); } } else { CAFFE_ENFORCE( caffe2::FLAGS_backend == "default", "Backend is not supported"); } caffe2::NetBase* net = workspace->CreateNet(net_def); CHECK_NOTNULL(net); LOG(INFO) << "Starting benchmark."; caffe2::ObserverConfig::initSampleRate( 1, 1, 1, caffe2::FLAGS_run_individual, caffe2::FLAGS_warmup); LOG(INFO) << "Running warmup runs."; for (int i = 0; i < caffe2::FLAGS_warmup; ++i) { CAFFE_ENFORCE(net->Run(), "Warmup run ", i, " has failed."); } LOG(INFO) << "Main runs."; CAFFE_ENFORCE( caffe2::FLAGS_iter >= 0, "Number of main runs should be non negative, provided ", caffe2::FLAGS_iter, "."); for (int i = 0; i < caffe2::FLAGS_iter; ++i) { caffe2::ObserverConfig::initSampleRate(1, 1, 1, 0, caffe2::FLAGS_warmup); CAFFE_ENFORCE(net->Run(), "Main run ", i, " has failed."); if (caffe2::FLAGS_run_individual) { caffe2::ObserverConfig::initSampleRate(1, 1, 1, 1, caffe2::FLAGS_warmup); CAFFE_ENFORCE(net->Run(), "Main run ", i, " with operator has failed."); } } string output_prefix = caffe2::FLAGS_output_folder.size() ? caffe2::FLAGS_output_folder + "/" : ""; if (caffe2::FLAGS_output.size()) { vector<string> output_names = caffe2::split(',', caffe2::FLAGS_output); if (caffe2::FLAGS_output == "*") { output_names = workspace->Blobs(); } for (const string& name : output_names) { CAFFE_ENFORCE( workspace->HasBlob(name), "You requested a non-existing blob: ", name); if (caffe2::FLAGS_text_output) { auto blob = workspace->GetBlob(name)->GetMutable<caffe2::TensorCPU>(); writeTextOutput(blob, output_prefix, name); } else { string serialized = workspace->GetBlob(name)->Serialize(name); string output_filename = output_prefix + name; caffe2::WriteStringToFile(serialized, output_filename.c_str()); } } } return 0; }
Remove OpenGL code from benchmark
Remove OpenGL code from benchmark Summary: OpenGL is no longer built by default. Even after setting flag -DUSE_MOBILE_OPENGL, the build fails. Remove it in the benchmark code so that the benchmark can still be built. Closes https://github.com/caffe2/caffe2/pull/1822 Reviewed By: Maratyszcza Differential Revision: D6824777 Pulled By: sf-wind fbshipit-source-id: 5af8b669a36adcd6a98b0a11237b9e03c146bb9d
C++
apache-2.0
Yangqing/caffe2,xzturn/caffe2,xzturn/caffe2,xzturn/caffe2,xzturn/caffe2,xzturn/caffe2,Yangqing/caffe2,caffe2/caffe2,Yangqing/caffe2,Yangqing/caffe2,Yangqing/caffe2
cbdd8c4311e7827b2d31199b128a3b94574e724e
test_compile/compile_dyn_dbn.cpp
test_compile/compile_dyn_dbn.cpp
//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll/dyn_dbn.hpp" #include "dll/ocv_visualizer.hpp" template<typename DBN> void test_dbn(DBN& dbn){ dbn->display(); std::vector<etl::dyn_vector<double>> images; dbn->pretrain(images, 10); } int main(){ using dbn_t = dll::dyn_dbn_desc< dll::dbn_dyn_layers< dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t, dll::dyn_rbm_desc<dll::momentum>::rbm_t, dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t >, dll::watcher<dll::opencv_dbn_visualizer> >::dbn_t; auto dbn = std::make_unique<dbn_t>( std::make_tuple(28*28,100), std::make_tuple(100,200), std::make_tuple(200,10)); test_dbn(dbn); return 0; }
//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll/dyn_dbn.hpp" #include "dll/ocv_visualizer.hpp" template<typename DBN> void test_dbn(DBN& dbn){ dbn->display(); std::vector<etl::dyn_vector<double>> images; dbn->pretrain(images, 10); } int main(){ using dbn_t = dll::dyn_dbn_desc< dll::dbn_layers< dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t, dll::dyn_rbm_desc<dll::momentum>::rbm_t, dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t >, dll::watcher<dll::opencv_dbn_visualizer> >::dbn_t; auto dbn = std::make_unique<dbn_t>( std::make_tuple(28*28,100), std::make_tuple(100,200), std::make_tuple(200,10)); test_dbn(dbn); return 0; }
Update test case
Update test case
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
9c5692df4e6f574930c25fcbde796f427ca31043
chrome/renderer/extensions/extension_api_json_validity_unittest.cc
chrome/renderer/extensions/extension_api_json_validity_unittest.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "chrome/common/json_value_serializer.h" #include "chrome/common/chrome_paths.h" #include "chrome/renderer/extensions/bindings_utils.h" #include "chrome/test/v8_unit_test.h" #include "grit/common_resources.h" #include "testing/gtest/include/gtest/gtest.h" namespace { // Given a ListValue* of dictionaries, find the first dictionary with // a property |property| whose string value is |expected_value|. The // following conditions result in a return value of false, and an // explanation in |out_error_message|: // * Any list element is not a dictionary. // * Any list element does not have a string property |property|. // * More than one list element has a string property with value // |expected_value|. // // Return true and set |out_matching_dict| if such a dictionary was // found. If false is returned, |out_message| is set to an explanation. bool FindDictionaryWithProperyValue(ListValue* list, const std::string& property, const std::string& expected_value, DictionaryValue** out_matching_dict, std::string* out_error_message) { bool found = false; for (ListValue::const_iterator it = list->begin(); it != list->end(); ++it) { if (!(*it)->IsType(Value::TYPE_DICTIONARY)) { *out_error_message = "List contains an item taht is not a dictionary."; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(*it); std::string actual_value; if (!dict->GetStringASCII(property, &actual_value)) { *out_error_message = "Dictionary has no string property \'" + property + "'."; return false; } if (actual_value != expected_value) continue; if (found) { *out_error_message = "More than one dictionary matches."; return false; } found = true; if (out_matching_dict) *out_matching_dict = dict; } if (!found) { *out_error_message = "No dictionary matches."; return false; } return true; } } class ExtensionApiJsonValidityTest : public V8UnitTest { }; // Read extension_api.json with JSONFileValueSerializer. This test checks // that the file is valid without using V8 or grit generated code. // Unlike V8's JSON.Parse(), it produces easy to read error messages. // If this test passes, and ExtensionApiJsonValidityTest.WithV8 fails, // check to see if V8 or the grit build step is broken. TEST_F(ExtensionApiJsonValidityTest, Basic) { // Build the path to extension_api.json, and check that the file exists. FilePath extension_api_json; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &extension_api_json)); extension_api_json = extension_api_json.AppendASCII("chrome") .AppendASCII("common") .AppendASCII("extensions") .AppendASCII("api") .AppendASCII("extension_api.json"); ASSERT_TRUE(file_util::PathExists(extension_api_json)) << "Failed to find file 'extension_api.json' at the following path: " << extension_api_json.value(); std::string error_message; // Check that extension_api.json can be parsed as JSON. JSONFileValueSerializer serializer(extension_api_json); scoped_ptr<Value> root(serializer.Deserialize(NULL, &error_message)); ASSERT_TRUE(root.get()) << error_message; ASSERT_EQ(Value::TYPE_LIST, root->GetType()); ListValue* root_list = static_cast<ListValue*>(root.get()); // As a basic smoke test that the JSON we read is reasonable, find the // definition of the functions chrome.test.log() and // chrome.test.notifyPass(). DictionaryValue* test_namespace_dict; ASSERT_TRUE(FindDictionaryWithProperyValue( root_list, "namespace", "test", &test_namespace_dict, &error_message)) << error_message; ListValue* functions_list; ASSERT_TRUE(test_namespace_dict->GetList(L"functions", &functions_list)) << "Namespace 'test' should define some functions."; EXPECT_TRUE(FindDictionaryWithProperyValue( functions_list, "name", "log", NULL, &error_message)) << error_message; EXPECT_TRUE(FindDictionaryWithProperyValue( functions_list, "name", "notifyPass", NULL, &error_message)) << error_message; } // Use V8 to load the string resource version of extension_api.json . // This test mimics the method extension_api.json is loaded in // chrome/renderer/resources/extension_process_bindings.js . TEST_F(ExtensionApiJsonValidityTest, WithV8) { std::string ext_api_string = bindings_utils::GetStringResource<IDR_EXTENSION_API_JSON>(); // Create a global variable holding the text of extension_api.json . SetGlobalStringVar("ext_api_json_text", ext_api_string); // Parse the text of extension_api.json . If there is a parse error, // an exception will be printed that includes a line number. std::string test_js = "var extension_api = JSON.parse(ext_api_json_text);"; ExecuteScriptInContext(test_js, "ParseExtensionApiJson"); }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "chrome/common/json_value_serializer.h" #include "chrome/common/chrome_paths.h" #include "chrome/renderer/extensions/bindings_utils.h" #include "chrome/test/v8_unit_test.h" #include "grit/common_resources.h" #include "testing/gtest/include/gtest/gtest.h" namespace { // Given a ListValue* of dictionaries, find the first dictionary with // a property |property| whose string value is |expected_value|. The // following conditions result in a return value of false, and an // explanation in |out_error_message|: // * Any list element is not a dictionary. // * Any list element does not have a string property |property|. // * More than one list element has a string property with value // |expected_value|. // // Return true and set |out_matching_dict| if such a dictionary was // found. If false is returned, |out_message| is set to an explanation. bool FindDictionaryWithProperyValue(ListValue* list, const std::string& property, const std::string& expected_value, DictionaryValue** out_matching_dict, std::string* out_error_message) { bool found = false; for (ListValue::const_iterator it = list->begin(); it != list->end(); ++it) { if (!(*it)->IsType(Value::TYPE_DICTIONARY)) { *out_error_message = "List contains an item taht is not a dictionary."; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(*it); std::string actual_value; if (!dict->GetStringASCII(property, &actual_value)) { *out_error_message = "Dictionary has no string property \'" + property + "'."; return false; } if (actual_value != expected_value) continue; if (found) { *out_error_message = "More than one dictionary matches."; return false; } found = true; if (out_matching_dict) *out_matching_dict = dict; } if (!found) { *out_error_message = "No dictionary matches."; return false; } return true; } } class ExtensionApiJsonValidityTest : public V8UnitTest { }; // Read extension_api.json with JSONFileValueSerializer. This test checks // that the file is valid without using V8 or grit generated code. // Unlike V8's JSON.Parse(), it produces easy to read error messages. // If this test passes, and ExtensionApiJsonValidityTest.WithV8 fails, // check to see if V8 or the grit build step is broken. TEST_F(ExtensionApiJsonValidityTest, Basic) { // Build the path to extension_api.json, and check that the file exists. FilePath extension_api_json; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &extension_api_json)); extension_api_json = extension_api_json.AppendASCII("chrome") .AppendASCII("common") .AppendASCII("extensions") .AppendASCII("api") .AppendASCII("extension_api.json"); ASSERT_TRUE(file_util::PathExists(extension_api_json)) << "Failed to find file 'extension_api.json' at the following path: " << extension_api_json.value(); std::string error_message; // Check that extension_api.json can be parsed as JSON. JSONFileValueSerializer serializer(extension_api_json); scoped_ptr<Value> root(serializer.Deserialize(NULL, &error_message)); ASSERT_TRUE(root.get()) << error_message; ASSERT_EQ(Value::TYPE_LIST, root->GetType()); ListValue* root_list = static_cast<ListValue*>(root.get()); // As a basic smoke test that the JSON we read is reasonable, find the // definition of the functions chrome.test.log() and // chrome.test.notifyPass(). DictionaryValue* test_namespace_dict; ASSERT_TRUE(FindDictionaryWithProperyValue( root_list, "namespace", "test", &test_namespace_dict, &error_message)) << error_message; ListValue* functions_list; ASSERT_TRUE(test_namespace_dict->GetList(L"functions", &functions_list)) << "Namespace 'test' should define some functions."; EXPECT_TRUE(FindDictionaryWithProperyValue( functions_list, "name", "log", NULL, &error_message)) << error_message; EXPECT_TRUE(FindDictionaryWithProperyValue( functions_list, "name", "notifyPass", NULL, &error_message)) << error_message; } #if defined(OS_WIN) #define MAYBE_WithV8 DISABLED_WithV8 #else #define MAYBE_WithV8 WithV8 #endif // Use V8 to load the string resource version of extension_api.json . // This test mimics the method extension_api.json is loaded in // chrome/renderer/resources/extension_process_bindings.js . TEST_F(ExtensionApiJsonValidityTest, MAYBE_WithV8) { std::string ext_api_string = bindings_utils::GetStringResource<IDR_EXTENSION_API_JSON>(); // Create a global variable holding the text of extension_api.json . SetGlobalStringVar("ext_api_json_text", ext_api_string); // Parse the text of extension_api.json . If there is a parse error, // an exception will be printed that includes a line number. std::string test_js = "var extension_api = JSON.parse(ext_api_json_text);"; ExecuteScriptInContext(test_js, "ParseExtensionApiJson"); }
Disable ExtensionApiJsonValidityTest.WithV8 under windows.
Disable ExtensionApiJsonValidityTest.WithV8 under windows. ExtensionApiJsonValidityTest.WithV8 sometimes crashes under Vista. TBR=sgjesse TEST=less crashyness, more happiness BUG=43855 Review URL: http://codereview.chromium.org/1985013 git-svn-id: http://src.chromium.org/svn/trunk/src@46908 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 3bf065b2fd31ba5f0c93426024f5292372832a76
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
f44686b4f5a7e5b3111eb04761247143e0aa30d9
test/server/admin/admin_test.cc
test/server/admin/admin_test.cc
#include <algorithm> #include <fstream> #include <memory> #include <regex> #include <vector> #include "envoy/json/json_object.h" #include "envoy/upstream/outlier_detection.h" #include "envoy/upstream/upstream.h" #include "common/access_log/access_log_impl.h" #include "common/http/message_impl.h" #include "common/json/json_loader.h" #include "common/protobuf/protobuf.h" #include "common/protobuf/utility.h" #include "common/upstream/upstream_impl.h" #include "extensions/access_loggers/common/file_access_log_impl.h" #include "test/server/admin/admin_instance.h" #include "test/test_common/logging.h" #include "test/test_common/printers.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::HasSubstr; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::ReturnPointee; using testing::ReturnRef; namespace Envoy { namespace Server { INSTANTIATE_TEST_SUITE_P(IpVersions, AdminInstanceTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(AdminInstanceTest, MutatesErrorWithGet) { Buffer::OwnedImpl data; Http::TestResponseHeaderMapImpl header_map; const std::string path("/healthcheck/fail"); // TODO(jmarantz): the call to getCallback should be made to fail, but as an interim we will // just issue a warning, so that scripts using curl GET commands to mutate state can be fixed. EXPECT_LOG_CONTAINS("error", "admin path \"" + path + "\" mutates state, method=GET rather than POST", EXPECT_EQ(Http::Code::MethodNotAllowed, getCallback(path, header_map, data))); } TEST_P(AdminInstanceTest, WriteAddressToFile) { std::ifstream address_file(address_out_path_); std::string address_from_file; std::getline(address_file, address_from_file); EXPECT_EQ(admin_.socket().addressProvider().localAddress()->asString(), address_from_file); } TEST_P(AdminInstanceTest, AdminBadAddressOutPath) { std::string bad_path = TestEnvironment::temporaryPath("some/unlikely/bad/path/admin.address"); AdminImpl admin_bad_address_out_path(cpu_profile_path_, server_); std::list<AccessLog::InstanceSharedPtr> access_logs; Filesystem::FilePathAndType file_info{Filesystem::DestinationType::File, "/dev/null"}; access_logs.emplace_back(new Extensions::AccessLoggers::File::FileAccessLog( file_info, {}, Formatter::SubstitutionFormatUtils::defaultSubstitutionFormatter(), server_.accessLogManager())); EXPECT_LOG_CONTAINS( "critical", "cannot open admin address output file " + bad_path + " for writing.", admin_bad_address_out_path.startHttpListener( access_logs, bad_path, Network::Test::getCanonicalLoopbackAddress(GetParam()), nullptr, listener_scope_.createScope("listener.admin."))); EXPECT_FALSE(std::ifstream(bad_path)); } TEST_P(AdminInstanceTest, CustomHandler) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; // Test removable handler. EXPECT_NO_LOGS(EXPECT_TRUE(admin_.addHandler("/foo/bar", "hello", callback, true, false))); Http::TestResponseHeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); // Test that removable handler gets removed. EXPECT_TRUE(admin_.removeHandler("/foo/bar")); EXPECT_EQ(Http::Code::NotFound, getCallback("/foo/bar", header_map, response)); EXPECT_FALSE(admin_.removeHandler("/foo/bar")); // Add non removable handler. EXPECT_TRUE(admin_.addHandler("/foo/bar", "hello", callback, false, false)); EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); // Add again and make sure it is not there twice. EXPECT_FALSE(admin_.addHandler("/foo/bar", "hello", callback, false, false)); // Try to remove non removable handler, and make sure it is not removed. EXPECT_FALSE(admin_.removeHandler("/foo/bar")); EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); } TEST_P(AdminInstanceTest, RejectHandlerWithXss) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; EXPECT_LOG_CONTAINS("error", "filter \"/foo<script>alert('hi')</script>\" contains invalid character '<'", EXPECT_FALSE(admin_.addHandler("/foo<script>alert('hi')</script>", "hello", callback, true, false))); } TEST_P(AdminInstanceTest, RejectHandlerWithEmbeddedQuery) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; EXPECT_LOG_CONTAINS("error", "filter \"/bar?queryShouldNotBeInPrefix\" contains invalid character '?'", EXPECT_FALSE(admin_.addHandler("/bar?queryShouldNotBeInPrefix", "hello", callback, true, false))); } TEST_P(AdminInstanceTest, EscapeHelpTextWithPunctuation) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; // It's OK to have help text with HTML characters in it, but when we render the home // page they need to be escaped. const std::string planets = "jupiter>saturn>mars"; EXPECT_TRUE(admin_.addHandler("/planets", planets, callback, true, false)); Http::TestResponseHeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::OK, getCallback("/", header_map, response)); const Http::HeaderString& content_type = header_map.ContentType()->value(); EXPECT_THAT(std::string(content_type.getStringView()), testing::HasSubstr("text/html")); EXPECT_EQ(-1, response.search(planets.data(), planets.size(), 0, 0)); const std::string escaped_planets = "jupiter&gt;saturn&gt;mars"; EXPECT_NE(-1, response.search(escaped_planets.data(), escaped_planets.size(), 0, 0)); } TEST_P(AdminInstanceTest, HelpUsesFormForMutations) { Http::TestResponseHeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::OK, getCallback("/", header_map, response)); const std::string logging_action = "<form action='logging' method='post'"; const std::string stats_href = "<a href='stats'"; EXPECT_NE(-1, response.search(logging_action.data(), logging_action.size(), 0, 0)); EXPECT_NE(-1, response.search(stats_href.data(), stats_href.size(), 0, 0)); } } // namespace Server } // namespace Envoy
#include <algorithm> #include <fstream> #include <memory> #include <regex> #include <vector> #include "envoy/json/json_object.h" #include "envoy/upstream/outlier_detection.h" #include "envoy/upstream/upstream.h" #include "common/access_log/access_log_impl.h" #include "common/http/message_impl.h" #include "common/json/json_loader.h" #include "common/protobuf/protobuf.h" #include "common/protobuf/utility.h" #include "common/upstream/upstream_impl.h" #include "extensions/access_loggers/common/file_access_log_impl.h" #include "test/server/admin/admin_instance.h" #include "test/test_common/logging.h" #include "test/test_common/printers.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::HasSubstr; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::ReturnPointee; using testing::ReturnRef; namespace Envoy { namespace Server { INSTANTIATE_TEST_SUITE_P(IpVersions, AdminInstanceTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(AdminInstanceTest, MutatesErrorWithGet) { Buffer::OwnedImpl data; Http::TestResponseHeaderMapImpl header_map; const std::string path("/healthcheck/fail"); // TODO(jmarantz): the call to getCallback should be made to fail, but as an interim we will // just issue a warning, so that scripts using curl GET commands to mutate state can be fixed. EXPECT_LOG_CONTAINS("error", "admin path \"" + path + "\" mutates state, method=GET rather than POST", EXPECT_EQ(Http::Code::MethodNotAllowed, getCallback(path, header_map, data))); } TEST_P(AdminInstanceTest, Getters) { EXPECT_EQ(&admin_.mutableSocket(), &admin_.socket()); EXPECT_EQ(1, admin_.concurrency()); EXPECT_EQ(false, admin_.preserveExternalRequestId()); EXPECT_EQ(nullptr, admin_.tracer()); EXPECT_EQ(false, admin_.streamErrorOnInvalidHttpMessaging()); } TEST_P(AdminInstanceTest, WriteAddressToFile) { std::ifstream address_file(address_out_path_); std::string address_from_file; std::getline(address_file, address_from_file); EXPECT_EQ(admin_.socket().addressProvider().localAddress()->asString(), address_from_file); } TEST_P(AdminInstanceTest, AdminBadAddressOutPath) { std::string bad_path = TestEnvironment::temporaryPath("some/unlikely/bad/path/admin.address"); AdminImpl admin_bad_address_out_path(cpu_profile_path_, server_); std::list<AccessLog::InstanceSharedPtr> access_logs; Filesystem::FilePathAndType file_info{Filesystem::DestinationType::File, "/dev/null"}; access_logs.emplace_back(new Extensions::AccessLoggers::File::FileAccessLog( file_info, {}, Formatter::SubstitutionFormatUtils::defaultSubstitutionFormatter(), server_.accessLogManager())); EXPECT_LOG_CONTAINS( "critical", "cannot open admin address output file " + bad_path + " for writing.", admin_bad_address_out_path.startHttpListener( access_logs, bad_path, Network::Test::getCanonicalLoopbackAddress(GetParam()), nullptr, listener_scope_.createScope("listener.admin."))); EXPECT_FALSE(std::ifstream(bad_path)); } TEST_P(AdminInstanceTest, CustomHandler) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; // Test removable handler. EXPECT_NO_LOGS(EXPECT_TRUE(admin_.addHandler("/foo/bar", "hello", callback, true, false))); Http::TestResponseHeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); // Test that removable handler gets removed. EXPECT_TRUE(admin_.removeHandler("/foo/bar")); EXPECT_EQ(Http::Code::NotFound, getCallback("/foo/bar", header_map, response)); EXPECT_FALSE(admin_.removeHandler("/foo/bar")); // Add non removable handler. EXPECT_TRUE(admin_.addHandler("/foo/bar", "hello", callback, false, false)); EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); // Add again and make sure it is not there twice. EXPECT_FALSE(admin_.addHandler("/foo/bar", "hello", callback, false, false)); // Try to remove non removable handler, and make sure it is not removed. EXPECT_FALSE(admin_.removeHandler("/foo/bar")); EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); } TEST_P(AdminInstanceTest, RejectHandlerWithXss) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; EXPECT_LOG_CONTAINS("error", "filter \"/foo<script>alert('hi')</script>\" contains invalid character '<'", EXPECT_FALSE(admin_.addHandler("/foo<script>alert('hi')</script>", "hello", callback, true, false))); } TEST_P(AdminInstanceTest, RejectHandlerWithEmbeddedQuery) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; EXPECT_LOG_CONTAINS("error", "filter \"/bar?queryShouldNotBeInPrefix\" contains invalid character '?'", EXPECT_FALSE(admin_.addHandler("/bar?queryShouldNotBeInPrefix", "hello", callback, true, false))); } TEST_P(AdminInstanceTest, EscapeHelpTextWithPunctuation) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; // It's OK to have help text with HTML characters in it, but when we render the home // page they need to be escaped. const std::string planets = "jupiter>saturn>mars"; EXPECT_TRUE(admin_.addHandler("/planets", planets, callback, true, false)); Http::TestResponseHeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::OK, getCallback("/", header_map, response)); const Http::HeaderString& content_type = header_map.ContentType()->value(); EXPECT_THAT(std::string(content_type.getStringView()), testing::HasSubstr("text/html")); EXPECT_EQ(-1, response.search(planets.data(), planets.size(), 0, 0)); const std::string escaped_planets = "jupiter&gt;saturn&gt;mars"; EXPECT_NE(-1, response.search(escaped_planets.data(), escaped_planets.size(), 0, 0)); } TEST_P(AdminInstanceTest, HelpUsesFormForMutations) { Http::TestResponseHeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::OK, getCallback("/", header_map, response)); const std::string logging_action = "<form action='logging' method='post'"; const std::string stats_href = "<a href='stats'"; EXPECT_NE(-1, response.search(logging_action.data(), logging_action.size(), 0, 0)); EXPECT_NE(-1, response.search(stats_href.data(), stats_href.size(), 0, 0)); } } // namespace Server } // namespace Envoy
increase coverage of simple getters (#15816)
admin: increase coverage of simple getters (#15816) Signed-off-by: Snow Pettersen <[email protected]>
C++
apache-2.0
lyft/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,lyft/envoy
5ac26aca5ac009d061a5f8e2c8ef12545f8da3dc
libraries/chain/wasm_eosio_constraints.cpp
libraries/chain/wasm_eosio_constraints.cpp
#include <eosio/chain/wasm_eosio_constraints.hpp> #include <fc/exception/exception.hpp> #include <eosio/chain/exceptions.hpp> #include "IR/Module.h" #include "IR/Operators.h" namespace eosio { namespace chain { using namespace IR; struct nop_opcode_visitor { typedef void Result; #define VISIT_OPCODE(opcode,name,nameString,Imm,...) \ virtual void name(Imm) {} ENUM_OPERATORS(VISIT_OPCODE) #undef VISIT_OPCODE void unknown(Opcode) { FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract encountered unknown opcode"); } }; struct eosio_constraints_visitor : public nop_opcode_visitor { ///Make this some sort of visitor enum to reduce chance of copy pasta errors (but // the override declaration makes it somewhat safe) //While it's possible to access beyond 1MiB by giving an offset that's 1KiB-1 and // an 8 byte data type, that's fine. There will be enough of a guard on the end // of 1MiB where it's not a problem void fail_large_offset(U32 offset) { if(offset >= 1024*1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract used an invalid large memory store/load offset"); } void i32_load (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i64_load (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } void i32_load8_s (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i32_load8_u (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i32_load16_s (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i32_load16_u (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_load8_s (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i64_load8_u (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i64_load16_s (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_load16_u (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_load32_s (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i64_load32_u (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i32_store (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i64_store (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } void i32_store8 (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i32_store16 (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_store8 (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i64_store16 (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_store32 (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void f32_load (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void f64_load (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } void f32_store (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void f64_store (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } #define VISIT_OPCODE(opcode,name,nameString,Imm,...) \ void name(Imm) override { FC_THROW_EXCEPTION(wasm_execution_error, "Smart contracts may not use WASM memory operators"); } ENUM_MEMORY_OPERATORS(VISIT_OPCODE); #undef VISIT_OPCODE }; void validate_eosio_wasm_constraints(const Module& m) { if(m.memories.defs.size() && m.memories.defs[0].type.size.min > 16) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract initial memory size must be less than or equal to 1MiB"); for(const DataSegment& ds : m.dataSegments) { if(ds.baseOffset.type != InitializerExpression::Type::i32_const) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract has unexpected memory base offset type"); if(static_cast<uint32_t>(ds.baseOffset.i32) + ds.data.size() > 64*1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract data segments must lie in first 64KiB"); } if(m.tables.defs.size() && m.tables.defs[0].type.size.min > 1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract table limited to 1024 elements"); unsigned mutable_globals_total_size = 0; for(const GlobalDef& global_def : m.globals.defs) { if(!global_def.type.isMutable) continue; switch(global_def.type.valueType) { case ValueType::any: case ValueType::num: FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract has unexpected global definition value type"); case ValueType::i64: case ValueType::f64: mutable_globals_total_size += 4; case ValueType::i32: case ValueType::f32: mutable_globals_total_size += 4; } } if(mutable_globals_total_size > 1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract has more than 1KiB of mutable globals"); //Some of the OperatorDecoderStream users inside of WAVM track the control stack and quit parsing from // OperatorDecoderStream when the control stack is empty (since that would indicate unreachable code). // Not doing that here, yet, since it's not clear it's required for the purpose of the validation eosio_constraints_visitor visitor; for(const FunctionDef& fd : m.functions.defs) { OperatorDecoderStream decoder(fd.code); while(decoder) { decoder.decodeOp(visitor); } } } }}
#include <eosio/chain/wasm_eosio_constraints.hpp> #include <fc/exception/exception.hpp> #include <eosio/chain/exceptions.hpp> #include "IR/Module.h" #include "IR/Operators.h" namespace eosio { namespace chain { using namespace IR; struct nop_opcode_visitor { typedef void Result; #define VISIT_OPCODE(opcode,name,nameString,Imm,...) \ virtual void name(Imm) {} ENUM_OPERATORS(VISIT_OPCODE) #undef VISIT_OPCODE void unknown(Opcode) { FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract encountered unknown opcode"); } }; struct eosio_constraints_visitor : public nop_opcode_visitor { ///Make this some sort of visitor enum to reduce chance of copy pasta errors (but // the override declaration makes it somewhat safe) //While it's possible to access beyond 1MiB by giving an offset that's 1MiB-1 and // an 8 byte data type, that's fine. There will be enough of a guard on the end // of 1MiB where it's not a problem void fail_large_offset(U32 offset) { if(offset >= 1024*1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract used an invalid large memory store/load offset"); } void i32_load (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i64_load (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } void i32_load8_s (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i32_load8_u (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i32_load16_s (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i32_load16_u (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_load8_s (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i64_load8_u (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i64_load16_s (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_load16_u (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_load32_s (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i64_load32_u (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i32_store (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void i64_store (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } void i32_store8 (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i32_store16 (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_store8 (LoadOrStoreImm<0> imm) override { fail_large_offset(imm.offset); } void i64_store16 (LoadOrStoreImm<1> imm) override { fail_large_offset(imm.offset); } void i64_store32 (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void f32_load (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void f64_load (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } void f32_store (LoadOrStoreImm<2> imm) override { fail_large_offset(imm.offset); } void f64_store (LoadOrStoreImm<3> imm) override { fail_large_offset(imm.offset); } #define VISIT_OPCODE(opcode,name,nameString,Imm,...) \ void name(Imm) override { FC_THROW_EXCEPTION(wasm_execution_error, "Smart contracts may not use WASM memory operators"); } ENUM_MEMORY_OPERATORS(VISIT_OPCODE); #undef VISIT_OPCODE }; void validate_eosio_wasm_constraints(const Module& m) { if(m.memories.defs.size() && m.memories.defs[0].type.size.min > 16) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract initial memory size must be less than or equal to 1MiB"); for(const DataSegment& ds : m.dataSegments) { if(ds.baseOffset.type != InitializerExpression::Type::i32_const) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract has unexpected memory base offset type"); if(static_cast<uint32_t>(ds.baseOffset.i32) + ds.data.size() > 64*1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract data segments must lie in first 64KiB"); } if(m.tables.defs.size() && m.tables.defs[0].type.size.min > 1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract table limited to 1024 elements"); unsigned mutable_globals_total_size = 0; for(const GlobalDef& global_def : m.globals.defs) { if(!global_def.type.isMutable) continue; switch(global_def.type.valueType) { case ValueType::any: case ValueType::num: FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract has unexpected global definition value type"); case ValueType::i64: case ValueType::f64: mutable_globals_total_size += 4; case ValueType::i32: case ValueType::f32: mutable_globals_total_size += 4; } } if(mutable_globals_total_size > 1024) FC_THROW_EXCEPTION(wasm_execution_error, "Smart contract has more than 1KiB of mutable globals"); //Some of the OperatorDecoderStream users inside of WAVM track the control stack and quit parsing from // OperatorDecoderStream when the control stack is empty (since that would indicate unreachable code). // Not doing that here, yet, since it's not clear it's required for the purpose of the validation eosio_constraints_visitor visitor; for(const FunctionDef& fd : m.functions.defs) { OperatorDecoderStream decoder(fd.code); while(decoder) { decoder.decodeOp(visitor); } } } }}
Fix small typo in comment
Fix small typo in comment
C++
mit
EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos
2728be6ea93d7c0cbb8eb6d426bd97ce64f33511
chrome/browser/extensions/api/identity/web_auth_flow_unittest.cc
chrome/browser/extensions/api/identity/web_auth_flow_unittest.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "chrome/browser/extensions/api/identity/web_auth_flow.h" #include "chrome/browser/ui/extensions/web_auth_flow_window.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_thread.h" #include "content/test/test_browser_thread.h" #include "content/test/web_contents_tester.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using content::BrowserContext; using content::BrowserThread; using content::TestBrowserThread; using content::WebContents; using content::WebContentsDelegate; using content::WebContentsTester; using extensions::WebAuthFlow; using testing::Return; using testing::ReturnRef; namespace { class MockDelegate : public WebAuthFlow::Delegate { public: MOCK_METHOD1(OnAuthFlowSuccess, void(const std::string& redirect_url)); MOCK_METHOD0(OnAuthFlowFailure, void()); }; class MockWebAuthFlowWindow : public WebAuthFlowWindow { public: MockWebAuthFlowWindow() : WebAuthFlowWindow(NULL, NULL, NULL) { } virtual void Show() OVERRIDE { // Do nothing in tests. } }; class MockWebAuthFlow : public WebAuthFlow { public: MockWebAuthFlow( WebAuthFlow::Delegate* delegate, BrowserContext* browser_context, const std::string& extension_id, const GURL& provider_url) : WebAuthFlow(delegate, browser_context, extension_id, provider_url), browser_context_(browser_context), web_contents_(NULL), window_(NULL) { } virtual WebContents* CreateWebContents() OVERRIDE { CHECK(!web_contents_); web_contents_ = WebContentsTester::CreateTestWebContents( browser_context_, NULL); return web_contents_; } virtual WebAuthFlowWindow* CreateAuthWindow() OVERRIDE { CHECK(!window_); window_ = new MockWebAuthFlowWindow(); return window_; } WebContents* contents() { return web_contents_; } WebContentsTester* contents_tester() { return WebContentsTester::For(web_contents_); } MockWebAuthFlowWindow& window() { return *window_; } bool HasWindow() const { return window_ != NULL; } virtual ~MockWebAuthFlow() { } private: BrowserContext* browser_context_; WebContents* web_contents_; MockWebAuthFlowWindow* window_; }; } // namespace class WebAuthFlowTest : public ChromeRenderViewHostTestHarness { protected: WebAuthFlowTest() : thread_(BrowserThread::UI, &message_loop_) { } virtual void SetUp() { ChromeRenderViewHostTestHarness::SetUp(); } void CreateAuthFlow(const std::string& extension_id, const GURL& url) { flow_.reset(new MockWebAuthFlow(&delegate_, profile(), extension_id, url)); } MockWebAuthFlow& flow() { return *flow_.get(); } WebAuthFlow* flow_base() { return flow_.get(); } void CallOnClose() { flow_base()->OnClose(); } bool CallIsValidRedirectUrl(const GURL& url) { return flow_base()->IsValidRedirectUrl(url); } TestBrowserThread thread_; MockDelegate delegate_; scoped_ptr<MockWebAuthFlow> flow_; }; TEST_F(WebAuthFlowTest, SilentRedirectToChromiumAppUrl) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("https://abcdefghij.chromiumapp.org/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowSuccess(result.spec())).Times(1); flow_->Start(); flow_->contents_tester()->NavigateAndCommit(result); } TEST_F(WebAuthFlowTest, SilentRedirectToChromeExtensionSchemeUrl) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("chrome-extension://abcdefghij/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowSuccess(result.spec())).Times(1); flow_->Start(); flow_->contents_tester()->NavigateAndCommit(result); } TEST_F(WebAuthFlowTest, UIResultsInSuccess) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("chrome-extension://abcdefghij/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowSuccess(result.spec())).Times(1); flow_->Start(); flow_->contents_tester()->TestSetIsLoading(false); EXPECT_TRUE(flow_->HasWindow()); flow_->contents_tester()->NavigateAndCommit(result); } TEST_F(WebAuthFlowTest, UIClosedByUser) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("chrome-extension://abcdefghij/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowFailure()).Times(1); flow_->Start(); flow_->contents_tester()->TestSetIsLoading(false); EXPECT_TRUE(flow_->HasWindow()); CallOnClose(); } TEST_F(WebAuthFlowTest, IsValidRedirectUrl) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); CreateAuthFlow(ext_id, url); // Positive cases. EXPECT_TRUE(CallIsValidRedirectUrl( GURL("https://abcdefghij.chromiumapp.org/"))); EXPECT_TRUE(CallIsValidRedirectUrl( GURL("https://abcdefghij.chromiumapp.org/callback"))); EXPECT_TRUE(CallIsValidRedirectUrl( GURL("chrome-extension://abcdefghij/"))); EXPECT_TRUE(CallIsValidRedirectUrl( GURL("chrome-extension://abcdefghij/callback"))); // Negative cases. EXPECT_FALSE(CallIsValidRedirectUrl( GURL("https://www.foo.com/"))); // http scheme is not allowed. EXPECT_FALSE(CallIsValidRedirectUrl( GURL("http://abcdefghij.chromiumapp.org/callback"))); EXPECT_FALSE(CallIsValidRedirectUrl( GURL("https://abcd.chromiumapp.org/callback"))); EXPECT_FALSE(CallIsValidRedirectUrl( GURL("chrome-extension://abcd/callback"))); EXPECT_FALSE(CallIsValidRedirectUrl( GURL("chrome-extension://abcdefghijkl/"))); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "chrome/browser/extensions/api/identity/web_auth_flow.h" #include "chrome/browser/ui/extensions/web_auth_flow_window.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_thread.h" #include "content/test/test_browser_thread.h" #include "content/test/web_contents_tester.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using content::BrowserContext; using content::BrowserThread; using content::TestBrowserThread; using content::WebContents; using content::WebContentsDelegate; using content::WebContentsTester; using extensions::WebAuthFlow; using testing::Return; using testing::ReturnRef; namespace { class MockDelegate : public WebAuthFlow::Delegate { public: MOCK_METHOD1(OnAuthFlowSuccess, void(const std::string& redirect_url)); MOCK_METHOD0(OnAuthFlowFailure, void()); }; class MockWebAuthFlowWindow : public WebAuthFlowWindow { public: MockWebAuthFlowWindow() : WebAuthFlowWindow(NULL, NULL, NULL) { } virtual void Show() OVERRIDE { // Do nothing in tests. } }; class MockWebAuthFlow : public WebAuthFlow { public: MockWebAuthFlow( WebAuthFlow::Delegate* delegate, BrowserContext* browser_context, const std::string& extension_id, const GURL& provider_url) : WebAuthFlow(delegate, browser_context, extension_id, provider_url), browser_context_(browser_context), web_contents_(NULL), window_(NULL) { } virtual WebContents* CreateWebContents() OVERRIDE { CHECK(!web_contents_); web_contents_ = WebContentsTester::CreateTestWebContents( browser_context_, NULL); return web_contents_; } virtual WebAuthFlowWindow* CreateAuthWindow() OVERRIDE { CHECK(!window_); window_ = new MockWebAuthFlowWindow(); return window_; } WebContents* contents() { return web_contents_; } WebContentsTester* contents_tester() { return WebContentsTester::For(web_contents_); } MockWebAuthFlowWindow& window() { return *window_; } bool HasWindow() const { return window_ != NULL; } virtual ~MockWebAuthFlow() { } private: BrowserContext* browser_context_; WebContents* web_contents_; MockWebAuthFlowWindow* window_; }; } // namespace class WebAuthFlowTest : public ChromeRenderViewHostTestHarness { protected: WebAuthFlowTest() : thread_(BrowserThread::UI, &message_loop_) { } virtual void SetUp() { ChromeRenderViewHostTestHarness::SetUp(); } virtual void TearDown() { // |flow_| must be reset before ChromeRenderViewHostTestHarness::TearDown(), // because |flow_| deletes the WebContents it owns via // MessageLoop::DeleteSoon(). flow_.reset(); ChromeRenderViewHostTestHarness::TearDown(); } void CreateAuthFlow(const std::string& extension_id, const GURL& url) { flow_.reset(new MockWebAuthFlow(&delegate_, profile(), extension_id, url)); } MockWebAuthFlow& flow() { return *flow_.get(); } WebAuthFlow* flow_base() { return flow_.get(); } void CallOnClose() { flow_base()->OnClose(); } bool CallIsValidRedirectUrl(const GURL& url) { return flow_base()->IsValidRedirectUrl(url); } TestBrowserThread thread_; MockDelegate delegate_; scoped_ptr<MockWebAuthFlow> flow_; }; TEST_F(WebAuthFlowTest, SilentRedirectToChromiumAppUrl) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("https://abcdefghij.chromiumapp.org/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowSuccess(result.spec())).Times(1); flow_->Start(); flow_->contents_tester()->NavigateAndCommit(result); } TEST_F(WebAuthFlowTest, SilentRedirectToChromeExtensionSchemeUrl) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("chrome-extension://abcdefghij/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowSuccess(result.spec())).Times(1); flow_->Start(); flow_->contents_tester()->NavigateAndCommit(result); } TEST_F(WebAuthFlowTest, UIResultsInSuccess) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("chrome-extension://abcdefghij/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowSuccess(result.spec())).Times(1); flow_->Start(); flow_->contents_tester()->TestSetIsLoading(false); EXPECT_TRUE(flow_->HasWindow()); flow_->contents_tester()->NavigateAndCommit(result); } TEST_F(WebAuthFlowTest, UIClosedByUser) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); GURL result("chrome-extension://abcdefghij/google_cb"); CreateAuthFlow(ext_id, url); EXPECT_CALL(delegate_, OnAuthFlowFailure()).Times(1); flow_->Start(); flow_->contents_tester()->TestSetIsLoading(false); EXPECT_TRUE(flow_->HasWindow()); CallOnClose(); } TEST_F(WebAuthFlowTest, IsValidRedirectUrl) { std::string ext_id = "abcdefghij"; GURL url("https://accounts.google.com/o/oauth2/auth"); CreateAuthFlow(ext_id, url); // Positive cases. EXPECT_TRUE(CallIsValidRedirectUrl( GURL("https://abcdefghij.chromiumapp.org/"))); EXPECT_TRUE(CallIsValidRedirectUrl( GURL("https://abcdefghij.chromiumapp.org/callback"))); EXPECT_TRUE(CallIsValidRedirectUrl( GURL("chrome-extension://abcdefghij/"))); EXPECT_TRUE(CallIsValidRedirectUrl( GURL("chrome-extension://abcdefghij/callback"))); // Negative cases. EXPECT_FALSE(CallIsValidRedirectUrl( GURL("https://www.foo.com/"))); // http scheme is not allowed. EXPECT_FALSE(CallIsValidRedirectUrl( GURL("http://abcdefghij.chromiumapp.org/callback"))); EXPECT_FALSE(CallIsValidRedirectUrl( GURL("https://abcd.chromiumapp.org/callback"))); EXPECT_FALSE(CallIsValidRedirectUrl( GURL("chrome-extension://abcd/callback"))); EXPECT_FALSE(CallIsValidRedirectUrl( GURL("chrome-extension://abcdefghijkl/"))); }
Fix a leak.
Valgrind: Fix a leak. BUG=none TEST=none R=groby TBR=aa Review URL: https://chromiumcodereview.appspot.com/10413039 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@138156 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,littlstar/chromium.src,patrickm/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,zcbenz/cefode-chromium,dednal/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,patrickm/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,Chilledheart/chromium,littlstar/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,dednal/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,keishi/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,littlstar/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,hujiajie/pa-chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,anirudhSK/chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Chilledheart/chromium,hujiajie/pa-chromium,hujiajie/pa-chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,jaruba/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,zcbenz/cefode-chromium,M4sse/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,keishi/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,patrickm/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,keishi/chromium,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,anirudhSK/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,keishi/chromium,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,keishi/chromium,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,patrickm/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,keishi/chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,dednal/chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,hujiajie/pa-chromium,keishi/chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium
ba2a325585668f3d397eb02e6725b90f931acfe1
chrome/browser/extensions/extension_disabled_infobar_delegate.cc
chrome/browser/extensions/extension_disabled_infobar_delegate.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_disabled_infobar_delegate.h" #include <string> #include "base/compiler_specific.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/infobars/infobar_tab_helper.h" #include "chrome/browser/tab_contents/confirm_infobar_delegate.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_resource.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" // ExtensionDisabledDialogDelegate -------------------------------------------- class ExtensionDisabledDialogDelegate : public ExtensionInstallUI::Delegate, public base::RefCountedThreadSafe<ExtensionDisabledDialogDelegate> { public: ExtensionDisabledDialogDelegate(Profile* profile, ExtensionService* service, const Extension* extension); private: friend class base::RefCountedThreadSafe<ExtensionDisabledDialogDelegate>; virtual ~ExtensionDisabledDialogDelegate(); // ExtensionInstallUI::Delegate: virtual void InstallUIProceed() OVERRIDE; virtual void InstallUIAbort(bool user_initiated) OVERRIDE; // The UI for showing the install dialog when enabling. scoped_ptr<ExtensionInstallUI> install_ui_; ExtensionService* service_; const Extension* extension_; }; ExtensionDisabledDialogDelegate::ExtensionDisabledDialogDelegate( Profile* profile, ExtensionService* service, const Extension* extension) : service_(service), extension_(extension) { AddRef(); // Balanced in Proceed or Abort. install_ui_.reset(new ExtensionInstallUI(profile)); install_ui_->ConfirmReEnable(this, extension_); } ExtensionDisabledDialogDelegate::~ExtensionDisabledDialogDelegate() { } void ExtensionDisabledDialogDelegate::InstallUIProceed() { service_->GrantPermissionsAndEnableExtension(extension_); Release(); } void ExtensionDisabledDialogDelegate::InstallUIAbort(bool user_initiated) { std::string histogram_name = user_initiated ? "Extensions.Permissions_ReEnableCancel" : "Extensions.Permissions_ReEnableAbort"; ExtensionService::RecordPermissionMessagesHistogram( extension_, histogram_name.c_str()); // Do nothing. The extension will remain disabled. Release(); } // ExtensionDisabledInfobarDelegate ------------------------------------------- class ExtensionDisabledInfobarDelegate : public ConfirmInfoBarDelegate, public content::NotificationObserver { public: ExtensionDisabledInfobarDelegate(InfoBarTabHelper* infobar_helper, ExtensionService* service, const Extension* extension); private: virtual ~ExtensionDisabledInfobarDelegate(); // ConfirmInfoBarDelegate: virtual string16 GetMessageText() const OVERRIDE; virtual int GetButtons() const OVERRIDE; virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE; virtual bool Accept() OVERRIDE; // content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; content::NotificationRegistrar registrar_; ExtensionService* service_; const Extension* extension_; }; ExtensionDisabledInfobarDelegate::ExtensionDisabledInfobarDelegate( InfoBarTabHelper* infobar_helper, ExtensionService* service, const Extension* extension) : ConfirmInfoBarDelegate(infobar_helper), service_(service), extension_(extension) { // The user might re-enable the extension in other ways, so watch for that. registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, content::Source<Profile>(service->profile())); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(service->profile())); } ExtensionDisabledInfobarDelegate::~ExtensionDisabledInfobarDelegate() { } string16 ExtensionDisabledInfobarDelegate::GetMessageText() const { return l10n_util::GetStringFUTF16(extension_->is_app() ? IDS_APP_DISABLED_INFOBAR_LABEL : IDS_EXTENSION_DISABLED_INFOBAR_LABEL, UTF8ToUTF16(extension_->name())); } int ExtensionDisabledInfobarDelegate::GetButtons() const { return BUTTON_OK; } string16 ExtensionDisabledInfobarDelegate::GetButtonLabel( InfoBarButton button) const { DCHECK_EQ(BUTTON_OK, button); return l10n_util::GetStringUTF16( IDS_EXTENSION_DISABLED_INFOBAR_ENABLE_BUTTON); } bool ExtensionDisabledInfobarDelegate::Accept() { // This object manages its own lifetime. new ExtensionDisabledDialogDelegate(service_->profile(), service_, extension_); return true; } void ExtensionDisabledInfobarDelegate::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { // TODO(mpcomplete): RemoveInfoBar doesn't seem to always result in us getting // deleted. const Extension* extension = NULL; if (type == chrome::NOTIFICATION_EXTENSION_LOADED) { extension = content::Details<const Extension>(details).ptr(); } else { DCHECK_EQ(chrome::NOTIFICATION_EXTENSION_UNLOADED, type); UnloadedExtensionInfo* info = content::Details<UnloadedExtensionInfo>(details).ptr(); if (info->reason == extension_misc::UNLOAD_REASON_DISABLE || info->reason == extension_misc::UNLOAD_REASON_UNINSTALL) extension = info->extension; } if (extension == extension_) RemoveSelf(); } // Globals -------------------------------------------------------------------- void ShowExtensionDisabledUI(ExtensionService* service, Profile* profile, const Extension* extension) { Browser* browser = BrowserList::GetLastActiveWithProfile(profile); if (!browser) return; TabContentsWrapper* tab_contents = browser->GetSelectedTabContentsWrapper(); if (!tab_contents) return; InfoBarTabHelper* infobar_helper = tab_contents->infobar_tab_helper(); infobar_helper->AddInfoBar( new ExtensionDisabledInfobarDelegate(infobar_helper, service, extension)); } void ShowExtensionDisabledDialog(ExtensionService* service, Profile* profile, const Extension* extension) { // This object manages its own lifetime. new ExtensionDisabledDialogDelegate(profile, service, extension); }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_disabled_infobar_delegate.h" #include <string> #include "base/compiler_specific.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/infobars/infobar_tab_helper.h" #include "chrome/browser/tab_contents/confirm_infobar_delegate.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_resource.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" // ExtensionDisabledDialogDelegate -------------------------------------------- class ExtensionDisabledDialogDelegate : public ExtensionInstallUI::Delegate, public base::RefCountedThreadSafe<ExtensionDisabledDialogDelegate> { public: ExtensionDisabledDialogDelegate(Profile* profile, ExtensionService* service, const Extension* extension); private: friend class base::RefCountedThreadSafe<ExtensionDisabledDialogDelegate>; virtual ~ExtensionDisabledDialogDelegate(); // ExtensionInstallUI::Delegate: virtual void InstallUIProceed() OVERRIDE; virtual void InstallUIAbort(bool user_initiated) OVERRIDE; // The UI for showing the install dialog when enabling. scoped_ptr<ExtensionInstallUI> install_ui_; ExtensionService* service_; const Extension* extension_; }; ExtensionDisabledDialogDelegate::ExtensionDisabledDialogDelegate( Profile* profile, ExtensionService* service, const Extension* extension) : service_(service), extension_(extension) { AddRef(); // Balanced in Proceed or Abort. install_ui_.reset(new ExtensionInstallUI(profile)); install_ui_->ConfirmReEnable(this, extension_); } ExtensionDisabledDialogDelegate::~ExtensionDisabledDialogDelegate() { } void ExtensionDisabledDialogDelegate::InstallUIProceed() { service_->GrantPermissionsAndEnableExtension(extension_); Release(); } void ExtensionDisabledDialogDelegate::InstallUIAbort(bool user_initiated) { std::string histogram_name = user_initiated ? "Extensions.Permissions_ReEnableCancel" : "Extensions.Permissions_ReEnableAbort"; ExtensionService::RecordPermissionMessagesHistogram( extension_, histogram_name.c_str()); // Do nothing. The extension will remain disabled. Release(); } // ExtensionDisabledInfobarDelegate ------------------------------------------- class ExtensionDisabledInfobarDelegate : public ConfirmInfoBarDelegate, public content::NotificationObserver { public: ExtensionDisabledInfobarDelegate(InfoBarTabHelper* infobar_helper, ExtensionService* service, const Extension* extension); private: virtual ~ExtensionDisabledInfobarDelegate(); // ConfirmInfoBarDelegate: virtual string16 GetMessageText() const OVERRIDE; virtual int GetButtons() const OVERRIDE; virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE; virtual bool Accept() OVERRIDE; // content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; content::NotificationRegistrar registrar_; ExtensionService* service_; const Extension* extension_; }; ExtensionDisabledInfobarDelegate::ExtensionDisabledInfobarDelegate( InfoBarTabHelper* infobar_helper, ExtensionService* service, const Extension* extension) : ConfirmInfoBarDelegate(infobar_helper), service_(service), extension_(extension) { // The user might re-enable the extension in other ways, so watch for that. registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, content::Source<Profile>(service->profile())); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(service->profile())); } ExtensionDisabledInfobarDelegate::~ExtensionDisabledInfobarDelegate() { } string16 ExtensionDisabledInfobarDelegate::GetMessageText() const { return l10n_util::GetStringFUTF16(extension_->is_app() ? IDS_APP_DISABLED_INFOBAR_LABEL : IDS_EXTENSION_DISABLED_INFOBAR_LABEL, UTF8ToUTF16(extension_->name())); } int ExtensionDisabledInfobarDelegate::GetButtons() const { return BUTTON_OK; } string16 ExtensionDisabledInfobarDelegate::GetButtonLabel( InfoBarButton button) const { DCHECK_EQ(BUTTON_OK, button); return l10n_util::GetStringUTF16( IDS_EXTENSION_DISABLED_INFOBAR_ENABLE_BUTTON); } bool ExtensionDisabledInfobarDelegate::Accept() { // This object manages its own lifetime. new ExtensionDisabledDialogDelegate(service_->profile(), service_, extension_); return true; } void ExtensionDisabledInfobarDelegate::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { // TODO(mpcomplete): RemoveInfoBar doesn't seem to always result in us getting // deleted. const Extension* extension = NULL; if (type == chrome::NOTIFICATION_EXTENSION_LOADED) { extension = content::Details<const Extension>(details).ptr(); } else { DCHECK_EQ(chrome::NOTIFICATION_EXTENSION_UNLOADED, type); UnloadedExtensionInfo* info = content::Details<UnloadedExtensionInfo>(details).ptr(); extension = info->extension; } if (extension == extension_) RemoveSelf(); } // Globals -------------------------------------------------------------------- void ShowExtensionDisabledUI(ExtensionService* service, Profile* profile, const Extension* extension) { Browser* browser = BrowserList::GetLastActiveWithProfile(profile); if (!browser) return; TabContentsWrapper* tab_contents = browser->GetSelectedTabContentsWrapper(); if (!tab_contents) return; InfoBarTabHelper* infobar_helper = tab_contents->infobar_tab_helper(); infobar_helper->AddInfoBar( new ExtensionDisabledInfobarDelegate(infobar_helper, service, extension)); } void ShowExtensionDisabledDialog(ExtensionService* service, Profile* profile, const Extension* extension) { // This object manages its own lifetime. new ExtensionDisabledDialogDelegate(profile, service, extension); }
Remove extension disabled infobar when extension is unloaded for any reason.
Remove extension disabled infobar when extension is unloaded for any reason. Not doing so could leave the infobar around even after the extension has been deleted, which is bad. BUG=105319 TEST=Follow steps in bug, comment 2; do not see a crash. Review URL: http://codereview.chromium.org/8966007 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@114735 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium
c3457a0139dfc344d5a4bbffaeaf938bf9cafccc
src/import/chips/p9/procedures/hwp/perv/p9_switch_rec_attn.H
src/import/chips/p9/procedures/hwp/perv/p9_switch_rec_attn.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_switch_rec_attn.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_switch_rec_attn.H /// /// @brief Switch recoverable/special attentions from host back to FSP //------------------------------------------------------------------------------ // *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : Sunil Kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 1 // *HWP Consumed by : HB //------------------------------------------------------------------------------ #ifndef _P9_SWITCH_REC_ATTN_H_ #define _P9_SWITCH_REC_ATTN_H_ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_switch_rec_attn_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); /// @brief Switch recoverable/special attentions from host back to FSP /// /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PROC_CHIP target /// @return FAPI2_RC_SUCCESS if success, else error code. extern "C" { fapi2::ReturnCode p9_switch_rec_attn(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet); } #endif
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_switch_rec_attn.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_switch_rec_attn.H /// /// @brief Switch recoverable/special attentions from host back to FSP //------------------------------------------------------------------------------ // *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : Sunil Kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 3 // *HWP Consumed by : HB //------------------------------------------------------------------------------ #ifndef _P9_SWITCH_REC_ATTN_H_ #define _P9_SWITCH_REC_ATTN_H_ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_switch_rec_attn_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); /// @brief Switch recoverable/special attentions from host back to FSP /// /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PROC_CHIP target /// @return FAPI2_RC_SUCCESS if success, else error code. extern "C" { fapi2::ReturnCode p9_switch_rec_attn(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet); } #endif
Update hardware procedure metadata
Update hardware procedure metadata update the metadata to reflect that HWPs are product ready (HWP Level: 3) Change-Id: Ia45766cabbf0bacf510b2732e1144ad12ebca17e Original-Change-Id: I5a7380e9f34865b3e0ef7872d6338a840b08aa4a Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/46789 Tested-by: FSP CI Jenkins <[email protected]> Tested-by: Jenkins Server <[email protected]> Tested-by: HWSV CI <[email protected]> Tested-by: PPE CI <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Joseph J. McGill <[email protected]> Reviewed-by: SRINIVAS V. POLISETTY <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
9bf16deb94fdb49891016c88de2044e472d56f7e
test/rsa-crypt/rsa-crypt-test.cc
test/rsa-crypt/rsa-crypt-test.cc
#include <gtest/gtest.h> #include <iostream> #include <dgcrypto/dgcrypto.hh> #include <rsa-crypt-lib/rsa-crypt-lib.hh> TEST(RSACrypt, RsaKeysConstructor) { RsaKeys my_keys(8); EXPECT_EQ(my_keys.e(), my_keys.totient());
#include <gtest/gtest.h> #include <iostream> #include <dgcrypto/dgcrypto.hh> #include <rsa-crypt-lib/rsa-crypt-lib.hh> TEST(RSACrypt, RsaKeysConstructor) { RsaKeys my_keys(8); EXPECT_EQ(my_keys.e(), my_keys.totient()); }
fix missing bracket
fix missing bracket
C++
bsd-3-clause
gwydirsam/DickGrayson,gwydirsam/DickGrayson,gwydirsam/DickGrayson
3cda35c5748595c208b8329f5fda2c62fa627fbc
media/ffmpeg/file_protocol.cc
media/ffmpeg/file_protocol.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/ffmpeg/file_protocol.h" #include "build/build_config.h" #if defined(OS_WIN) #include <io.h> #else #include <unistd.h> #endif #include <fcntl.h> #include "base/compiler_specific.h" #include "base/eintr_wrapper.h" #include "base/file_util.h" #include "media/ffmpeg/ffmpeg_common.h" // warning C4996: 'open': The POSIX name for this item is deprecated. MSVC_PUSH_DISABLE_WARNING(4996) static int GetHandle(URLContext *h) { return static_cast<int>(reinterpret_cast<intptr_t>(h->priv_data)); } // FFmpeg protocol interface. static int OpenContext(URLContext* h, const char* filename, int flags) { int access = O_RDONLY; if (flags & URL_RDWR) { access = O_CREAT | O_TRUNC | O_RDWR; } else if (flags & URL_WRONLY) { access = O_CREAT | O_TRUNC | O_WRONLY; } #ifdef O_BINARY access |= O_BINARY; #endif int f = open(filename, access, 0666); if (f == -1) return AVERROR(ENOENT); h->priv_data = reinterpret_cast<void*>(static_cast<intptr_t>(f)); h->is_streamed = false; return 0; } static int ReadContext(URLContext* h, unsigned char* buf, int size) { return HANDLE_EINTR(read(GetHandle(h), buf, size)); } #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(52, 68, 0) static int WriteContext(URLContext* h, const unsigned char* buf, int size) { #else static int WriteContext(URLContext* h, unsigned char* buf, int size) { #endif return HANDLE_EINTR(write(GetHandle(h), buf, size)); } static int64 SeekContext(URLContext* h, int64 offset, int whence) { #if defined(OS_WIN) return _lseeki64(GetHandle(h), static_cast<__int64>(offset), whence); #else COMPILE_ASSERT(sizeof(off_t) == 8, off_t_not_64_bit); return lseek(GetHandle(h), static_cast<off_t>(offset), whence); #endif } static int CloseContext(URLContext* h) { return HANDLE_EINTR(close(GetHandle(h))); } MSVC_POP_WARNING() URLProtocol kFFmpegFileProtocol = { "file", &OpenContext, &ReadContext, &WriteContext, &SeekContext, &CloseContext, NULL, // *next NULL, // url_read_pause NULL, // url_read_seek &GetHandle };
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/ffmpeg/file_protocol.h" #include "build/build_config.h" #if defined(OS_WIN) #include <io.h> #else #include <unistd.h> #endif #include <fcntl.h> #include "base/compiler_specific.h" #include "base/eintr_wrapper.h" #include "base/file_util.h" #include "media/ffmpeg/ffmpeg_common.h" // warning C4996: 'open': The POSIX name for this item is deprecated. MSVC_PUSH_DISABLE_WARNING(4996) static int GetHandle(URLContext *h) { return static_cast<int>(reinterpret_cast<intptr_t>(h->priv_data)); } // FFmpeg protocol interface. static int OpenContext(URLContext* h, const char* filename, int flags) { int access = O_RDONLY; if ((flags & AVIO_FLAG_WRITE) && (flags & AVIO_FLAG_READ)) { access = O_CREAT | O_TRUNC | O_RDWR; } else if (flags & AVIO_FLAG_WRITE) { access = O_CREAT | O_TRUNC | O_WRONLY; } #ifdef O_BINARY access |= O_BINARY; #endif int f = open(filename, access, 0666); if (f == -1) return AVERROR(ENOENT); h->priv_data = reinterpret_cast<void*>(static_cast<intptr_t>(f)); h->is_streamed = false; return 0; } static int ReadContext(URLContext* h, unsigned char* buf, int size) { return HANDLE_EINTR(read(GetHandle(h), buf, size)); } #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(52, 68, 0) static int WriteContext(URLContext* h, const unsigned char* buf, int size) { #else static int WriteContext(URLContext* h, unsigned char* buf, int size) { #endif return HANDLE_EINTR(write(GetHandle(h), buf, size)); } static int64 SeekContext(URLContext* h, int64 offset, int whence) { #if defined(OS_WIN) return _lseeki64(GetHandle(h), static_cast<__int64>(offset), whence); #else COMPILE_ASSERT(sizeof(off_t) == 8, off_t_not_64_bit); return lseek(GetHandle(h), static_cast<off_t>(offset), whence); #endif } static int CloseContext(URLContext* h) { return HANDLE_EINTR(close(GetHandle(h))); } MSVC_POP_WARNING() URLProtocol kFFmpegFileProtocol = { "file", &OpenContext, &ReadContext, &WriteContext, &SeekContext, &CloseContext, NULL, // *next NULL, // url_read_pause NULL, // url_read_seek &GetHandle };
Update Chromium's FFmpeg file URLProtocol implementation.
Update Chromium's FFmpeg file URLProtocol implementation. The flag values were changed resulting in Chromium opening the file for create resulting in a 0-byte file. BUG=88784 TEST=use media_bench/ffmpeg_unittests, the file won't be overwritten Review URL: http://codereview.chromium.org/7466034 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@93526 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium
c67c71021ab13e92691cffc03d80f031c504c019
test/unit/core/dat/test-file.cpp
test/unit/core/dat/test-file.cpp
/* -*- c-basic-offset: 2; coding: utf-8 -*- */ /* Copyright (C) 2011 Brazil 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 */ #include <gcutter.h> #include <cppcutter.h> #include <grn-assertions.h> #include <dat/file.hpp> #include <cstring> namespace test_dat_file { void test_invalid_file(void) { const grn::dat::File file; cppcut_assert_equal(file.ptr(), static_cast<void *>(NULL)); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(0)); } void test_create_without_path(void) { grn::dat::File file; try { file.create(NULL, 0); cut_fail("A zero-byte request is not allowed."); } catch (const grn::dat::Exception &) { } file.create(NULL, 32); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(32)); grn::dat::UInt8 * const buf = static_cast<grn::dat::UInt8 *>(file.ptr()); for (grn::dat::UInt64 i = 0; i < file.size(); ++i) { buf[i] = static_cast<grn::dat::UInt8>(i); cppcut_assert_equal(buf[i], static_cast<grn::dat::UInt8>(i)); } } void test_create_with_path(void) { grn::dat::File file; try { file.create("test_dat_file.tmp", 0); cut_fail("A zero-byte request is not allowed."); } catch (const grn::dat::Exception &) { } file.create("test_dat_file.tmp", 32); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(32)); grn::dat::UInt8 * const buf = static_cast<grn::dat::UInt8 *>(file.ptr()); for (grn::dat::UInt64 i = 0; i < file.size(); ++i) { buf[i] = static_cast<grn::dat::UInt8>(i); cppcut_assert_equal(buf[i], static_cast<grn::dat::UInt8>(i)); } } void test_open(void) { grn::dat::File file; try { file.open(NULL); cut_fail("A null-path request is not allowed."); } catch (const grn::dat::Exception &) { } file.create("test_dat_file.tmp", 32); std::strcpy(static_cast<char *>(file.ptr()), "This is a pen."); file.close(); cppcut_assert_equal(file.ptr(), static_cast<void *>(NULL)); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(0)); file.open("test_dat_file.tmp"); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(32)); cut_assert(!std::strcmp(static_cast<char *>(file.ptr()), "This is a pen.")); } void test_swap(void) { grn::dat::File file; file.create(NULL, 100); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(100)); grn::dat::File file_new; file_new.swap(&file); cppcut_assert_equal(file.ptr(), static_cast<void *>(NULL)); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(0)); cut_assert(file_new.ptr() != NULL); cppcut_assert_equal(file_new.size(), static_cast<grn::dat::UInt64>(100)); } }
/* -*- c-basic-offset: 2; coding: utf-8 -*- */ /* Copyright (C) 2011 Brazil 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 */ #include <gcutter.h> #include <cppcutter.h> #include <grn-assertions.h> #include <dat/file.hpp> #include <cstring> namespace test_dat_file { const gchar *base_dir = NULL; void cut_setup(void) { base_dir = grn_test_get_tmp_dir(); cut_remove_path(base_dir, NULL); g_mkdir_with_parents(base_dir, 0755); } void cut_teardown(void) { if (base_dir) { cut_remove_path(base_dir, NULL); } } void test_invalid_file(void) { const grn::dat::File file; cppcut_assert_equal(file.ptr(), static_cast<void *>(NULL)); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(0)); } void test_create_without_path(void) { grn::dat::File file; try { file.create(NULL, 0); cut_fail("A zero-byte request is not allowed."); } catch (const grn::dat::Exception &) { } file.create(NULL, 32); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(32)); grn::dat::UInt8 * const buf = static_cast<grn::dat::UInt8 *>(file.ptr()); for (grn::dat::UInt64 i = 0; i < file.size(); ++i) { buf[i] = static_cast<grn::dat::UInt8>(i); cppcut_assert_equal(buf[i], static_cast<grn::dat::UInt8>(i)); } } void test_create_with_path(void) { char path[PATH_MAX]; strcpy(path, base_dir); strcat(path, "test_create_with_path.dat"); grn::dat::File file; try { file.create(path, 0); cut_fail("A zero-byte request is not allowed."); } catch (const grn::dat::Exception &) { } file.create(path, 32); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(32)); grn::dat::UInt8 * const buf = static_cast<grn::dat::UInt8 *>(file.ptr()); for (grn::dat::UInt64 i = 0; i < file.size(); ++i) { buf[i] = static_cast<grn::dat::UInt8>(i); cppcut_assert_equal(buf[i], static_cast<grn::dat::UInt8>(i)); } } void test_open(void) { char path[PATH_MAX]; strcpy(path, base_dir); strcat(path, "test_open.dat"); grn::dat::File file; try { file.open(NULL); cut_fail("A null-path request is not allowed."); } catch (const grn::dat::Exception &) { } file.create(path, 32); std::strcpy(static_cast<char *>(file.ptr()), "This is a pen."); file.close(); cppcut_assert_equal(file.ptr(), static_cast<void *>(NULL)); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(0)); file.open(path); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(32)); cut_assert(!std::strcmp(static_cast<char *>(file.ptr()), "This is a pen.")); } void test_swap(void) { grn::dat::File file; file.create(NULL, 100); cut_assert(file.ptr() != NULL); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(100)); grn::dat::File file_new; file_new.swap(&file); cppcut_assert_equal(file.ptr(), static_cast<void *>(NULL)); cppcut_assert_equal(file.size(), static_cast<grn::dat::UInt64>(0)); cut_assert(file_new.ptr() != NULL); cppcut_assert_equal(file_new.size(), static_cast<grn::dat::UInt64>(100)); } }
change handling of temporary files.
change handling of temporary files.
C++
lgpl-2.1
myokoym/groonga,naoa/groonga,redfigure/groonga,kenhys/groonga,naoa/groonga,groonga/groonga,myokoym/groonga,kenhys/groonga,hiroyuki-sato/groonga,myokoym/groonga,groonga/groonga,cosmo0920/groonga,redfigure/groonga,kenhys/groonga,komainu8/groonga,komainu8/groonga,groonga/groonga,groonga/groonga,kenhys/groonga,myokoym/groonga,cosmo0920/groonga,hiroyuki-sato/groonga,kenhys/groonga,naoa/groonga,komainu8/groonga,cosmo0920/groonga,hiroyuki-sato/groonga,cosmo0920/groonga,myokoym/groonga,kenhys/groonga,hiroyuki-sato/groonga,groonga/groonga,komainu8/groonga,naoa/groonga,redfigure/groonga,naoa/groonga,hiroyuki-sato/groonga,redfigure/groonga,redfigure/groonga,groonga/groonga,kenhys/groonga,myokoym/groonga,naoa/groonga,komainu8/groonga,redfigure/groonga,groonga/groonga,komainu8/groonga,cosmo0920/groonga,groonga/groonga,redfigure/groonga,hiroyuki-sato/groonga,myokoym/groonga,hiroyuki-sato/groonga,cosmo0920/groonga,komainu8/groonga,cosmo0920/groonga,naoa/groonga,cosmo0920/groonga,kenhys/groonga,hiroyuki-sato/groonga,naoa/groonga,redfigure/groonga,myokoym/groonga,komainu8/groonga
102b89dd5821036179b0419685b31bb35abcd9cd
test/tsan/Linux/check_memcpy.cc
test/tsan/Linux/check_memcpy.cc
// Test that verifies TSan runtime doesn't contain compiler-emitted // memcpy/memmove calls. It builds the binary with TSan and passes it to // check_memcpy.sh script. // RUN: %clangxx_tsan -O1 %s -o %t // RUN: llvm-objdump -d %t | FileCheck %s int main() { return 0; } // CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}} // tail calls: // CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}
// Test that verifies TSan runtime doesn't contain compiler-emitted // memcpy/memmove calls. It builds the binary with TSan and passes it to // check_memcpy.sh script. // RUN: %clangxx_tsan -O1 %s -o %t // RUN: llvm-objdump -d %t | FileCheck %s // REQUIRES: compiler-rt-optimized int main() { return 0; } // CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}} // tail calls: // CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}
Disable test with debug runtime
[tsan] Disable test with debug runtime Test expects at least -O1 compiled runtime. git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@308121 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
3117e6615402ba6cb054de059dd4d7b4ff15c177
tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc
tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/mlir_graph_optimization_pass.h" #include <string> #include "absl/container/flat_hash_set.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_os_ostream.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/translate/export_graphdef.h" #include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h" #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" #include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { static inline absl::string_view StringRefToView(llvm::StringRef ref) { return {ref.data(), ref.size()}; } // Dumps the MLIR module to disk. // This require the TF_DUMP_GRAPH_PREFIX to be set to a path that exist (or can // be created). static void DumpModule(mlir::ModuleOp module, std::string file_prefix) { std::string prefix = GetDumpDirFromEnvVar(); if (prefix.empty()) return; auto* env = tensorflow::Env::Default(); auto status = env->RecursivelyCreateDir(prefix); if (!status.ok()) { LOG(WARNING) << "cannot create directory '" + prefix + "': " + status.error_message(); return; } prefix += "/" + file_prefix; if (!tensorflow::Env::Default()->CreateUniqueFileName(&prefix, ".mlir")) { LOG(WARNING) << "cannot create unique filename, won't dump MLIR module."; return; } std::unique_ptr<WritableFile> file_writer; status = env->NewWritableFile(prefix, &file_writer); if (!status.ok()) { LOG(WARNING) << "cannot open file '" + prefix + "': " + status.error_message(); return; } // Print the module to a string before writing to the file. std::string txt_module; { llvm::raw_string_ostream os(txt_module); module.print(os); } status = file_writer->Append(txt_module); if (!status.ok()) { LOG(WARNING) << "error writing to file '" + prefix + "': " + status.error_message(); return; } (void)file_writer->Close(); VLOG(1) << "Dumped MLIR module to " << prefix; } MlirOptimizationPassRegistry& MlirOptimizationPassRegistry::Global() { static auto* global = new MlirOptimizationPassRegistry(); return *global; } static void RegisterDialects() { static bool init_once = []() { mlir::registerDialect<mlir::StandardOpsDialect>(); mlir::registerDialect<mlir::tf_device::TensorFlowDeviceDialect>(); mlir::registerDialect<mlir::tf_executor::TensorFlowExecutorDialect>(); mlir::registerDialect<mlir::TF::TensorFlowDialect>(); return true; }(); (void)init_once; } Status MlirFunctionOptimizationPass::Run( const DeviceSet& device_set, const ConfigProto& config_proto, std::unique_ptr<Graph>* graph, FunctionLibraryDefinition* flib_def, std::vector<std::string>* control_ret_node_names, bool* control_rets_updated) { // Skip conversion from Graph to MLIR if none of the passes are enabled. const bool is_enabled = llvm::any_of(registry_->passes(), [&](auto& pass_registration) -> bool { return pass_registration.pass->IsEnabled(config_proto); }); if (!is_enabled) { VLOG(1) << "None of the MLIR optimization passes are enabled " << "(registered " << registry_->passes().size() << ")"; return Status::OK(); } VLOG(1) << "Running MLIR Graph Optimization Passes " << "(registered " << registry_->passes().size() << " passes)"; GraphDebugInfo debug_info; RegisterDialects(); mlir::MLIRContext context; GraphImportConfig import_config; import_config.graph_as_function = true; import_config.control_outputs = *control_ret_node_names; TF_ASSIGN_OR_RETURN(auto module_ref, ConvertGraphToMlir(**graph, debug_info, *flib_def, import_config, &context)); AddDevicesToOp(*module_ref, &device_set); for (auto& pass_registration : registry_->passes()) { llvm::StringRef name = pass_registration.pass->name(); VLOG(2) << "Run MLIR graph optimization pass: " << StringRefToView(name); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_before_", name)); } TF_RETURN_IF_ERROR(pass_registration.pass->Run(config_proto, *module_ref)); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_after_", name)); } } GraphExportConfig export_config; export_config.graph_as_function = true; absl::flat_hash_set<Node*> control_ret_nodes; TF_RETURN_WITH_CONTEXT_IF_ERROR( ConvertMlirToGraph(*module_ref, export_config, graph, flib_def, &control_ret_nodes), "Error converting MLIR module back to graph"); control_ret_node_names->clear(); control_ret_node_names->reserve(control_ret_nodes.size()); for (const auto* node : control_ret_nodes) control_ret_node_names->push_back(node->name()); *control_rets_updated = true; return Status::OK(); } MlirV1CompatOptimizationPassRegistry& MlirV1CompatOptimizationPassRegistry::Global() { static auto* global = new MlirV1CompatOptimizationPassRegistry(); return *global; } Status MlirV1CompatGraphOptimizationPass::Run( const GraphOptimizationPassOptions& options) { // Skip function graphs as MlirOptimizationPassRegistry_ will be used instead. if (options.is_function_graph) return Status::OK(); // Skip conversion from Graph to MLIR if none of the passes are enabled. const bool is_enabled = absl::c_any_of(registry_->passes(), [&](auto& pass_registration) -> bool { return pass_registration.pass->IsEnabled( options.session_options->config); }); if (!is_enabled) { VLOG(1) << "None of the MLIR optimization passes are enabled " << "(registered" << registry_->passes().size() << " passes)"; return Status::OK(); } VLOG(1) << "Running MLIR Graph Optimization V1 Compat Passes " << "(registered" << registry_->passes().size() << " passes)"; GraphDebugInfo debug_info; RegisterDialects(); mlir::MLIRContext context; GraphImportConfig import_config; // TODO(b/150959075): Running functionalization before TPU cluster formation // is not semantics preserving and should be disabled for now. import_config.upgrade_legacy = false; TF_ASSIGN_OR_RETURN( auto module_ref, ConvertGraphToMlir(**options.graph, debug_info, *options.flib_def, import_config, &context)); AddDevicesToOp(*module_ref, options.device_set); for (auto& pass_registration : registry_->passes()) { llvm::StringRef name = pass_registration.pass->name(); VLOG(2) << "Run MLIR graph optimization pass: " << StringRefToView(name); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_before_", name)); } TF_RETURN_IF_ERROR(pass_registration.pass->Run(options, *module_ref)); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_after_", name)); } } GraphExportConfig export_config; TF_RETURN_WITH_CONTEXT_IF_ERROR( ConvertMlirToGraph(*module_ref, export_config, options.graph, options.flib_def), "Error converting MLIR module back to graph"); return Status::OK(); } } // namespace tensorflow
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/mlir_graph_optimization_pass.h" #include <string> #include "absl/container/flat_hash_set.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_os_ostream.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/translate/export_graphdef.h" #include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h" #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" #include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { static inline absl::string_view StringRefToView(llvm::StringRef ref) { return {ref.data(), ref.size()}; } // Dumps the MLIR module to disk. // This require the TF_DUMP_GRAPH_PREFIX to be set to a path that exist (or can // be created). static void DumpModule(mlir::ModuleOp module, std::string file_prefix) { std::string prefix = GetDumpDirFromEnvVar(); if (prefix.empty()) return; auto* env = tensorflow::Env::Default(); auto status = env->RecursivelyCreateDir(prefix); if (!status.ok()) { LOG(WARNING) << "cannot create directory '" + prefix + "': " + status.error_message(); return; } prefix += "/" + file_prefix; if (!tensorflow::Env::Default()->CreateUniqueFileName(&prefix, ".mlir")) { LOG(WARNING) << "cannot create unique filename, won't dump MLIR module."; return; } std::unique_ptr<WritableFile> file_writer; status = env->NewWritableFile(prefix, &file_writer); if (!status.ok()) { LOG(WARNING) << "cannot open file '" + prefix + "': " + status.error_message(); return; } // Print the module to a string before writing to the file. std::string txt_module; { llvm::raw_string_ostream os(txt_module); module.print(os); } status = file_writer->Append(txt_module); if (!status.ok()) { LOG(WARNING) << "error writing to file '" + prefix + "': " + status.error_message(); return; } (void)file_writer->Close(); VLOG(1) << "Dumped MLIR module to " << prefix; } MlirOptimizationPassRegistry& MlirOptimizationPassRegistry::Global() { static auto* global = new MlirOptimizationPassRegistry(); return *global; } static void RegisterDialects() { static bool init_once = []() { mlir::registerDialect<mlir::StandardOpsDialect>(); mlir::registerDialect<mlir::tf_device::TensorFlowDeviceDialect>(); mlir::registerDialect<mlir::tf_executor::TensorFlowExecutorDialect>(); mlir::registerDialect<mlir::TF::TensorFlowDialect>(); return true; }(); (void)init_once; } Status MlirFunctionOptimizationPass::Run( const DeviceSet& device_set, const ConfigProto& config_proto, std::unique_ptr<Graph>* graph, FunctionLibraryDefinition* flib_def, std::vector<std::string>* control_ret_node_names, bool* control_rets_updated) { // Skip conversion from Graph to MLIR if none of the passes are enabled. const bool is_enabled = llvm::any_of(registry_->passes(), [&](auto& pass_registration) -> bool { return pass_registration.pass->IsEnabled(config_proto); }); if (!is_enabled) { VLOG(1) << "None of the MLIR optimization passes are enabled " << "(registered " << registry_->passes().size() << ")"; return Status::OK(); } VLOG(1) << "Running MLIR Graph Optimization Passes " << "(registered " << registry_->passes().size() << " passes)"; GraphDebugInfo debug_info; RegisterDialects(); mlir::MLIRContext context; GraphImportConfig import_config; import_config.graph_as_function = true; import_config.control_outputs = *control_ret_node_names; import_config.upgrade_legacy = true; TF_ASSIGN_OR_RETURN(auto module_ref, ConvertGraphToMlir(**graph, debug_info, *flib_def, import_config, &context)); AddDevicesToOp(*module_ref, &device_set); for (auto& pass_registration : registry_->passes()) { llvm::StringRef name = pass_registration.pass->name(); VLOG(2) << "Run MLIR graph optimization pass: " << StringRefToView(name); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_before_", name)); } TF_RETURN_IF_ERROR(pass_registration.pass->Run(config_proto, *module_ref)); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_after_", name)); } } GraphExportConfig export_config; export_config.graph_as_function = true; absl::flat_hash_set<Node*> control_ret_nodes; TF_RETURN_WITH_CONTEXT_IF_ERROR( ConvertMlirToGraph(*module_ref, export_config, graph, flib_def, &control_ret_nodes), "Error converting MLIR module back to graph"); control_ret_node_names->clear(); control_ret_node_names->reserve(control_ret_nodes.size()); for (const auto* node : control_ret_nodes) control_ret_node_names->push_back(node->name()); *control_rets_updated = true; return Status::OK(); } MlirV1CompatOptimizationPassRegistry& MlirV1CompatOptimizationPassRegistry::Global() { static auto* global = new MlirV1CompatOptimizationPassRegistry(); return *global; } Status MlirV1CompatGraphOptimizationPass::Run( const GraphOptimizationPassOptions& options) { // Skip function graphs as MlirOptimizationPassRegistry_ will be used instead. if (options.is_function_graph) return Status::OK(); // Skip conversion from Graph to MLIR if none of the passes are enabled. const bool is_enabled = absl::c_any_of(registry_->passes(), [&](auto& pass_registration) -> bool { return pass_registration.pass->IsEnabled( options.session_options->config); }); if (!is_enabled) { VLOG(1) << "None of the MLIR optimization passes are enabled " << "(registered" << registry_->passes().size() << " passes)"; return Status::OK(); } VLOG(1) << "Running MLIR Graph Optimization V1 Compat Passes " << "(registered" << registry_->passes().size() << " passes)"; GraphDebugInfo debug_info; RegisterDialects(); mlir::MLIRContext context; GraphImportConfig import_config; // TODO(b/150959075): Running functionalization before TPU cluster formation // is not semantics preserving and should be disabled for now. import_config.upgrade_legacy = false; TF_ASSIGN_OR_RETURN( auto module_ref, ConvertGraphToMlir(**options.graph, debug_info, *options.flib_def, import_config, &context)); AddDevicesToOp(*module_ref, options.device_set); for (auto& pass_registration : registry_->passes()) { llvm::StringRef name = pass_registration.pass->name(); VLOG(2) << "Run MLIR graph optimization pass: " << StringRefToView(name); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_before_", name)); } TF_RETURN_IF_ERROR(pass_registration.pass->Run(options, *module_ref)); if (VLOG_IS_ON(1)) { DumpModule(*module_ref, llvm::formatv("mlir_{0}_after_", name)); } } GraphExportConfig export_config; TF_RETURN_WITH_CONTEXT_IF_ERROR( ConvertMlirToGraph(*module_ref, export_config, options.graph, options.flib_def), "Error converting MLIR module back to graph"); return Status::OK(); } } // namespace tensorflow
Enable 'upgrade_legacy' for MlirFunctionOptimizationPass
Enable 'upgrade_legacy' for MlirFunctionOptimizationPass This change enables functionalization of v1 control flow to v2 control flow in the beginning of the MlirFunctionOptimizationPass. This avoids v1 control flow in the MLIR-based TPU bridge which is not well supported yet. PiperOrigin-RevId: 307101482 Change-Id: I66cbaf74a5aeef3dc10d664379cbd3b39581d8a1
C++
apache-2.0
paolodedios/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,Intel-tensorflow/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,annarev/tensorflow,annarev/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,sarvex/tensorflow,sarvex/tensorflow,karllessard/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,annarev/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,annarev/tensorflow,aldian/tensorflow,Intel-tensorflow/tensorflow,davidzchen/tensorflow,cxxgtxy/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,annarev/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,paolodedios/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,gautam1858/tensorflow,aldian/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,aldian/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,aldian/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,petewarden/tensorflow,frreiss/tensorflow-fred,aldian/tensorflow,annarev/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,frreiss/tensorflow-fred,frreiss/tensorflow-fred,cxxgtxy/tensorflow,cxxgtxy/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,annarev/tensorflow,sarvex/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aam-at/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,aldian/tensorflow,gautam1858/tensorflow,aldian/tensorflow,petewarden/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,petewarden/tensorflow,aldian/tensorflow,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow
3aea890bb52e233d6b3d67d71aa528d13fc39f64
hestonBarrier/hestonBarrier.cpp
hestonBarrier/hestonBarrier.cpp
/* ====================================================== Copyright 2016 Liang Ma 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. ====================================================== *---------------------------------------------------------------------------- * * Author: Liang Ma ([email protected]) * * Top function is defined here with interface specified as axi4. * It creates an object of heston and launches the simulation. * *---------------------------------------------------------------------------- */ #include "hestonBarrier.h" void hestonEuroBarrier(data_t *pCall, data_t *pPut, // call price and put price data_t expect, // theta data_t kappa, // kappa data_t variance, // xi data_t correlation, // rho data_t timeT, // time period of options data_t freeRate, // interest rate of the riskless asset data_t volatility, // volatility of the risky asset data_t initPrice, // stock price at time 0 data_t strikePrice, // strike price data_t upB, // up barrier data_t lowB, // low barrier int num_sims) { #pragma HLS INTERFACE m_axi port=pCall bundle=gmem #pragma HLS INTERFACE s_axilite port=pCall bundle=control #pragma HLS INTERFACE m_axi port=pPut bundle=gmem #pragma HLS INTERFACE s_axilite port=pPut bundle=control #pragma HLS INTERFACE s_axilite port=correlation bundle=gmem #pragma HLS INTERFACE s_axilite port=correlation bundle=control #pragma HLS INTERFACE s_axilite port=variance bundle=gmem #pragma HLS INTERFACE s_axilite port=variance bundle=control #pragma HLS INTERFACE s_axilite port=kappa bundle=gmem #pragma HLS INTERFACE s_axilite port=kappa bundle=control #pragma HLS INTERFACE s_axilite port=expect bundle=gmem #pragma HLS INTERFACE s_axilite port=expect bundle=control #pragma HLS INTERFACE s_axilite port=timeT bundle=gmem #pragma HLS INTERFACE s_axilite port=timeT bundle=control #pragma HLS INTERFACE s_axilite port=freeRate bundle=gmem #pragma HLS INTERFACE s_axilite port=freeRate bundle=control #pragma HLS INTERFACE s_axilite port=volatility bundle=gmem #pragma HLS INTERFACE s_axilite port=volatility bundle=control #pragma HLS INTERFACE s_axilite port=initPrice bundle=gmem #pragma HLS INTERFACE s_axilite port=initPrice bundle=control #pragma HLS INTERFACE s_axilite port=strikePrice bundle=gmem #pragma HLS INTERFACE s_axilite port=strikePrice bundle=control #pragma HLS INTERFACE s_axilite port=lowB bundle=gmem #pragma HLS INTERFACE s_axilite port=lowB bundle=control #pragma HLS INTERFACE s_axilite port=upB bundle=gmem #pragma HLS INTERFACE s_axilite port=upB bundle=control #pragma HLS INTERFACE s_axilite port=num_sims bundle=gmem #pragma HLS INTERFACE s_axilite port=num_sims bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control volData vol(expect,kappa,variance,volatility,correlation); stockData sd(timeT,freeRate,volatility,initPrice,strikePrice); barrierData bD(upB,lowB); heston bs(sd,vol,bD); data_t call,put; bs.simulation(&call,&put,num_sims); *pCall=call; *pPut=put; return; } const int heston::NUM_RNGS=2; const int heston::NUM_SIMGROUPS=64; const int heston::NUM_STEPS=64; heston::heston(stockData data,volData vol,barrierData bData) :data(data),vol(vol),bData(bData) { } void heston::simulation(data_t* pCall, data_t *pPut, int num_sims) { RNG mt_rng[NUM_RNGS]; #pragma HLS ARRAY_PARTITION variable=mt_rng complete dim=1 uint seeds[NUM_RNGS]; #pragma HLS ARRAY_PARTITION variable=seeds complete dim=1 loop_seed:for(int i=0;i<NUM_RNGS;i++) { #pragma HLS UNROLL seeds[i]=i; } RNG::init_array(mt_rng,seeds,NUM_RNGS); return sampleSIM(mt_rng,pCall,pPut,num_sims); } void heston::sampleSIM(RNG* mt_rng, data_t* call,data_t* put,int num_sims) { const data_t Dt=data.timeT/NUM_STEPS, ratio1=expf(-data.freeRate*data.timeT), ratio2=sqrtf(fmaxf(1-vol.correlation*vol.correlation,0)), ratio3=Dt*data.freeRate, ratio4=vol.kappa*vol.expect*Dt, volInit =fmaxf(vol.initValue,0)*Dt; data_t fCall=0,fPut=0; data_t sCall[NUM_RNGS],sPut[NUM_RNGS]; #pragma HLS ARRAY_PARTITION variable=sCall complete dim=1 #pragma HLS ARRAY_PARTITION variable=sPut complete dim=1 data_t stockPrice[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=stockPrice complete dim=1 data_t vols[NUM_RNGS][NUM_SIMGROUPS],pVols[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=vols complete dim=1 #pragma HLS ARRAY_PARTITION variable=pVols complete dim=1 data_t num1[NUM_RNGS][NUM_SIMGROUPS],num2[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=num2 complete dim=1 #pragma HLS ARRAY_PARTITION variable=num1 complete dim=1 data_t bBarrier[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=bBarrier complete dim=1 for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL sCall[i]=0; sPut[i]=0; } loop_init:for(int s=0;s<NUM_SIMGROUPS;s++) { for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL stockPrice[i][s]=data.initPrice; vols[i][s]=vol.initValue; pVols[i][s]=volInit; bBarrier[i][s]=true; } } loop_main:for(int j=0;j<num_sims;j++) { loop_path:for(int path=0;path<NUM_STEPS;path++) { loop_share:for(int s=0;s<NUM_SIMGROUPS;s++) { #pragma HLS PIPELINE loop_parallel:for(uint i=0;i<NUM_RNGS;i++) { #pragma HLS UNROLL if(!bBarrier[i][s]) continue; mt_rng[i].BOX_MULLER(&num1[i][s],&num2[i][s],pVols[i][s]); stockPrice[i][s]*=expf(ratio3-pVols[i][s]*0.5f+num1[i][s]*vol.correlation+num2[i][s]*ratio2); if(stockPrice[i][s]<bData.downBarrier || stockPrice[i][s]>bData.upBarrier) { bBarrier[i][s]=false; } vols[i][s]+=ratio4-vol.kappa*pVols[i][s]+vol.variance*num1[i][s]; pVols[i][s]=fmaxf(vols[i][s],0)*Dt; } } } loop_sum:for(int s=0;s<NUM_SIMGROUPS;s++) { loop_sum_R:for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL vols[i][s]=vol.initValue; pVols[i][s]=volInit; if(bBarrier[i][s]) { if(stockPrice[i][s]>data.strikePrice) { sCall[i]+=stockPrice[i][s]-data.strikePrice; } else { sPut[i]+=data.strikePrice-stockPrice[i][s]; } } stockPrice[i][s]=data.initPrice; bBarrier[i][s]=true; } } } loop_final_sum:for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL fCall+=sCall[i]; fPut+=sPut[i]; } *call= ratio1*fCall/NUM_RNGS/num_sims/NUM_SIMGROUPS; *put= ratio1*fPut/NUM_RNGS/num_sims/NUM_SIMGROUPS; }
/* ====================================================== Copyright 2016 Liang Ma 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. ====================================================== *---------------------------------------------------------------------------- * * Author: Liang Ma ([email protected]) * * Top function is defined here with interface specified as axi4. * It creates an object of heston and launches the simulation. * *---------------------------------------------------------------------------- */ #include "hestonBarrier.h" void hestonEuroBarrier(data_t *pCall, data_t *pPut, // call price and put price data_t expect, // theta data_t kappa, // kappa data_t variance, // xi data_t correlation, // rho data_t timeT, // time period of options data_t freeRate, // interest rate of the riskless asset data_t volatility, // volatility of the risky asset data_t initPrice, // stock price at time 0 data_t strikePrice, // strike price data_t upB, // up barrier data_t lowB, // low barrier int num_sims) { #pragma HLS INTERFACE m_axi port=pCall bundle=gmem #pragma HLS INTERFACE s_axilite port=pCall bundle=control #pragma HLS INTERFACE m_axi port=pPut bundle=gmem #pragma HLS INTERFACE s_axilite port=pPut bundle=control #pragma HLS INTERFACE s_axilite port=correlation bundle=gmem #pragma HLS INTERFACE s_axilite port=correlation bundle=control #pragma HLS INTERFACE s_axilite port=variance bundle=gmem #pragma HLS INTERFACE s_axilite port=variance bundle=control #pragma HLS INTERFACE s_axilite port=kappa bundle=gmem #pragma HLS INTERFACE s_axilite port=kappa bundle=control #pragma HLS INTERFACE s_axilite port=expect bundle=gmem #pragma HLS INTERFACE s_axilite port=expect bundle=control #pragma HLS INTERFACE s_axilite port=timeT bundle=gmem #pragma HLS INTERFACE s_axilite port=timeT bundle=control #pragma HLS INTERFACE s_axilite port=freeRate bundle=gmem #pragma HLS INTERFACE s_axilite port=freeRate bundle=control #pragma HLS INTERFACE s_axilite port=volatility bundle=gmem #pragma HLS INTERFACE s_axilite port=volatility bundle=control #pragma HLS INTERFACE s_axilite port=initPrice bundle=gmem #pragma HLS INTERFACE s_axilite port=initPrice bundle=control #pragma HLS INTERFACE s_axilite port=strikePrice bundle=gmem #pragma HLS INTERFACE s_axilite port=strikePrice bundle=control #pragma HLS INTERFACE s_axilite port=lowB bundle=gmem #pragma HLS INTERFACE s_axilite port=lowB bundle=control #pragma HLS INTERFACE s_axilite port=upB bundle=gmem #pragma HLS INTERFACE s_axilite port=upB bundle=control #pragma HLS INTERFACE s_axilite port=num_sims bundle=gmem #pragma HLS INTERFACE s_axilite port=num_sims bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control volData vol(expect,kappa,variance,volatility,correlation); stockData sd(timeT,freeRate,volatility,initPrice,strikePrice); barrierData bD(upB,lowB); heston bs(sd,vol,bD); data_t call,put; bs.simulation(&call,&put,num_sims); *pCall=call; *pPut=put; return; } const int heston::NUM_RNGS=2; const int heston::NUM_SIMGROUPS=64; const int heston::NUM_STEPS=64; heston::heston(stockData data,volData vol,barrierData bData) :data(data),vol(vol),bData(bData) { } void heston::simulation(data_t* pCall, data_t *pPut, int num_sims) { RNG mt_rng[NUM_RNGS]; #pragma HLS ARRAY_PARTITION variable=mt_rng complete dim=1 uint seeds[NUM_RNGS]; #pragma HLS ARRAY_PARTITION variable=seeds complete dim=1 loop_seed:for(int i=0;i<NUM_RNGS;i++) { #pragma HLS UNROLL seeds[i]=i; } RNG::init_array(mt_rng,seeds,NUM_RNGS); return sampleSIM(mt_rng,pCall,pPut,num_sims); } void heston::sampleSIM(RNG* mt_rng, data_t* call,data_t* put,int num_sims) { const data_t Dt=data.timeT/NUM_STEPS, ratio1=expf(-data.freeRate*data.timeT), ratio2=sqrtf(fmaxf(1-vol.correlation*vol.correlation,0)), ratio3=Dt*data.freeRate, ratio4=vol.kappa*vol.expect*Dt, volInit =fmaxf(vol.initValue,0)*Dt; data_t fCall=0,fPut=0; data_t sCall[NUM_RNGS],sPut[NUM_RNGS]; #pragma HLS ARRAY_PARTITION variable=sCall complete dim=1 #pragma HLS ARRAY_PARTITION variable=sPut complete dim=1 data_t stockPrice[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=stockPrice complete dim=1 data_t vols[NUM_RNGS][NUM_SIMGROUPS],pVols[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=vols complete dim=1 #pragma HLS ARRAY_PARTITION variable=pVols complete dim=1 data_t num1[NUM_RNGS][NUM_SIMGROUPS],num2[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=num2 complete dim=1 #pragma HLS ARRAY_PARTITION variable=num1 complete dim=1 data_t bBarrier[NUM_RNGS][NUM_SIMGROUPS]; #pragma HLS ARRAY_PARTITION variable=bBarrier complete dim=1 for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL sCall[i]=0; sPut[i]=0; } loop_init:for(int s=0;s<NUM_SIMGROUPS;s++) { for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL stockPrice[i][s]=data.initPrice; vols[i][s]=vol.initValue; pVols[i][s]=volInit; bBarrier[i][s]=true; } } loop_main:for(int j=0;j<num_sims;j++) { loop_path:for(int path=0;path<NUM_STEPS;path++) { loop_share:for(int s=0;s<NUM_SIMGROUPS;s++) { #pragma HLS PIPELINE loop_parallel:for(uint i=0;i<NUM_RNGS;i++) { #pragma HLS UNROLL if(!bBarrier[i][s]) continue; mt_rng[i].BOX_MULLER(&num1[i][s],&num2[i][s],pVols[i][s]); stockPrice[i][s]*=expf(ratio3-pVols[i][s]*0.5f+num1[i][s]*vol.correlation+num2[i][s]*ratio2); if(stockPrice[i][s]<bData.downBarrier || stockPrice[i][s]>bData.upBarrier) { bBarrier[i][s]=false; } vols[i][s]+=ratio4-vol.kappa*pVols[i][s]+vol.variance*num1[i][s]; pVols[i][s]=fmaxf(vols[i][s],0)*Dt; } } } loop_sum:for(int s=0;s<NUM_SIMGROUPS;s++) { loop_sum_R:for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL vols[i][s]=vol.initValue; pVols[i][s]=volInit; if(bBarrier[i][s]) { float payoff = stockPrice[i][s]-data.strikePrice; if(stockPrice[i][s]>data.strikePrice) { sCall[i]+= payoff; } else { sPut[i]-=payoff; } } stockPrice[i][s]=data.initPrice; bBarrier[i][s]=true; } } } loop_final_sum:for(int i =0;i<NUM_RNGS;i++) { #pragma HLS UNROLL fCall+=sCall[i]; fPut+=sPut[i]; } *call= ratio1*fCall/NUM_RNGS/num_sims/NUM_SIMGROUPS; *put= ratio1*fPut/NUM_RNGS/num_sims/NUM_SIMGROUPS; }
reduce branch resouce utilization
reduce branch resouce utilization
C++
apache-2.0
KitAway/HestonModel_MonteCarlo
d23bcd8eb62c9634c9892be3883be0d0271503f9
src/tests/gl_tests/WebGLReadOutsideFramebufferTest.cpp
src/tests/gl_tests/WebGLReadOutsideFramebufferTest.cpp
// // Copyright 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // WebGLReadOutsideFramebufferTest.cpp : Test functions which read the framebuffer (readPixels, // copyTexSubImage2D, copyTexImage2D) on areas outside the framebuffer. #include "test_utils/ANGLETest.h" #include "test_utils/gl_raii.h" namespace { class PixelRect { public: PixelRect(int width, int height) : mWidth(width), mHeight(height), mData(width * height) {} // Set each pixel to a different color consisting of the x,y position and a given tag. // Making each pixel a different means any misplaced pixel will cause a failure. // Encoding the position proved valuable in debugging. void fill(unsigned tag) { for (int x = 0; x < mWidth; ++x) { for (int y = 0; y < mHeight; ++y) { mData[x + y * mWidth] = angle::GLColor(x + (y << 8) + (tag << 16)); } } } void setPixel(GLubyte x, GLubyte y, GLubyte z, GLubyte w) { mData[x + y * mWidth] = angle::GLColor(x, y, z, w); } void toTexture2D(GLuint texid) const { glBindTexture(GL_TEXTURE_2D, texid); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } void toTexture3D(GLuint texid, GLint depth) const { glBindTexture(GL_TEXTURE_3D, texid); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, mWidth, mHeight, depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); for (GLint z = 0; z < depth; z++) { glTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, z, mWidth, mHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); } void readFB(int x, int y) { glReadPixels(x, y, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } // Read pixels from 'other' into 'this' from position (x,y). // Pixels outside 'other' are untouched or zeroed according to 'zeroOutside.' void readPixelRect(const PixelRect &other, int x, int y, bool zeroOutside) { for (int i = 0; i < mWidth; ++i) { for (int j = 0; j < mHeight; ++j) { angle::GLColor *dest = &mData[i + j * mWidth]; if (!other.getPixel(x + i, y + j, dest) && zeroOutside) { *dest = angle::GLColor(0); } } } } bool getPixel(int x, int y, angle::GLColor *colorOut) const { if (0 <= x && x < mWidth && 0 <= y && y < mHeight) { *colorOut = mData[x + y * mWidth]; return true; } return false; } void compare(const PixelRect &expected) const { ASSERT_EQ(mWidth, expected.mWidth); ASSERT_EQ(mHeight, expected.mHeight); for (int x = 0; x < mWidth; ++x) { for (int y = 0; y < mHeight; ++y) { ASSERT_EQ(expected.mData[x + y * mWidth], mData[x + y * mWidth]) << "at (" << x << ", " << y << ")"; } } } private: int mWidth, mHeight; std::vector<angle::GLColor> mData; }; } // namespace namespace angle { class WebGLReadOutsideFramebufferTest : public ANGLETest { public: // Read framebuffer to 'pixelsOut' via glReadPixels. void TestReadPixels(int x, int y, int, PixelRect *pixelsOut) { pixelsOut->readFB(x, y); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage2D. void TestCopyTexSubImage2D(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, x, y, kReadWidth, kReadHeight); readTexture2D(kReadWidth, kReadHeight, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage3D. void TestCopyTexSubImage3D(int x, int y, int z, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture3D(destTexture.get(), kTextureDepth); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, z, x, y, kReadWidth, kReadHeight); readTexture3D(destTexture, kReadWidth, kReadHeight, z, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexImage2D. void TestCopyTexImage2D(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, kReadWidth, kReadHeight, 0); readTexture2D(kReadWidth, kReadHeight, pixelsOut); } protected: static constexpr int kFbWidth = 128; static constexpr int kFbHeight = 128; static constexpr int kTextureDepth = 16; static constexpr int kReadWidth = 4; static constexpr int kReadHeight = 4; static constexpr int kReadLayer = 2; // Tag the framebuffer pixels differently than the initial read buffer pixels, so we know for // sure which pixels are changed by reading. static constexpr GLuint fbTag = 0x1122; static constexpr GLuint readTag = 0xaabb; WebGLReadOutsideFramebufferTest() : mFBData(kFbWidth, kFbHeight) { setWindowWidth(kFbWidth); setWindowHeight(kFbHeight); setConfigRedBits(8); setConfigGreenBits(8); setConfigBlueBits(8); setConfigAlphaBits(8); setWebGLCompatibilityEnabled(true); } void SetUp() override { ANGLETest::SetUp(); // TODO(fjhenigman): Factor out this shader and others like it in other tests, into // ANGLETest. const std::string vertexShader = "attribute vec3 a_position;\n" "varying vec2 v_texCoord;\n" "void main() {\n" " v_texCoord = a_position.xy * 0.5 + 0.5;\n" " gl_Position = vec4(a_position, 1);\n" "}\n"; const std::string fragmentShader = "precision mediump float;\n" "varying vec2 v_texCoord;\n" "uniform sampler2D u_texture;\n" "void main() {\n" " gl_FragColor = texture2D(u_texture, v_texCoord);\n" "}\n"; mProgram = CompileProgram(vertexShader, fragmentShader); glUseProgram(mProgram); GLint uniformLoc = glGetUniformLocation(mProgram, "u_texture"); ASSERT_NE(-1, uniformLoc); glUniform1i(uniformLoc, 0); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); // fill framebuffer with unique pixels mFBData.fill(fbTag); GLTexture fbTexture; mFBData.toTexture2D(fbTexture.get()); drawQuad(mProgram, "a_position", 0.0f, 1.0f, true); } void TearDown() override { glDeleteProgram(mProgram); ANGLETest::TearDown(); } using TestFunc = void (WebGLReadOutsideFramebufferTest::*)(int x, int y, int z, PixelRect *dest); void Main2D(TestFunc testFunc, bool zeroOutside) { mainImpl(testFunc, zeroOutside, 0); } void Main3D(TestFunc testFunc, bool zeroOutside) { mainImpl(testFunc, zeroOutside, kReadLayer); } void mainImpl(TestFunc testFunc, bool zeroOutside, int readLayer) { PixelRect actual(kReadWidth, kReadHeight); PixelRect expected(kReadWidth, kReadHeight); // Read a kReadWidth*kReadHeight rectangle of pixels from places that include: // - completely outside framebuffer, on all sides of it (i,j < 0 or > 2) // - completely inside framebuffer (i,j == 1) // - straddling framebuffer boundary, at each corner and side for (int i = -1; i < 4; ++i) { for (int j = -1; j < 4; ++j) { int x = i * kFbWidth / 2 - kReadWidth / 2; int y = j * kFbHeight / 2 - kReadHeight / 2; // Put unique pixel values into the read destinations. actual.fill(readTag); expected.readPixelRect(actual, 0, 0, false); // Read from framebuffer into 'actual.' glBindFramebuffer(GL_FRAMEBUFFER, 0); (this->*testFunc)(x, y, readLayer, &actual); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Simulate framebuffer read, into 'expected.' expected.readPixelRect(mFBData, x, y, zeroOutside); // See if they are the same. actual.compare(expected); } } } // Get contents of current texture by drawing it into a framebuffer then reading with // glReadPixels(). void readTexture2D(GLsizei width, GLsizei height, PixelRect *out) { GLRenderbuffer colorBuffer; glBindRenderbuffer(GL_RENDERBUFFER, colorBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height); GLFramebuffer fbo; glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorBuffer.get()); glViewport(0, 0, width, height); drawQuad(mProgram, "a_position", 0.0f, 1.0f, true); out->readFB(0, 0); } // Get contents of current texture by drawing it into a framebuffer then reading with // glReadPixels(). void readTexture3D(GLuint texture, GLsizei width, GLsizei height, int zSlice, PixelRect *out) { GLFramebuffer fbo; glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture, 0, zSlice); out->readFB(0, 0); } PixelRect mFBData; GLuint mProgram; }; class WebGL2ReadOutsideFramebufferTest : public WebGLReadOutsideFramebufferTest { }; // TODO(fjhenigman): Enable each test as part of a CL that lets the test pass. // Check that readPixels does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, ReadPixels) { Main2D(&WebGLReadOutsideFramebufferTest::TestReadPixels, false); } // Check that copyTexSubImage2D does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, CopyTexSubImage2D) { // TODO(fjhenigman): Figure out why this fails on Win10 Intel OpenGL if (IsWindows() && IsIntel() && IsDesktopOpenGL()) { std::cout << "Test skipped on Windows OpenGL on Intel." << std::endl; return; } Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage2D, false); } // Check that copyTexImage2D sets (0,0,0,0) for pixels outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, CopyTexImage2D) { // TODO(fjhenigman): Figure out why this fails on Win10 Intel OpenGL if (IsWindows() && IsIntel() && IsDesktopOpenGL()) { std::cout << "Test skipped on Windows OpenGL on Intel." << std::endl; return; } Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexImage2D, true); } // Check that copyTexSubImage3D does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGL2ReadOutsideFramebufferTest, CopyTexSubImage3D) { if (IsDesktopOpenGL() || IsOpenGLES()) { std::cout << "Robust CopyTexSubImage3D behaviour is not implemented on OpenGL." << std::endl; return; } Main3D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage3D, false); } ANGLE_INSTANTIATE_TEST(WebGLReadOutsideFramebufferTest, ES2_D3D9(), ES2_D3D11(), ES3_D3D11(), ES2_D3D11_FL9_3(), ES2_OPENGL(), ES3_OPENGL(), ES2_OPENGLES(), ES3_OPENGLES()); ANGLE_INSTANTIATE_TEST(WebGL2ReadOutsideFramebufferTest, ES3_D3D11(), ES3_OPENGL(), ES2_OPENGLES(), ES3_OPENGLES()); } // namespace
// // Copyright 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // WebGLReadOutsideFramebufferTest.cpp : Test functions which read the framebuffer (readPixels, // copyTexSubImage2D, copyTexImage2D) on areas outside the framebuffer. #include "test_utils/ANGLETest.h" #include "test_utils/gl_raii.h" namespace { class PixelRect { public: PixelRect(int width, int height) : mWidth(width), mHeight(height), mData(width * height) {} // Set each pixel to a different color consisting of the x,y position and a given tag. // Making each pixel a different means any misplaced pixel will cause a failure. // Encoding the position proved valuable in debugging. void fill(unsigned tag) { for (int x = 0; x < mWidth; ++x) { for (int y = 0; y < mHeight; ++y) { mData[x + y * mWidth] = angle::GLColor(x + (y << 8) + (tag << 16)); } } } void toTexture2D(GLuint target, GLuint texid) const { glBindTexture(target, texid); if (target == GL_TEXTURE_CUBE_MAP) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } else { ASSERT(target == GL_TEXTURE_2D); glTexImage2D(target, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } void toTexture3D(GLuint texid, GLint depth) const { glBindTexture(GL_TEXTURE_3D, texid); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, mWidth, mHeight, depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); for (GLint z = 0; z < depth; z++) { glTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, z, mWidth, mHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); } void readFB(int x, int y) { glReadPixels(x, y, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } // Read pixels from 'other' into 'this' from position (x,y). // Pixels outside 'other' are untouched or zeroed according to 'zeroOutside.' void readPixelRect(const PixelRect &other, int x, int y, bool zeroOutside) { for (int i = 0; i < mWidth; ++i) { for (int j = 0; j < mHeight; ++j) { angle::GLColor *dest = &mData[i + j * mWidth]; if (!other.getPixel(x + i, y + j, dest) && zeroOutside) { *dest = angle::GLColor(0); } } } } bool getPixel(int x, int y, angle::GLColor *colorOut) const { if (0 <= x && x < mWidth && 0 <= y && y < mHeight) { *colorOut = mData[x + y * mWidth]; return true; } return false; } void compare(const PixelRect &expected) const { ASSERT_EQ(mWidth, expected.mWidth); ASSERT_EQ(mHeight, expected.mHeight); for (int x = 0; x < mWidth; ++x) { for (int y = 0; y < mHeight; ++y) { ASSERT_EQ(expected.mData[x + y * mWidth], mData[x + y * mWidth]) << "at (" << x << ", " << y << ")"; } } } private: int mWidth, mHeight; std::vector<angle::GLColor> mData; }; } // namespace namespace angle { class WebGLReadOutsideFramebufferTest : public ANGLETest { public: // Read framebuffer to 'pixelsOut' via glReadPixels. void TestReadPixels(int x, int y, int, PixelRect *pixelsOut) { pixelsOut->readFB(x, y); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage2D and GL_TEXTURE_2D. void TestCopyTexSubImage2D(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_2D, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, x, y, kReadWidth, kReadHeight); readTexture2D(GL_TEXTURE_2D, destTexture.get(), kReadWidth, kReadHeight, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage2D and cube map. void TestCopyTexSubImageCube(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_CUBE_MAP, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, 0, 0, x, y, kReadWidth, kReadHeight); readTexture2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, destTexture.get(), kReadWidth, kReadHeight, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage3D. void TestCopyTexSubImage3D(int x, int y, int z, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture3D(destTexture.get(), kTextureDepth); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, z, x, y, kReadWidth, kReadHeight); readTexture3D(destTexture, kReadWidth, kReadHeight, z, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexImage2D and GL_TEXTURE_2D. void TestCopyTexImage2D(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_2D, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, kReadWidth, kReadHeight, 0); readTexture2D(GL_TEXTURE_2D, destTexture.get(), kReadWidth, kReadHeight, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexImage2D and cube map. void TestCopyTexImageCube(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_CUBE_MAP, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, x, y, kReadWidth, kReadHeight, 0); readTexture2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, destTexture, kReadWidth, kReadHeight, pixelsOut); } protected: static constexpr int kFbWidth = 128; static constexpr int kFbHeight = 128; static constexpr int kTextureDepth = 16; static constexpr int kReadWidth = 4; static constexpr int kReadHeight = 4; static constexpr int kReadLayer = 2; // Tag the framebuffer pixels differently than the initial read buffer pixels, so we know for // sure which pixels are changed by reading. static constexpr GLuint fbTag = 0x1122; static constexpr GLuint readTag = 0xaabb; WebGLReadOutsideFramebufferTest() : mFBData(kFbWidth, kFbHeight) { setWindowWidth(kFbWidth); setWindowHeight(kFbHeight); setConfigRedBits(8); setConfigGreenBits(8); setConfigBlueBits(8); setConfigAlphaBits(8); setWebGLCompatibilityEnabled(true); } void SetUp() override { ANGLETest::SetUp(); // TODO(fjhenigman): Factor out this shader and others like it in other tests, into // ANGLETest. const std::string vertexShader = "attribute vec3 a_position;\n" "varying vec2 v_texCoord;\n" "void main() {\n" " v_texCoord = a_position.xy * 0.5 + 0.5;\n" " gl_Position = vec4(a_position, 1);\n" "}\n"; const std::string fragmentShader = "precision mediump float;\n" "varying vec2 v_texCoord;\n" "uniform sampler2D u_texture;\n" "void main() {\n" " gl_FragColor = texture2D(u_texture, v_texCoord);\n" "}\n"; mProgram = CompileProgram(vertexShader, fragmentShader); glUseProgram(mProgram); GLint uniformLoc = glGetUniformLocation(mProgram, "u_texture"); ASSERT_NE(-1, uniformLoc); glUniform1i(uniformLoc, 0); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); // fill framebuffer with unique pixels mFBData.fill(fbTag); GLTexture fbTexture; mFBData.toTexture2D(GL_TEXTURE_2D, fbTexture); drawQuad(mProgram, "a_position", 0.0f, 1.0f, true); } void TearDown() override { glDeleteProgram(mProgram); ANGLETest::TearDown(); } using TestFunc = void (WebGLReadOutsideFramebufferTest::*)(int x, int y, int z, PixelRect *dest); void Main2D(TestFunc testFunc, bool zeroOutside) { mainImpl(testFunc, zeroOutside, 0); } void Main3D(TestFunc testFunc, bool zeroOutside) { mainImpl(testFunc, zeroOutside, kReadLayer); } void mainImpl(TestFunc testFunc, bool zeroOutside, int readLayer) { PixelRect actual(kReadWidth, kReadHeight); PixelRect expected(kReadWidth, kReadHeight); // Read a kReadWidth*kReadHeight rectangle of pixels from places that include: // - completely outside framebuffer, on all sides of it (i,j < 0 or > 2) // - completely inside framebuffer (i,j == 1) // - straddling framebuffer boundary, at each corner and side for (int i = -1; i < 4; ++i) { for (int j = -1; j < 4; ++j) { int x = i * kFbWidth / 2 - kReadWidth / 2; int y = j * kFbHeight / 2 - kReadHeight / 2; // Put unique pixel values into the read destinations. actual.fill(readTag); expected.readPixelRect(actual, 0, 0, false); // Read from framebuffer into 'actual.' glBindFramebuffer(GL_FRAMEBUFFER, 0); (this->*testFunc)(x, y, readLayer, &actual); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Simulate framebuffer read, into 'expected.' expected.readPixelRect(mFBData, x, y, zeroOutside); // See if they are the same. actual.compare(expected); } } } // Get contents of given texture by drawing it into a framebuffer then reading with // glReadPixels(). void readTexture2D(GLuint target, GLuint texture, GLsizei width, GLsizei height, PixelRect *out) { GLFramebuffer fbo; glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target, texture, 0); out->readFB(0, 0); } // Get contents of current texture by drawing it into a framebuffer then reading with // glReadPixels(). void readTexture3D(GLuint texture, GLsizei width, GLsizei height, int zSlice, PixelRect *out) { GLFramebuffer fbo; glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture, 0, zSlice); out->readFB(0, 0); } PixelRect mFBData; GLuint mProgram; }; class WebGL2ReadOutsideFramebufferTest : public WebGLReadOutsideFramebufferTest { }; // Check that readPixels does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, ReadPixels) { Main2D(&WebGLReadOutsideFramebufferTest::TestReadPixels, false); } // Check that copyTexSubImage2D does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, CopyTexSubImage2D) { // TODO(fjhenigman): Figure out why this fails on Win10 Intel OpenGL if (IsWindows() && IsIntel() && IsDesktopOpenGL()) { std::cout << "Test skipped on Windows OpenGL on Intel." << std::endl; return; } Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage2D, false); // TODO(fjhenigman): Enable this test as part of a CL that lets the test pass. //Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImageCube, false); } // Check that copyTexImage2D sets (0,0,0,0) for pixels outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, CopyTexImage2D) { // TODO(fjhenigman): Figure out why this fails on Win10 Intel OpenGL if (IsWindows() && IsIntel() && IsDesktopOpenGL()) { std::cout << "Test skipped on Windows OpenGL on Intel." << std::endl; return; } Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexImage2D, true); // TODO(fjhenigman): Enable this test as part of a CL that lets the test pass. //Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexImageCube, true); } // Check that copyTexSubImage3D does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGL2ReadOutsideFramebufferTest, CopyTexSubImage3D) { if (IsDesktopOpenGL() || IsOpenGLES()) { std::cout << "Robust CopyTexSubImage3D behaviour is not implemented on OpenGL." << std::endl; return; } Main3D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage3D, false); } ANGLE_INSTANTIATE_TEST(WebGLReadOutsideFramebufferTest, ES2_D3D9(), ES2_D3D11(), ES3_D3D11(), ES2_D3D11_FL9_3(), ES2_OPENGL(), ES3_OPENGL(), ES2_OPENGLES(), ES3_OPENGLES()); ANGLE_INSTANTIATE_TEST(WebGL2ReadOutsideFramebufferTest, ES3_D3D11(), ES3_OPENGL(), ES2_OPENGLES(), ES3_OPENGLES()); } // namespace
Add cube map to read-outside-framebuffer tests.
Add cube map to read-outside-framebuffer tests. Cube maps go through a separate path on D3D so we need to test them. BUG=angleproject:1815 Change-Id: Ifb7a85d7e2750f25bce382fdd7a00062d23b3573 Reviewed-on: https://chromium-review.googlesource.com/597213 Commit-Queue: Frank Henigman <[email protected]> Reviewed-by: Geoff Lang <[email protected]>
C++
bsd-3-clause
ecoal95/angle,MSOpenTech/angle,MSOpenTech/angle,ecoal95/angle,ppy/angle,ppy/angle,ppy/angle,ecoal95/angle,ppy/angle,ecoal95/angle,MSOpenTech/angle,MSOpenTech/angle,ecoal95/angle
d4fbe99f615fc7860b39c44517bc0433db5d3eaf
OutputPartInstancerNode.C
OutputPartInstancerNode.C
#include "OutputPartInstancerNode.h" #include <maya/MFnTypedAttribute.h> #include <maya/MFnArrayAttrsData.h> #include <maya/MArrayDataBuilder.h> #include <maya/MFnPointArrayData.h> #include <maya/MPointArray.h> #include <maya/MIntArray.h> #include <maya/MFnIntArrayData.h> #include "MayaTypeID.h" #include "hapiutil.h" #include "util.h" MString OutputPartInstancerNode::typeName( "houdiniOutputPartInstancer" ); MTypeId OutputPartInstancerNode::typeId( MayaTypeID_HoudiniOutputPartInstancerNode ); MObject OutputPartInstancerNode::pointData; MObject OutputPartInstancerNode::storablePositions; MObject OutputPartInstancerNode::storableRotations; MObject OutputPartInstancerNode::storableScales; MObject OutputPartInstancerNode::storableObjectIndices; void* OutputPartInstancerNode::creator() { return new OutputPartInstancerNode(); } MStatus OutputPartInstancerNode::initialize() { MFnTypedAttribute tAttr; // pointData will be connected between the asset node and instancer.inputPoints OutputPartInstancerNode::pointData = tAttr.create( "pointData", "pd", MFnData::kDynArrayAttrs ); tAttr.setReadable( true ); tAttr.setWritable( true ); tAttr.setConnectable( true ); tAttr.setHidden( false ); addAttribute( OutputPartInstancerNode::pointData ); // The storable attrs for the parts of pointData that we want to persist // OutputPartInstancerNode::storablePositions = tAttr.create( "storablePositions", "storablePositions", MFnData::kPointArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storablePositions ); OutputPartInstancerNode::storableRotations = tAttr.create( "storableRotations", "storableRotations", MFnData::kPointArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storableRotations ); OutputPartInstancerNode::storableScales = tAttr.create( "storableScales", "storableScales", MFnData::kPointArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storableScales ); OutputPartInstancerNode::storableObjectIndices = tAttr.create( "storableObjectIndices", "storableObjectIndices", MFnData::kIntArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storableObjectIndices ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storablePositions ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storableRotations ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storableScales ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storableObjectIndices ); return MStatus::kSuccess; } OutputPartInstancerNode::OutputPartInstancerNode() { } OutputPartInstancerNode::~OutputPartInstancerNode() { } MStatus OutputPartInstancerNode::compute( const MPlug &plug, MDataBlock &dataBlock ) { MStatus status; if ( plug == OutputPartInstancerNode::pointData ) { if ( !plug.isDestination( &status ) ) { // in this case we should use the storeable data MDataHandle pointDataDataHandle = dataBlock.outputValue( plug, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject pointDataDataObj = pointDataDataHandle.data(); MFnArrayAttrsData pointDataFnArrayAttrs( pointDataDataObj, &status ); if ( pointDataDataObj.isNull() ) { pointDataDataObj = pointDataFnArrayAttrs.create( &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = pointDataDataHandle.setMObject( pointDataDataObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); pointDataDataObj = pointDataDataHandle.data(); status = pointDataFnArrayAttrs.setObject( pointDataDataObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); } // copy vector arrays MString attr[3] = { "position", "rotation", "scale" }; MObject attrObjs[3] = { OutputPartInstancerNode::storablePositions , OutputPartInstancerNode::storableRotations, OutputPartInstancerNode::storableScales }; for ( int i = 0; i < 3; ++i ) { MDataHandle storableHandle = dataBlock.inputValue( attrObjs[ i ], &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnPointArrayData storableFn( storableObj, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MVectorArray vectorArray = pointDataFnArrayAttrs.vectorArray( attr[ i ], &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); // convert points->vectors int nPoints = storableFn.length(); vectorArray.setLength( nPoints ); for ( int j = 0; j < nPoints; ++j ) { vectorArray.set( MVector( storableFn[ j ] ), j); } } // copy int array MDataHandle storableHandle = dataBlock.inputValue( OutputPartInstancerNode::storableObjectIndices, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnIntArrayData storableFn( storableObj, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MIntArray intArray = pointDataFnArrayAttrs.intArray( "objectIndex", &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = storableFn.copyTo( intArray ); pointDataDataHandle.setClean(); } } else if ( plug == OutputPartInstancerNode::storablePositions || plug == OutputPartInstancerNode::storableRotations || plug == OutputPartInstancerNode::storableScales || plug == OutputPartInstancerNode::storableObjectIndices ) { MDataHandle pointDataDataHandle = dataBlock.inputValue( OutputPartInstancerNode::pointData, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject pointDataDataObj = pointDataDataHandle.data(); MFnArrayAttrsData pointDataFnArrayAttrs( pointDataDataObj, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); if ( plug == OutputPartInstancerNode::storableObjectIndices ) { MFnArrayAttrsData::Type checkType( MFnArrayAttrsData::kIntArray ); bool exists = pointDataFnArrayAttrs.checkArrayExist( "objectIndex", checkType ); if ( exists ) { MIntArray arrayData = pointDataFnArrayAttrs.getIntData( "objectIndex", &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MDataHandle storableHandle = dataBlock.outputValue( plug, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnIntArrayData storableFn( storableObj, &status ); if ( storableObj.isNull() ) { storableObj = storableFn.create( &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = storableHandle.setMObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); storableObj = storableHandle.data(); status = storableFn.setObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); } status = storableFn.set( arrayData ); CHECK_MSTATUS_AND_RETURN_IT( status ); storableHandle.setClean(); } } else { MString outAttrName; if ( plug == OutputPartInstancerNode::storablePositions ) { outAttrName = "position"; } else if ( plug == OutputPartInstancerNode::storableRotations ) { outAttrName = "rotation"; } else outAttrName = "scale"; MFnArrayAttrsData::Type checkType( MFnArrayAttrsData::kVectorArray ); bool exists = pointDataFnArrayAttrs.checkArrayExist( outAttrName, checkType ); if ( exists ) { MVectorArray arrayData = pointDataFnArrayAttrs.getVectorData( outAttrName, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MDataHandle storableHandle = dataBlock.outputValue( plug, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnPointArrayData storableFn( storableObj, &status ); if ( storableObj.isNull() ) { storableObj = storableFn.create( &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = storableHandle.setMObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); storableObj = storableHandle.data(); status = storableFn.setObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); } // Convert vectors -> points unsigned int numElems = arrayData.length(); MPointArray tempPointArray; tempPointArray.setLength( numElems ); for ( unsigned int i = 0; i < numElems; ++i ) { status = tempPointArray.set( MPoint( arrayData[ i ] ), i ); } status = storableFn.set( tempPointArray ); CHECK_MSTATUS_AND_RETURN_IT( status ); storableHandle.setClean(); } } return status; } return MPxNode::compute( plug, dataBlock ); }
#include "OutputPartInstancerNode.h" #include <maya/MFnTypedAttribute.h> #include <maya/MFnArrayAttrsData.h> #include <maya/MArrayDataBuilder.h> #include <maya/MFnVectorArrayData.h> #include <maya/MPointArray.h> #include <maya/MIntArray.h> #include <maya/MFnIntArrayData.h> #include "MayaTypeID.h" #include "hapiutil.h" #include "util.h" MString OutputPartInstancerNode::typeName( "houdiniOutputPartInstancer" ); MTypeId OutputPartInstancerNode::typeId( MayaTypeID_HoudiniOutputPartInstancerNode ); MObject OutputPartInstancerNode::pointData; MObject OutputPartInstancerNode::storablePositions; MObject OutputPartInstancerNode::storableRotations; MObject OutputPartInstancerNode::storableScales; MObject OutputPartInstancerNode::storableObjectIndices; void* OutputPartInstancerNode::creator() { return new OutputPartInstancerNode(); } MStatus OutputPartInstancerNode::initialize() { MFnTypedAttribute tAttr; // pointData will be connected between the asset node and instancer.inputPoints OutputPartInstancerNode::pointData = tAttr.create( "pointData", "pd", MFnData::kDynArrayAttrs ); tAttr.setReadable( true ); tAttr.setWritable( true ); tAttr.setConnectable( true ); tAttr.setHidden( false ); addAttribute( OutputPartInstancerNode::pointData ); // The storable attrs for the parts of pointData that we want to persist // OutputPartInstancerNode::storablePositions = tAttr.create( "storablePositions", "storablePositions", MFnData::kVectorArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storablePositions ); OutputPartInstancerNode::storableRotations = tAttr.create( "storableRotations", "storableRotations", MFnData::kVectorArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storableRotations ); OutputPartInstancerNode::storableScales = tAttr.create( "storableScales", "storableScales", MFnData::kVectorArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storableScales ); OutputPartInstancerNode::storableObjectIndices = tAttr.create( "storableObjectIndices", "storableObjectIndices", MFnData::kIntArray ); tAttr.setStorable( true ); tAttr.setWritable( true ); tAttr.setReadable( true ); tAttr.setHidden( true ); addAttribute( OutputPartInstancerNode::storableObjectIndices ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storablePositions ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storableRotations ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storableScales ); attributeAffects( OutputPartInstancerNode::pointData, OutputPartInstancerNode::storableObjectIndices ); return MStatus::kSuccess; } OutputPartInstancerNode::OutputPartInstancerNode() { } OutputPartInstancerNode::~OutputPartInstancerNode() { } MStatus OutputPartInstancerNode::compute( const MPlug &plug, MDataBlock &dataBlock ) { MStatus status; if ( plug == OutputPartInstancerNode::pointData ) { if ( !plug.isDestination( &status ) ) { // in this case we should use the storeable data MDataHandle pointDataDataHandle = dataBlock.outputValue( plug, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject pointDataDataObj = pointDataDataHandle.data(); MFnArrayAttrsData pointDataFnArrayAttrs( pointDataDataObj, &status ); if ( pointDataDataObj.isNull() ) { pointDataDataObj = pointDataFnArrayAttrs.create( &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = pointDataDataHandle.setMObject( pointDataDataObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); pointDataDataObj = pointDataDataHandle.data(); status = pointDataFnArrayAttrs.setObject( pointDataDataObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); } // copy vector arrays MString attr[3] = { "position", "rotation", "scale" }; MObject attrObjs[3] = { OutputPartInstancerNode::storablePositions , OutputPartInstancerNode::storableRotations, OutputPartInstancerNode::storableScales }; for ( int i = 0; i < 3; ++i ) { MDataHandle storableHandle = dataBlock.inputValue( attrObjs[ i ], &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnVectorArrayData storableFn( storableObj, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MVectorArray vectorArray = pointDataFnArrayAttrs.vectorArray( attr[ i ], &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = storableFn.copyTo(vectorArray); CHECK_MSTATUS_AND_RETURN_IT(status); } // copy int array MDataHandle storableHandle = dataBlock.inputValue( OutputPartInstancerNode::storableObjectIndices, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnIntArrayData storableFn( storableObj, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MIntArray intArray = pointDataFnArrayAttrs.intArray( "objectIndex", &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = storableFn.copyTo( intArray ); CHECK_MSTATUS_AND_RETURN_IT(status); pointDataDataHandle.setClean(); return status; } } else if ( plug == OutputPartInstancerNode::storablePositions || plug == OutputPartInstancerNode::storableRotations || plug == OutputPartInstancerNode::storableScales || plug == OutputPartInstancerNode::storableObjectIndices ) { MDataHandle pointDataDataHandle = dataBlock.inputValue( OutputPartInstancerNode::pointData, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject pointDataDataObj = pointDataDataHandle.data(); MFnArrayAttrsData pointDataFnArrayAttrs( pointDataDataObj, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); if ( plug == OutputPartInstancerNode::storableObjectIndices ) { MFnArrayAttrsData::Type checkType( MFnArrayAttrsData::kIntArray ); bool exists = pointDataFnArrayAttrs.checkArrayExist( "objectIndex", checkType ); if ( exists ) { MIntArray arrayData = pointDataFnArrayAttrs.getIntData( "objectIndex", &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MDataHandle storableHandle = dataBlock.outputValue( plug, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnIntArrayData storableFn( storableObj, &status ); if ( storableObj.isNull() ) { storableObj = storableFn.create( &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = storableHandle.setMObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); storableObj = storableHandle.data(); status = storableFn.setObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); } status = storableFn.set( arrayData ); CHECK_MSTATUS_AND_RETURN_IT( status ); storableHandle.setClean(); } } else { MString outAttrName; if ( plug == OutputPartInstancerNode::storablePositions ) { outAttrName = "position"; } else if ( plug == OutputPartInstancerNode::storableRotations ) { outAttrName = "rotation"; } else outAttrName = "scale"; MFnArrayAttrsData::Type checkType( MFnArrayAttrsData::kVectorArray ); bool exists = pointDataFnArrayAttrs.checkArrayExist( outAttrName, checkType ); if ( exists ) { MVectorArray arrayData = pointDataFnArrayAttrs.getVectorData( outAttrName, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MDataHandle storableHandle = dataBlock.outputValue( plug, &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); MObject storableObj = storableHandle.data(); MFnVectorArrayData storableFn( storableObj, &status ); if ( storableObj.isNull() ) { storableObj = storableFn.create( &status ); CHECK_MSTATUS_AND_RETURN_IT( status ); status = storableHandle.setMObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); storableObj = storableHandle.data(); status = storableFn.setObject( storableObj ); CHECK_MSTATUS_AND_RETURN_IT( status ); } status = storableFn.set(arrayData); CHECK_MSTATUS_AND_RETURN_IT( status ); storableHandle.setClean(); } } return status; } return MPxNode::compute( plug, dataBlock ); }
Use VectorArray instead of PointArray for stored instancer data
Use VectorArray instead of PointArray for stored instancer data
C++
mit
sideeffects/HoudiniEngineForMaya,sideeffects/HoudiniEngineForMaya,sideeffects/HoudiniEngineForMaya
8eecfd9a97e6df7ffb639c077b7c43a4b6722119
hprose/client/CookieManager.hpp
hprose/client/CookieManager.hpp
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.net/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * CookieManager.hpp * * * * hprose cookie manager unit for cpp. * * * * LastModified: May 29, 2014 * * Author: Chen fei <[email protected]> * * * \**********************************************************/ #ifndef HPROSE_CLIENT_COOKIE_MANAGER_HPP #define HPROSE_CLIENT_COOKIE_MANAGER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <hprose/common.hpp> #include <ctime> #include <vector> #include <boost/algorithm/string/replace.hpp> #include <boost/tr1/unordered_map.hpp> #include <boost/thread/shared_mutex.hpp> #include <boost/thread/locks.hpp> namespace hprose { const char MonthNames[12][4] = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", // 1-6 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" // 7-12 }; const int TimeZoneCount[26] = { 1, 1, 4, 2, 2, 2, 2, 2, 2, 1, 1, 2, 4, // -12-0 5, 6, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 1 // 1-13 }; const char TimeZoneNames[26][6][5] = { { "IDLW" }, // -12 { "NT" }, // -11 { "AHST", "CAT", "HST", "AHST" }, // -10 { "YST", "HDT" }, // -9 { "PST", "YDT" }, // -8 { "MST", "PDT" }, // -7 { "CST", "MDT" }, // -6 { "EST", "CDT" }, // -5 { "AST", "EDT" }, // -4 { "ADT" }, // -3 { "AT" }, // -2 { "WAT", "BST" }, // -1 { "UT", "UTC", "GMT", "WET" }, // 0 { "CET", "FWT", "MET", "MEWT", "SWT" }, // 1 { "EET", "MEST", "MESZ", "SST", "FST", "CEST" }, // 2 { "BT" }, // 3 { "ZP4" }, // 4 { "ZP5" }, // 5 { "ZP6" }, // 6 { "WAST" }, // 7 { "CCT", "WADT" }, // 8 { "JST" }, // 9 { "GST" }, // 10 { "EADT" }, // 11 { "IDLE", "NZST", "NZT" }, // 12 { "NZDT" } // 13 }; bool parseMonth(const std::string & value, int & month) { for (int i = 0; i < 12; i++) { if (MonthNames[i] == value) { month = i; return true; } } return false; } bool parseTimezone(const std::string & value, long & zone) { if ((value[0] == '+') || (value[0] == '-')) { if (value == "-0000") { zone = CTime::TimeZone(); } else if (value.size() > 4) { int zh = atoi(value.substr(1, 2).c_str()); int zm = atoi(value.substr(3, 2).c_str()); zone = zh * 3600 + zm * 60; if (value[0] == '-') { zone = zone * (-1); } } return true; } else { for (int i = 0; i < 26; i++) { for (int j = 0; j < TimeZoneCount[i]; j++) { if (TimeZoneNames[i][j] == value) { zone = (i - 12) * 3600; return true; } } } } return false; } std::time_t parseRFCDatetime(std::string value) { boost::replace_all(value, " -", " #"); std::replace(value.begin(), value.end(), '-', ' '); boost::replace_all(value, " #", " -"); std::tm t; memset(&t, 0, sizeof(std::tm)); int x; long zone = 0; std::string s; std::string::size_type pos; while (!value.empty()) { pos = value.find(' '); if (pos != std::string::npos) { s = value.substr(0, pos); value.erase(0, pos + 1); } else { s = value; value.clear(); } std::transform(s.begin(), s.end(), s.begin(), toupper); if (parseTimezone(s, zone)) continue; if ((x = atoi(s.c_str())) > 0) { if ((x < 32) && (!t.tm_mday)) { t.tm_mday = x; continue; } else { if ((!t.tm_year) && (t.tm_mon || (x > 12))) { if (x < 32) { t.tm_year = x + 100; } else if (x < 1000) { t.tm_year = x; } else { t.tm_year = x - 1900; } continue; } } } std::string::size_type first, last; if ((first = s.find_first_of(':')) < (last = s.find_last_of(':'))) { t.tm_hour = atoi(s.substr(0, first).c_str()); t.tm_min = atoi(s.substr(first + 1, last).c_str()); t.tm_sec = atoi(s.substr(last + 1).c_str()); continue; } if (s == "DST") { t.tm_isdst = true; continue; } if (parseMonth(s, x) && (!t.tm_mon)) { t.tm_mon = x; } } if (!t.tm_year) { t.tm_year = 80; } if (t.tm_mon > 11) { t.tm_mon = 11; } if (!t.tm_mday) { t.tm_mday = 1; } t.tm_sec -= (zone + CTime::TimeZone()); return mktime(&t); } struct cookie { cookie() : expiry(0), secure(false) { } inline bool expired() const { return expiry && (expiry < time(0)); }; inline bool good() const { return !value.empty(); }; inline std::string rawform() const { return name + "=" + value; }; std::string name; std::string value; std::string domain; std::string path; std::time_t expiry; bool secure; }; class CookieManager { public: inline static CookieManager * SharedInstance() { static CookieManager cookieManager; return &cookieManager; } public: std::string GetCookie(const std::string & host, const std::string & path, bool secure = false) { boost::upgrade_lock<boost::shared_mutex> lock(mutex); std::string ret; for (AllCookies::iterator iter1 = container.begin(); iter1 != container.end(); ++iter1) { if (host.find(iter1->first) != std::string::npos) { std::vector<std::string> names; DomainCookies & map = iter1->second; for (DomainCookies::iterator iter2 = map.begin(); iter2 != map.end(); ++iter2) { cookie & c = iter2->second; if (path.find(c.path) == 0) { if (c.expired()) { names.push_back(c.name); } else if (((!c.secure) || (secure && c.secure)) && c.good()) { ret += ret.empty() ? c.rawform() : ("; " + c.rawform()); } } } if (!names.empty()) { // boost::upgrade_to_unique_lock doesn't compile on C++0x mode(#2501) // boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(lock); mutex.unlock_upgrade_and_lock(); for (size_t i = 0; i < names.size(); i++) { map.erase(names[i]); } mutex.unlock_and_lock_upgrade(); } } } return ret; }; void SetCookie(const std::string & host, std::string content) { std::string::size_type pos = content.find(';'); if (pos != std::string::npos) { cookie c; std::string s = content.substr(0, pos); content.erase(0, pos + 2); pos = s.find('='); if (pos != std::string::npos) { c.name = s.substr(0, pos); c.value = s.substr(pos + 1); std::string key, value; while (true) { bool eof = false; pos = content.find(';'); if (pos == std::string::npos) { eof = true; s = content; } else { s = content.substr(0, pos); content.erase(0, pos + 2); } pos = s.find('='); if (pos != std::string::npos) { key = s.substr(0, pos); value = s.substr(pos + 1); } else { if (_strcmpi(s.c_str(), "secure") == 0) { c.secure = true; } continue; } if (_strcmpi(key.c_str(), "path") == 0) { if (!value.empty()) { if (*value.begin() == '"') { value.erase(0, 1); } if (*value.rbegin() == '"') { value.erase(value.size() - 1); } c.path = value.empty() ? std::string("/") : value; } } else if (_strcmpi(key.c_str(), "domain") == 0) { if (!value.empty()) { std::transform(value.begin(), value.end(), value.begin(), tolower); c.domain = value; } } else if (_strcmpi(key.c_str(), "expires") == 0) { if (!value.empty()) { c.expiry = parseRFCDatetime(value); } } if (eof) break; } if (c.path.empty()) { c.path = "/"; } if (c.domain.empty()) { c.domain = host; } boost::unique_lock<boost::shared_mutex> lock(mutex); container[c.domain][c.name] = c; } } }; private: typedef std::tr1::unordered_map<std::string, cookie> DomainCookies; typedef std::tr1::unordered_map<std::string, DomainCookies> AllCookies; AllCookies container; boost::shared_mutex mutex; // read-write lock for containers }; // class CookieManager } // namespace hprose #endif // HPROSE_CLIENT_COOKIE_MANAGER_HPP
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.net/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * CookieManager.hpp * * * * hprose cookie manager unit for cpp. * * * * LastModified: May 29, 2014 * * Author: Chen fei <[email protected]> * * * \**********************************************************/ #ifndef HPROSE_CLIENT_COOKIE_MANAGER_HPP #define HPROSE_CLIENT_COOKIE_MANAGER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <hprose/common.hpp> #include <ctime> #include <vector> #include <boost/algorithm/string/replace.hpp> #include <boost/tr1/unordered_map.hpp> #include <boost/thread/shared_mutex.hpp> #include <boost/thread/locks.hpp> namespace hprose { const char MonthNames[12][4] = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", // 1-6 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" // 7-12 }; const int TimeZoneCount[26] = { 1, 1, 4, 2, 2, 2, 2, 2, 2, 1, 1, 2, 4, // -12-0 5, 6, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 1 // 1-13 }; const char TimeZoneNames[26][6][5] = { { "IDLW" }, // -12 { "NT" }, // -11 { "AHST", "CAT", "HST", "AHST" }, // -10 { "YST", "HDT" }, // -9 { "PST", "YDT" }, // -8 { "MST", "PDT" }, // -7 { "CST", "MDT" }, // -6 { "EST", "CDT" }, // -5 { "AST", "EDT" }, // -4 { "ADT" }, // -3 { "AT" }, // -2 { "WAT", "BST" }, // -1 { "UT", "UTC", "GMT", "WET" }, // 0 { "CET", "FWT", "MET", "MEWT", "SWT" }, // 1 { "EET", "MEST", "MESZ", "SST", "FST", "CEST" }, // 2 { "BT" }, // 3 { "ZP4" }, // 4 { "ZP5" }, // 5 { "ZP6" }, // 6 { "WAST" }, // 7 { "CCT", "WADT" }, // 8 { "JST" }, // 9 { "GST" }, // 10 { "EADT" }, // 11 { "IDLE", "NZST", "NZT" }, // 12 { "NZDT" } // 13 }; struct cookie { cookie() : expiry(0), secure(false) { } inline bool expired() const { return expiry && (expiry < time(0)); }; inline bool good() const { return !value.empty(); }; inline std::string rawform() const { return name + "=" + value; }; std::string name; std::string value; std::string domain; std::string path; std::time_t expiry; bool secure; }; class CookieManager { public: inline static CookieManager * SharedInstance() { static CookieManager cookieManager; return &cookieManager; } public: std::string GetCookie(const std::string & host, const std::string & path, bool secure = false) { boost::upgrade_lock<boost::shared_mutex> lock(mutex); std::string ret; for (AllCookies::iterator iter1 = container.begin(); iter1 != container.end(); ++iter1) { if (host.find(iter1->first) != std::string::npos) { std::vector<std::string> names; DomainCookies & map = iter1->second; for (DomainCookies::iterator iter2 = map.begin(); iter2 != map.end(); ++iter2) { cookie & c = iter2->second; if (path.find(c.path) == 0) { if (c.expired()) { names.push_back(c.name); } else if (((!c.secure) || (secure && c.secure)) && c.good()) { ret += ret.empty() ? c.rawform() : ("; " + c.rawform()); } } } if (!names.empty()) { // boost::upgrade_to_unique_lock doesn't compile on C++0x mode(#2501) // boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(lock); mutex.unlock_upgrade_and_lock(); for (size_t i = 0; i < names.size(); i++) { map.erase(names[i]); } mutex.unlock_and_lock_upgrade(); } } } return ret; }; void SetCookie(const std::string & host, std::string content) { std::string::size_type pos = content.find(';'); if (pos != std::string::npos) { cookie c; std::string s = content.substr(0, pos); content.erase(0, pos + 2); pos = s.find('='); if (pos != std::string::npos) { c.name = s.substr(0, pos); c.value = s.substr(pos + 1); std::string key, value; while (true) { bool eof = false; pos = content.find(';'); if (pos == std::string::npos) { eof = true; s = content; } else { s = content.substr(0, pos); content.erase(0, pos + 2); } pos = s.find('='); if (pos != std::string::npos) { key = s.substr(0, pos); value = s.substr(pos + 1); } else { if (_strcmpi(s.c_str(), "secure") == 0) { c.secure = true; } continue; } if (_strcmpi(key.c_str(), "path") == 0) { if (!value.empty()) { if (*value.begin() == '"') { value.erase(0, 1); } if (*value.rbegin() == '"') { value.erase(value.size() - 1); } c.path = value.empty() ? std::string("/") : value; } } else if (_strcmpi(key.c_str(), "domain") == 0) { if (!value.empty()) { std::transform(value.begin(), value.end(), value.begin(), tolower); c.domain = value; } } else if (_strcmpi(key.c_str(), "expires") == 0) { if (!value.empty()) { c.expiry = parseRFCDatetime(value); } } if (eof) break; } if (c.path.empty()) { c.path = "/"; } if (c.domain.empty()) { c.domain = host; } boost::unique_lock<boost::shared_mutex> lock(mutex); container[c.domain][c.name] = c; } } }; private: bool parseMonth(const std::string & value, int & month) { for (int i = 0; i < 12; i++) { if (MonthNames[i] == value) { month = i; return true; } } return false; } bool parseTimezone(const std::string & value, long & zone) { if ((value[0] == '+') || (value[0] == '-')) { if (value == "-0000") { zone = CTime::TimeZone(); } else if (value.size() > 4) { int zh = atoi(value.substr(1, 2).c_str()); int zm = atoi(value.substr(3, 2).c_str()); zone = zh * 3600 + zm * 60; if (value[0] == '-') { zone = zone * (-1); } } return true; } else { for (int i = 0; i < 26; i++) { for (int j = 0; j < TimeZoneCount[i]; j++) { if (TimeZoneNames[i][j] == value) { zone = (i - 12) * 3600; return true; } } } } return false; } std::time_t parseRFCDatetime(std::string value) { boost::replace_all(value, " -", " #"); std::replace(value.begin(), value.end(), '-', ' '); boost::replace_all(value, " #", " -"); std::tm t; memset(&t, 0, sizeof(std::tm)); int x; long zone = 0; std::string s; std::string::size_type pos; while (!value.empty()) { pos = value.find(' '); if (pos != std::string::npos) { s = value.substr(0, pos); value.erase(0, pos + 1); } else { s = value; value.clear(); } std::transform(s.begin(), s.end(), s.begin(), toupper); if (parseTimezone(s, zone)) continue; if ((x = atoi(s.c_str())) > 0) { if ((x < 32) && (!t.tm_mday)) { t.tm_mday = x; continue; } else { if ((!t.tm_year) && (t.tm_mon || (x > 12))) { if (x < 32) { t.tm_year = x + 100; } else if (x < 1000) { t.tm_year = x; } else { t.tm_year = x - 1900; } continue; } } } std::string::size_type first, last; if ((first = s.find_first_of(':')) < (last = s.find_last_of(':'))) { t.tm_hour = atoi(s.substr(0, first).c_str()); t.tm_min = atoi(s.substr(first + 1, last).c_str()); t.tm_sec = atoi(s.substr(last + 1).c_str()); continue; } if (s == "DST") { t.tm_isdst = true; continue; } if (parseMonth(s, x) && (!t.tm_mon)) { t.tm_mon = x; } } if (!t.tm_year) { t.tm_year = 80; } if (t.tm_mon > 11) { t.tm_mon = 11; } if (!t.tm_mday) { t.tm_mday = 1; } t.tm_sec -= (zone + CTime::TimeZone()); return mktime(&t); } private: typedef std::tr1::unordered_map<std::string, cookie> DomainCookies; typedef std::tr1::unordered_map<std::string, DomainCookies> AllCookies; AllCookies container; boost::shared_mutex mutex; // read-write lock for containers }; // class CookieManager } // namespace hprose #endif // HPROSE_CLIENT_COOKIE_MANAGER_HPP
move parseMonth parseTimezone parseRFCDatetime to CookieManager private.
move parseMonth parseTimezone parseRFCDatetime to CookieManager private.
C++
mit
hprose/hprose-cpp
7115998bb21e6c731d52351a3e53f33ba4624b6b
modules/audio_coding/main/acm2/audio_coding_module_unittest.cc
modules/audio_coding/main/acm2/audio_coding_module_unittest.cc
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module_typedefs.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/compile_assert.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/thread_annotations.h" #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "webrtc/test/testsupport/gtest_disable.h" namespace webrtc { const int kSampleRateHz = 16000; const int kNumSamples10ms = kSampleRateHz / 100; const int kFrameSizeMs = 10; // Multiple of 10. const int kFrameSizeSamples = kFrameSizeMs / 10 * kNumSamples10ms; const int kPayloadSizeBytes = kFrameSizeSamples * sizeof(int16_t); const uint8_t kPayloadType = 111; class RtpUtility { public: RtpUtility(int samples_per_packet, uint8_t payload_type) : samples_per_packet_(samples_per_packet), payload_type_(payload_type) {} virtual ~RtpUtility() {} void Populate(WebRtcRTPHeader* rtp_header) { rtp_header->header.sequenceNumber = 0xABCD; rtp_header->header.timestamp = 0xABCDEF01; rtp_header->header.payloadType = payload_type_; rtp_header->header.markerBit = false; rtp_header->header.ssrc = 0x1234; rtp_header->header.numCSRCs = 0; rtp_header->frameType = kAudioFrameSpeech; rtp_header->header.payload_type_frequency = kSampleRateHz; rtp_header->type.Audio.channel = 1; rtp_header->type.Audio.isCNG = false; } void Forward(WebRtcRTPHeader* rtp_header) { ++rtp_header->header.sequenceNumber; rtp_header->header.timestamp += samples_per_packet_; } private: int samples_per_packet_; uint8_t payload_type_; }; class PacketizationCallbackStub : public AudioPacketizationCallback { public: PacketizationCallbackStub() : num_calls_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {} virtual int32_t SendData( FrameType frame_type, uint8_t payload_type, uint32_t timestamp, const uint8_t* payload_data, uint16_t payload_len_bytes, const RTPFragmentationHeader* fragmentation) OVERRIDE { CriticalSectionScoped lock(crit_sect_.get()); ++num_calls_; return 0; } int num_calls() const { CriticalSectionScoped lock(crit_sect_.get()); return num_calls_; } private: int num_calls_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; }; class AudioCodingModuleTest : public ::testing::Test { protected: AudioCodingModuleTest() : id_(1), rtp_utility_(new RtpUtility(kFrameSizeSamples, kPayloadType)), clock_(Clock::GetRealTimeClock()) {} ~AudioCodingModuleTest() {} void TearDown() {} void SetUp() { acm_.reset(AudioCodingModule::Create(id_, clock_)); AudioCodingModule::Codec("L16", &codec_, kSampleRateHz, 1); codec_.pltype = kPayloadType; // Register L16 codec in ACM. ASSERT_EQ(0, acm_->RegisterReceiveCodec(codec_)); ASSERT_EQ(0, acm_->RegisterSendCodec(codec_)); rtp_utility_->Populate(&rtp_header_); input_frame_.sample_rate_hz_ = kSampleRateHz; input_frame_.num_channels_ = 1; input_frame_.samples_per_channel_ = kSampleRateHz * 10 / 1000; // 10 ms. COMPILE_ASSERT(kSampleRateHz * 10 / 1000 <= AudioFrame::kMaxDataSizeSamples, audio_frame_too_small); memset(input_frame_.data_, 0, input_frame_.samples_per_channel_ * sizeof(input_frame_.data_[0])); ASSERT_EQ(0, acm_->RegisterTransportCallback(&packet_cb_)); } void InsertPacketAndPullAudio() { InsertPacket(); PullAudio(); } void InsertPacket() { const uint8_t kPayload[kPayloadSizeBytes] = {0}; ASSERT_EQ(0, acm_->IncomingPacket(kPayload, kPayloadSizeBytes, rtp_header_)); rtp_utility_->Forward(&rtp_header_); } void PullAudio() { AudioFrame audio_frame; ASSERT_EQ(0, acm_->PlayoutData10Ms(-1, &audio_frame)); } void InsertAudio() { ASSERT_EQ(0, acm_->Add10MsData(input_frame_)); } void Encode() { int32_t encoded_bytes = acm_->Process(); // Expect to get one packet with two bytes per sample, or no packet at all, // depending on how many 10 ms blocks go into |codec_.pacsize|. EXPECT_TRUE(encoded_bytes == 2 * codec_.pacsize || encoded_bytes == 0); } const int id_; scoped_ptr<RtpUtility> rtp_utility_; scoped_ptr<AudioCodingModule> acm_; PacketizationCallbackStub packet_cb_; WebRtcRTPHeader rtp_header_; AudioFrame input_frame_; CodecInst codec_; Clock* clock_; }; // Check if the statistics are initialized correctly. Before any call to ACM // all fields have to be zero. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(InitializedToZero)) { AudioDecodingCallStats stats; acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Apply an initial playout delay. Calls to AudioCodingModule::PlayoutData10ms() // should result in generating silence, check the associated field. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(SilenceGeneratorCalled)) { AudioDecodingCallStats stats; const int kInitialDelay = 100; acm_->SetInitialPlayoutDelay(kInitialDelay); int num_calls = 0; for (int time_ms = 0; time_ms < kInitialDelay; time_ms += kFrameSizeMs, ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(num_calls, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Insert some packets and pull audio. Check statistics are valid. Then, // simulate packet loss and check if PLC and PLC-to-CNG statistics are // correctly updated. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(NetEqCalls)) { AudioDecodingCallStats stats; const int kNumNormalCalls = 10; for (int num_calls = 0; num_calls < kNumNormalCalls; ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); const int kNumPlc = 3; const int kNumPlcCng = 5; // Simulate packet-loss. NetEq first performs PLC then PLC fades to CNG. for (int n = 0; n < kNumPlc + kNumPlcCng; ++n) { PullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls + kNumPlc + kNumPlcCng, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(kNumPlc, stats.decoded_plc); EXPECT_EQ(kNumPlcCng, stats.decoded_plc_cng); } TEST_F(AudioCodingModuleTest, VerifyOutputFrame) { AudioFrame audio_frame; const int kSampleRateHz = 32000; EXPECT_EQ(0, acm_->PlayoutData10Ms(kSampleRateHz, &audio_frame)); EXPECT_EQ(id_, audio_frame.id_); EXPECT_EQ(0u, audio_frame.timestamp_); EXPECT_GT(audio_frame.num_channels_, 0); EXPECT_EQ(kSampleRateHz / 100, audio_frame.samples_per_channel_); EXPECT_EQ(kSampleRateHz, audio_frame.sample_rate_hz_); } TEST_F(AudioCodingModuleTest, FailOnZeroDesiredFrequency) { AudioFrame audio_frame; EXPECT_EQ(-1, acm_->PlayoutData10Ms(0, &audio_frame)); } class AudioCodingModuleMtTest : public AudioCodingModuleTest { protected: static const int kNumPackets = 5000; static const int kNumPullCalls = 5000; AudioCodingModuleMtTest() : AudioCodingModuleTest(), send_thread_(ThreadWrapper::CreateThread(CbSendThread, this, kRealtimePriority, "send")), insert_packet_thread_(ThreadWrapper::CreateThread(CbInsertPacketThread, this, kRealtimePriority, "insert_packet")), pull_audio_thread_(ThreadWrapper::CreateThread(CbPullAudioThread, this, kRealtimePriority, "pull_audio")), test_complete_(EventWrapper::Create()), send_count_(0), insert_packet_count_(0), pull_audio_count_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), next_insert_packet_time_ms_(0), fake_clock_(new SimulatedClock(0)) { clock_ = fake_clock_; } ~AudioCodingModuleMtTest() {} void SetUp() { AudioCodingModuleTest::SetUp(); unsigned int thread_id = 0; ASSERT_TRUE(send_thread_->Start(thread_id)); ASSERT_TRUE(insert_packet_thread_->Start(thread_id)); ASSERT_TRUE(pull_audio_thread_->Start(thread_id)); } void TearDown() { AudioCodingModuleTest::TearDown(); pull_audio_thread_->Stop(); send_thread_->Stop(); insert_packet_thread_->Stop(); } EventTypeWrapper RunTest() { return test_complete_->Wait(120000); } private: static bool CbSendThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context)->CbSendImpl(); } // The send thread doesn't have to care about the current simulated time, // since only the AcmReceiver is using the clock. bool CbSendImpl() { if (HasFatalFailure()) { // End the test early if a fatal failure (ASSERT_*) has occurred. test_complete_->Set(); } ++send_count_; InsertAudio(); Encode(); if (packet_cb_.num_calls() > kNumPackets) { CriticalSectionScoped lock(crit_sect_.get()); if (pull_audio_count_ > kNumPullCalls) { // Both conditions for completion are met. End the test. test_complete_->Set(); } } return true; } static bool CbInsertPacketThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbInsertPacketImpl(); } bool CbInsertPacketImpl() { { CriticalSectionScoped lock(crit_sect_.get()); if (clock_->TimeInMilliseconds() < next_insert_packet_time_ms_) { return true; } next_insert_packet_time_ms_ += 10; } // Now we're not holding the crit sect when calling ACM. ++insert_packet_count_; InsertPacket(); return true; } static bool CbPullAudioThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbPullAudioImpl(); } bool CbPullAudioImpl() { { CriticalSectionScoped lock(crit_sect_.get()); // Don't let the insert thread fall behind. if (next_insert_packet_time_ms_ < clock_->TimeInMilliseconds()) { return true; } ++pull_audio_count_; } // Now we're not holding the crit sect when calling ACM. PullAudio(); fake_clock_->AdvanceTimeMilliseconds(10); return true; } scoped_ptr<ThreadWrapper> send_thread_; scoped_ptr<ThreadWrapper> insert_packet_thread_; scoped_ptr<ThreadWrapper> pull_audio_thread_; const scoped_ptr<EventWrapper> test_complete_; int send_count_; int insert_packet_count_; int pull_audio_count_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; int64_t next_insert_packet_time_ms_ GUARDED_BY(crit_sect_); SimulatedClock* fake_clock_; }; TEST_F(AudioCodingModuleMtTest, DoTest) { EXPECT_EQ(kEventSignaled, RunTest()); } } // namespace webrtc
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module_typedefs.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/compile_assert.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/thread_annotations.h" #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "webrtc/test/testsupport/gtest_disable.h" namespace webrtc { const int kSampleRateHz = 16000; const int kNumSamples10ms = kSampleRateHz / 100; const int kFrameSizeMs = 10; // Multiple of 10. const int kFrameSizeSamples = kFrameSizeMs / 10 * kNumSamples10ms; const int kPayloadSizeBytes = kFrameSizeSamples * sizeof(int16_t); const uint8_t kPayloadType = 111; class RtpUtility { public: RtpUtility(int samples_per_packet, uint8_t payload_type) : samples_per_packet_(samples_per_packet), payload_type_(payload_type) {} virtual ~RtpUtility() {} void Populate(WebRtcRTPHeader* rtp_header) { rtp_header->header.sequenceNumber = 0xABCD; rtp_header->header.timestamp = 0xABCDEF01; rtp_header->header.payloadType = payload_type_; rtp_header->header.markerBit = false; rtp_header->header.ssrc = 0x1234; rtp_header->header.numCSRCs = 0; rtp_header->frameType = kAudioFrameSpeech; rtp_header->header.payload_type_frequency = kSampleRateHz; rtp_header->type.Audio.channel = 1; rtp_header->type.Audio.isCNG = false; } void Forward(WebRtcRTPHeader* rtp_header) { ++rtp_header->header.sequenceNumber; rtp_header->header.timestamp += samples_per_packet_; } private: int samples_per_packet_; uint8_t payload_type_; }; class PacketizationCallbackStub : public AudioPacketizationCallback { public: PacketizationCallbackStub() : num_calls_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {} virtual int32_t SendData( FrameType frame_type, uint8_t payload_type, uint32_t timestamp, const uint8_t* payload_data, uint16_t payload_len_bytes, const RTPFragmentationHeader* fragmentation) OVERRIDE { CriticalSectionScoped lock(crit_sect_.get()); ++num_calls_; return 0; } int num_calls() const { CriticalSectionScoped lock(crit_sect_.get()); return num_calls_; } private: int num_calls_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; }; class AudioCodingModuleTest : public ::testing::Test { protected: AudioCodingModuleTest() : id_(1), rtp_utility_(new RtpUtility(kFrameSizeSamples, kPayloadType)), clock_(Clock::GetRealTimeClock()) {} ~AudioCodingModuleTest() {} void TearDown() {} void SetUp() { acm_.reset(AudioCodingModule::Create(id_, clock_)); AudioCodingModule::Codec("L16", &codec_, kSampleRateHz, 1); codec_.pltype = kPayloadType; // Register L16 codec in ACM. ASSERT_EQ(0, acm_->RegisterReceiveCodec(codec_)); ASSERT_EQ(0, acm_->RegisterSendCodec(codec_)); rtp_utility_->Populate(&rtp_header_); input_frame_.sample_rate_hz_ = kSampleRateHz; input_frame_.samples_per_channel_ = kSampleRateHz * 10 / 1000; // 10 ms. COMPILE_ASSERT(kSampleRateHz * 10 / 1000 <= AudioFrame::kMaxDataSizeSamples, audio_frame_too_small); memset(input_frame_.data_, 0, input_frame_.samples_per_channel_ * sizeof(input_frame_.data_[0])); ASSERT_EQ(0, acm_->RegisterTransportCallback(&packet_cb_)); } void InsertPacketAndPullAudio() { InsertPacket(); PullAudio(); } void InsertPacket() { const uint8_t kPayload[kPayloadSizeBytes] = {0}; ASSERT_EQ(0, acm_->IncomingPacket(kPayload, kPayloadSizeBytes, rtp_header_)); rtp_utility_->Forward(&rtp_header_); } void PullAudio() { AudioFrame audio_frame; ASSERT_EQ(0, acm_->PlayoutData10Ms(-1, &audio_frame)); } void InsertAudio() { ASSERT_EQ(0, acm_->Add10MsData(input_frame_)); } void Encode() { int32_t encoded_bytes = acm_->Process(); // Expect to get one packet with two bytes per sample, or no packet at all, // depending on how many 10 ms blocks go into |codec_.pacsize|. EXPECT_TRUE(encoded_bytes == 2 * codec_.pacsize || encoded_bytes == 0); } const int id_; scoped_ptr<RtpUtility> rtp_utility_; scoped_ptr<AudioCodingModule> acm_; PacketizationCallbackStub packet_cb_; WebRtcRTPHeader rtp_header_; AudioFrame input_frame_; CodecInst codec_; Clock* clock_; }; // Check if the statistics are initialized correctly. Before any call to ACM // all fields have to be zero. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(InitializedToZero)) { AudioDecodingCallStats stats; acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Apply an initial playout delay. Calls to AudioCodingModule::PlayoutData10ms() // should result in generating silence, check the associated field. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(SilenceGeneratorCalled)) { AudioDecodingCallStats stats; const int kInitialDelay = 100; acm_->SetInitialPlayoutDelay(kInitialDelay); int num_calls = 0; for (int time_ms = 0; time_ms < kInitialDelay; time_ms += kFrameSizeMs, ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(num_calls, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Insert some packets and pull audio. Check statistics are valid. Then, // simulate packet loss and check if PLC and PLC-to-CNG statistics are // correctly updated. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(NetEqCalls)) { AudioDecodingCallStats stats; const int kNumNormalCalls = 10; for (int num_calls = 0; num_calls < kNumNormalCalls; ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); const int kNumPlc = 3; const int kNumPlcCng = 5; // Simulate packet-loss. NetEq first performs PLC then PLC fades to CNG. for (int n = 0; n < kNumPlc + kNumPlcCng; ++n) { PullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls + kNumPlc + kNumPlcCng, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(kNumPlc, stats.decoded_plc); EXPECT_EQ(kNumPlcCng, stats.decoded_plc_cng); } TEST_F(AudioCodingModuleTest, VerifyOutputFrame) { AudioFrame audio_frame; const int kSampleRateHz = 32000; EXPECT_EQ(0, acm_->PlayoutData10Ms(kSampleRateHz, &audio_frame)); EXPECT_EQ(id_, audio_frame.id_); EXPECT_EQ(0u, audio_frame.timestamp_); EXPECT_GT(audio_frame.num_channels_, 0); EXPECT_EQ(kSampleRateHz / 100, audio_frame.samples_per_channel_); EXPECT_EQ(kSampleRateHz, audio_frame.sample_rate_hz_); } TEST_F(AudioCodingModuleTest, FailOnZeroDesiredFrequency) { AudioFrame audio_frame; EXPECT_EQ(-1, acm_->PlayoutData10Ms(0, &audio_frame)); } class AudioCodingModuleMtTest : public AudioCodingModuleTest { protected: static const int kNumPackets = 10000; static const int kNumPullCalls = 10000; AudioCodingModuleMtTest() : AudioCodingModuleTest(), send_thread_(ThreadWrapper::CreateThread(CbSendThread, this, kRealtimePriority, "send")), insert_packet_thread_(ThreadWrapper::CreateThread(CbInsertPacketThread, this, kRealtimePriority, "insert_packet")), pull_audio_thread_(ThreadWrapper::CreateThread(CbPullAudioThread, this, kRealtimePriority, "pull_audio")), test_complete_(EventWrapper::Create()), send_count_(0), insert_packet_count_(0), pull_audio_count_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), next_insert_packet_time_ms_(0), fake_clock_(new SimulatedClock(0)) { clock_ = fake_clock_; } ~AudioCodingModuleMtTest() {} void SetUp() { AudioCodingModuleTest::SetUp(); unsigned int thread_id = 0; ASSERT_TRUE(send_thread_->Start(thread_id)); ASSERT_TRUE(insert_packet_thread_->Start(thread_id)); ASSERT_TRUE(pull_audio_thread_->Start(thread_id)); } void TearDown() { AudioCodingModuleTest::TearDown(); pull_audio_thread_->Stop(); send_thread_->Stop(); insert_packet_thread_->Stop(); } EventTypeWrapper RunTest() { return test_complete_->Wait(60000); } private: static bool CbSendThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context)->CbSendImpl(); } // The send thread doesn't have to care about the current simulated time, // since only the AcmReceiver is using the clock. bool CbSendImpl() { ++send_count_; InsertAudio(); Encode(); if (packet_cb_.num_calls() > kNumPackets) { CriticalSectionScoped lock(crit_sect_.get()); if (pull_audio_count_ > kNumPullCalls) { // Both conditions for completion are met. End the test. test_complete_->Set(); } } return true; } static bool CbInsertPacketThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbInsertPacketImpl(); } bool CbInsertPacketImpl() { { CriticalSectionScoped lock(crit_sect_.get()); if (clock_->TimeInMilliseconds() < next_insert_packet_time_ms_) { return true; } next_insert_packet_time_ms_ += 10; } // Now we're not holding the crit sect when calling ACM. ++insert_packet_count_; InsertPacket(); return true; } static bool CbPullAudioThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbPullAudioImpl(); } bool CbPullAudioImpl() { { CriticalSectionScoped lock(crit_sect_.get()); // Don't let the insert thread fall behind. if (next_insert_packet_time_ms_ < clock_->TimeInMilliseconds()) { return true; } ++pull_audio_count_; } // Now we're not holding the crit sect when calling ACM. PullAudio(); fake_clock_->AdvanceTimeMilliseconds(10); return true; } scoped_ptr<ThreadWrapper> send_thread_; scoped_ptr<ThreadWrapper> insert_packet_thread_; scoped_ptr<ThreadWrapper> pull_audio_thread_; const scoped_ptr<EventWrapper> test_complete_; int send_count_; int insert_packet_count_; int pull_audio_count_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; int64_t next_insert_packet_time_ms_ GUARDED_BY(crit_sect_); SimulatedClock* fake_clock_; }; TEST_F(AudioCodingModuleMtTest, DISABLED_DoTest) { EXPECT_EQ(kEventSignaled, RunTest()); } } // namespace webrtc
Revert 6312 "Re-enable AudioCodingModuleMtTest"
Revert 6312 "Re-enable AudioCodingModuleMtTest" An example of botbreakage is http://chromegw.corp.google.com/i/client.webrtc/builders/Linux%20Memcheck/builds/1807 > Re-enable AudioCodingModuleMtTest > > Increase timeout and decrease test length. Also fixing a bug in the > test, and make sure the test aborts if fatal failure occurrs. > > BUG=3426 > [email protected] > > Review URL: https://webrtc-codereview.appspot.com/13579005 [email protected] Review URL: https://webrtc-codereview.appspot.com/19609004 git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@6314 4adac7df-926f-26a2-2b94-8c16560cd09d
C++
bsd-3-clause
CyanogenMod/android_external_chromium_org_third_party_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,krieger-od/webrtc,PersonifyInc/chromium_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,AOSPU/external_chromium_org_third_party_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,AOSPU/external_chromium_org_third_party_webrtc,jchavanton/webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,jchavanton/webrtc,MIPS/external-chromium_org-third_party-webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,bpsinc-native/src_third_party_webrtc,bpsinc-native/src_third_party_webrtc,sippet/webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,AOSPU/external_chromium_org_third_party_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,sippet/webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,jchavanton/webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,Alkalyne/webrtctrunk,MIPS/external-chromium_org-third_party-webrtc,bpsinc-native/src_third_party_webrtc,bpsinc-native/src_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,PersonifyInc/chromium_webrtc,Alkalyne/webrtctrunk,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,aleonliao/webrtc-trunk,AOSPU/external_chromium_org_third_party_webrtc,krieger-od/webrtc,krieger-od/nwjs_chromium_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,svn2github/webrtc-Revision-8758,xin3liang/platform_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,CyanogenMod/android_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,krieger-od/webrtc,jchavanton/webrtc,AOSPU/external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,krieger-od/webrtc,Omegaphora/external_chromium_org_third_party_webrtc,sippet/webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,sippet/webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,PersonifyInc/chromium_webrtc,krieger-od/nwjs_chromium_webrtc,krieger-od/webrtc,aleonliao/webrtc-trunk,PersonifyInc/chromium_webrtc,CyanogenMod/android_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,svn2github/webrtc-Revision-8758,bpsinc-native/src_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,Omegaphora/external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,aleonliao/webrtc-trunk,krieger-od/webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,svn2github/webrtc-Revision-8758,xin3liang/platform_external_chromium_org_third_party_webrtc,jchavanton/webrtc,AOSPU/external_chromium_org_third_party_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,krieger-od/nwjs_chromium_webrtc,krieger-od/nwjs_chromium_webrtc,AOSPU/external_chromium_org_third_party_webrtc,sippet/webrtc,Omegaphora/external_chromium_org_third_party_webrtc,jchavanton/webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,android-ia/platform_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,Omegaphora/external_chromium_org_third_party_webrtc,sippet/webrtc,MIPS/external-chromium_org-third_party-webrtc,Alkalyne/webrtctrunk
39c19da7bc063f6e9146398c5bc6950cb2f81a7f
lib/libport/semaphore.cc
lib/libport/semaphore.cc
#include <cerrno> #include <iostream> #include <libport/assert.hh> #include <libport/exception.hh> #include <libport/program-name.hh> #include <libport/semaphore.hh> #include <libport/sysexits.hh> #include <time.h> namespace libport { # if defined WIN32 || defined LIBPORT_WIN32 # define CLOCK_REALTIME 0 # define ETIMEDOUT 110 void clock_gettime(int, struct timespec* t) { if (t) { t->tv_sec = 0; t->tv_nsec = 0; } } sem_t* sem_open(const char* /* name */, int /* oflag */, unsigned int /*mode_t*/ /* mode */, unsigned int /* value */) { return 0; // Use sem_init instead. } int sem_init(sem_t* sem, int, unsigned value) { *sem = CreateSemaphore(0, value, MAXLONG, 0); if (!sem) errabort("CreateSemaphore"); return 0; } int sem_post(sem_t* sem) { if (!ReleaseSemaphore(*sem, 1, 0)) errabort("ReleaseSemaphore"); return 0; } int sem_wait(sem_t* sem) { if (WaitForSingleObject(*sem, INFINITE) == WAIT_FAILED) errabort("WaitForSingleObject"); return 0; } int sem_timedwait(sem_t* sem, const struct timespec *abs_timeout) { switch (WaitForSingleObject(*sem, abs_timeout->tv_sec * 1000 + abs_timeout->tv_nsec / 1000000)) { case WAIT_FAILED: errabort("WaitForSingleObject"); case WAIT_TIMEOUT: errno = ETIMEDOUT; return -1; default: return 0; } } int sem_destroy(sem_t* sem) { return CloseHandle(*sem) ? 0 : -1; } int sem_getvalue(sem_t* /* sem */, int* v) { *v = 1; //TODO: implement // Maybe look at: http://www.codeguru.com/Cpp/W-P/win32/article.php/c1423 return 0; } #endif /* !WIN32 */ } // namespace libport /* Darwin doesn't implement sem_init/sem_close (although the functions exists * and is defined, in fact it just returns ENOSYS). That's why we need to use * named semaphores (with sem_open) instead. * See: * http://lists.apple.com/archives/darwin-development/2004/May/msg00077.html * http://www.google.com/search?as_q=sem_init&as_sitesearch=apple.com * * Semaphores created with sem_open must be closed with sem_close. * Semaphores created with sem_init must be closed with sem_destroy. */ #ifdef __APPLE__ # include <fstream> # include <sstream> # include <sys/stat.h> # include <sys/time.h> # include <signal.h> #endif namespace libport { Semaphore::Semaphore(unsigned cnt) { # ifdef __APPLE__ static unsigned int counter = 0; int sem_open_errno; do { std::stringstream s; errno = 0; s << "sema/" << getpid() << "/" << counter++; name_ = s.str(); sem_ = sem_open(name_.c_str(), O_CREAT | O_EXCL, 0777, cnt); sem_open_errno = errno; } while (sem_ == SEM_FAILED && errno == EEXIST); { // Save the semaphore name if we can, in order to provide the // user with a means to reclaim them. Don't check for success, // this is best effort. // // If you change this file name, update // build-aux/semaphores-clean.sh. mkdir("/tmp/urbi-semaphores", 0777); std::stringstream f; f << "/tmp/urbi-semaphores/" << getpid(); std::ofstream o(f.str().c_str(), std::ios_base::app); o << name_; if (sem_ == SEM_FAILED) o << ": " << strerror(sem_open_errno); o << std::endl; } if (sem_ == SEM_FAILED) { std::string error = strerror(sem_open_errno); if (sem_open_errno == ENOSPC) error += " (i.e., used all the semaphores, run semaphore-clean)"; // Certainly dying because we don't have enough semaphores // available. Report we should be skipped. std::cerr << program_name() << ": cannot sem_open(" << name_ << "): " << strerror(sem_open_errno) << std::endl << exit(EX_SKIP); } # else sem_ = new sem_t; if (sem_init(sem_, 0, cnt)) { destroy(); errabort("sem_init(" << cnt << ')'); } # endif ++instances_; } Semaphore::~Semaphore() { destroy(); --instances_; } size_t Semaphore::instances_ = 0; size_t Semaphore::instances() { return instances_; } void Semaphore::destroy() { # ifdef __APPLE__ // We *really* need to unlink the semaphores when we are done, // otherwise they leak, and at some point, ENOSPCE is the only // answer from the system. I could not find a means to remove // them from the shell (ipcs shows nothing), so I had to reboot my // machine. // // So really, try to call sem_unlink in all the cases, including // aborts here. // // http://lists.apple.com/archives/darwin-dev/2005/Jun/msg00078.html int c = sem_close(sem_); int close_errno = errno; int u = sem_unlink(name_.c_str()); int unlink_errno = errno; if (c) { errno = close_errno; errabort("sem_close"); } if (u) { errno = unlink_errno; errabort("sem_unlink"); } # else if (sem_destroy(sem_)) errabort("sem_destroy"); delete sem_; # endif } void Semaphore::operator++() { if (sem_post(sem_)) { destroy(); errabort("sem_post"); } } void Semaphore::operator--() { get(0); } Semaphore& Semaphore::operator-=(unsigned c) { for (unsigned i = 0; i < c; ++i) --*this; return *this; } Semaphore& Semaphore::operator+=(unsigned c) { for (unsigned i = 0; i < c; ++i) ++*this; return *this; } # if defined __APPLE__ int flag; void fun_timeout(int fl) { std::cout << fl << std::endl; flag = 0; } # endif bool Semaphore::uget(utime_t useconds) { int err; do { if (useconds == 0) err = sem_wait(sem_); # if defined __APPLE__ else { struct itimerval it; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 0; it.it_value.tv_sec = useconds / 1000000; it.it_value.tv_usec = useconds % 1000000; flag = 1; signal(SIGALRM, fun_timeout); setitimer(ITIMER_REAL, &it, NULL); do { err = sem_trywait(sem_); } while (flag && err == -1 && errno == EAGAIN); if (!flag) err = -1; } # else else { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += useconds / 1000000; ts.tv_nsec += (useconds % 1000000) * 1000; err = sem_timedwait(sem_, &ts); } # endif } while (err == -1 && errno == EINTR); # if defined __APPLE__ if (!flag) return false; # else if (err && errno == ETIMEDOUT) return false; # endif if (err) { destroy(); errabort("sem_wait"); } return true; } bool Semaphore::get(unsigned seconds) { return uget(seconds * 1000 * 1000); } Semaphore::operator int() { int res; if (sem_getvalue(sem_, &res)) { destroy(); errabort("sem_getvalue"); } return res; } } // namespace libport
#include <cerrno> #include <iostream> #include <libport/assert.hh> #include <libport/exception.hh> #include <libport/program-name.hh> #include <libport/semaphore.hh> #include <libport/sysexits.hh> #include <time.h> namespace libport { # if defined WIN32 || defined LIBPORT_WIN32 # define CLOCK_REALTIME 0 # define ETIMEDOUT 110 void clock_gettime(int, struct timespec* t) { if (t) { t->tv_sec = 0; t->tv_nsec = 0; } } sem_t* sem_open(const char* /* name */, int /* oflag */, unsigned int /*mode_t*/ /* mode */, unsigned int /* value */) { return 0; // Use sem_init instead. } int sem_init(sem_t* sem, int, unsigned value) { *sem = CreateSemaphore(0, value, MAXLONG, 0); if (!sem) errabort("CreateSemaphore"); return 0; } int sem_post(sem_t* sem) { if (!ReleaseSemaphore(*sem, 1, 0)) errabort("ReleaseSemaphore"); return 0; } int sem_wait(sem_t* sem) { if (WaitForSingleObject(*sem, INFINITE) == WAIT_FAILED) errabort("WaitForSingleObject"); return 0; } int sem_timedwait(sem_t* sem, const struct timespec *abs_timeout) { switch (WaitForSingleObject(*sem, abs_timeout->tv_sec * 1000 + abs_timeout->tv_nsec / 1000000)) { case WAIT_FAILED: errabort("WaitForSingleObject"); case WAIT_TIMEOUT: errno = ETIMEDOUT; return -1; default: return 0; } } int sem_destroy(sem_t* sem) { return CloseHandle(*sem) ? 0 : -1; } int sem_getvalue(sem_t* /* sem */, int* v) { *v = 1; //TODO: implement // Maybe look at: http://www.codeguru.com/Cpp/W-P/win32/article.php/c1423 return 0; } #endif /* !WIN32 */ } // namespace libport /* Darwin doesn't implement sem_init/sem_close (although the functions exists * and is defined, in fact it just returns ENOSYS). That's why we need to use * named semaphores (with sem_open) instead. * See: * http://lists.apple.com/archives/darwin-development/2004/May/msg00077.html * http://www.google.com/search?as_q=sem_init&as_sitesearch=apple.com * * Semaphores created with sem_open must be closed with sem_close. * Semaphores created with sem_init must be closed with sem_destroy. */ #ifdef __APPLE__ # include <fstream> # include <sstream> # include <sys/stat.h> # include <sys/time.h> # include <signal.h> #endif namespace libport { Semaphore::Semaphore(unsigned cnt) { # ifdef __APPLE__ static unsigned int counter = 0; int sem_open_errno; do { std::stringstream s; errno = 0; s << "sema/" << getpid() << "/" << counter++; name_ = s.str(); sem_ = sem_open(name_.c_str(), O_CREAT | O_EXCL, 0777, cnt); sem_open_errno = errno; } while (sem_ == SEM_FAILED && errno == EEXIST); { // Save the semaphore name if we can, in order to provide the // user with a means to reclaim them. Don't check for success, // this is best effort. // // If you change this file name, update // build-aux/semaphores-clean.sh. mkdir("/tmp/urbi-semaphores", 0777); std::stringstream f; f << "/tmp/urbi-semaphores/" << getpid(); std::ofstream o(f.str().c_str(), std::ios_base::app); o << name_; if (sem_ == SEM_FAILED) o << ": " << strerror(sem_open_errno); o << std::endl; } if (sem_ == SEM_FAILED) { std::string error = strerror(sem_open_errno); if (sem_open_errno == ENOSPC) error += " (i.e., used all the semaphores, run semaphore-clean)"; // Certainly dying because we don't have enough semaphores // available. Report we should be skipped. std::cerr << program_name() << ": cannot sem_open(" << name_ << "): " << strerror(sem_open_errno) << std::endl << exit(EX_SKIP); } # else sem_ = new sem_t; if (sem_init(sem_, 0, cnt)) { destroy(); errabort("sem_init(" << cnt << ')'); } # endif ++instances_; } Semaphore::~Semaphore() { destroy(); --instances_; } size_t Semaphore::instances_ = 0; size_t Semaphore::instances() { return instances_; } void Semaphore::destroy() { # ifdef __APPLE__ // We *really* need to unlink the semaphores when we are done, // otherwise they leak, and at some point, ENOSPCE is the only // answer from the system. I could not find a means to remove // them from the shell (ipcs shows nothing), so I had to reboot my // machine. // // So really, try to call sem_unlink in all the cases, including // aborts here. // // http://lists.apple.com/archives/darwin-dev/2005/Jun/msg00078.html int c = sem_close(sem_); int close_errno = errno; int u = sem_unlink(name_.c_str()); int unlink_errno = errno; if (c) { errno = close_errno; errabort("sem_close"); } if (u) { errno = unlink_errno; errabort("sem_unlink"); } # else if (sem_destroy(sem_)) errabort("sem_destroy"); delete sem_; # endif } void Semaphore::operator++() { if (sem_post(sem_)) { destroy(); errabort("sem_post"); } } void Semaphore::operator--() { get(0); } Semaphore& Semaphore::operator-=(unsigned c) { for (unsigned i = 0; i < c; ++i) --*this; return *this; } Semaphore& Semaphore::operator+=(unsigned c) { for (unsigned i = 0; i < c; ++i) ++*this; return *this; } # if defined __APPLE__ int flag; void fun_timeout(int fl) { flag = 0; } # endif bool Semaphore::uget(utime_t useconds) { int err; do { if (useconds == 0) err = sem_wait(sem_); # if defined __APPLE__ else { struct itimerval it; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 0; it.it_value.tv_sec = useconds / 1000000; it.it_value.tv_usec = useconds % 1000000; flag = 1; signal(SIGALRM, fun_timeout); setitimer(ITIMER_REAL, &it, NULL); do { err = sem_trywait(sem_); } while (flag && err == -1 && errno == EAGAIN); if (!flag) err = -1; } # else else { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += useconds / 1000000; ts.tv_nsec += (useconds % 1000000) * 1000; err = sem_timedwait(sem_, &ts); } # endif } while (err == -1 && errno == EINTR); # if defined __APPLE__ if (!flag) return false; # else if (err && errno == ETIMEDOUT) return false; # endif if (err) { destroy(); errabort("sem_wait"); } return true; } bool Semaphore::get(unsigned seconds) { return uget(seconds * 1000 * 1000); } Semaphore::operator int() { int res; if (sem_getvalue(sem_, &res)) { destroy(); errabort("sem_getvalue"); } return res; } } // namespace libport
Delete useless debug output.
Delete useless debug output. * lib/libport/semaphore.cc: here.
C++
bsd-3-clause
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
3663d7579b252dde77e1cebc9779a59912ef2a5b
tests/benchmarks/declarative/painting/paintbenchmark.cpp
tests/benchmarks/declarative/painting/paintbenchmark.cpp
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QPixmap> #include <QImage> #include <QPainter> #include <QGLWidget> #include <QTextLayout> #include <QVBoxLayout> #include <QTime> #include <QDebug> #include <QStaticText> int iterations = 20; const int count = 600; const int lines = 12; const int spacing = 36; QSizeF size(1000, 800); const qreal lineWidth = 1000; QString strings[lines]; QGLWidget *testWidget = 0; void paint_QTextLayout(QPainter &p, bool useCache) { static bool first = true; static QTextLayout *textLayout[lines]; if (first) { for (int i = 0; i < lines; ++i) { textLayout[i] = new QTextLayout(strings[i]); int leading = p.fontMetrics().leading(); qreal height = 0; qreal widthUsed = 0; textLayout[i]->setCacheEnabled(useCache); textLayout[i]->beginLayout(); while (1) { QTextLine line = textLayout[i]->createLine(); if (!line.isValid()) break; line.setLineWidth(lineWidth); height += leading; line.setPosition(QPointF(0, height)); height += line.height(); widthUsed = qMax(widthUsed, line.naturalTextWidth()); } textLayout[i]->endLayout(); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { textLayout[j]->draw(&p, QPoint(0, j*spacing)); } } } void paint_QTextLayout_noCache(QPainter &p) { paint_QTextLayout(p, false); } void paint_QTextLayout_cache(QPainter &p) { paint_QTextLayout(p, true); } void paint_QStaticText(QPainter &p, bool useOptimizations) { static QStaticText *staticText[lines]; static bool first = true; if (first) { for (int i = 0; i < lines; ++i) { staticText[i] = new QStaticText(strings[i]); if (useOptimizations) staticText[i]->setPerformanceHint(QStaticText::AggressiveCaching); else staticText[i]->setPerformanceHint(QStaticText::ModerateCaching); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { p.drawStaticText(QPointF(0, 30 + j*spacing), *staticText[j]); } } } void paint_QStaticText_noOptimizations(QPainter &p) { paint_QStaticText(p, false); } void paint_QStaticText_optimizations(QPainter &p) { paint_QStaticText(p, true); } void paint_QPixmapCachedText(QPainter &p) { static bool first = true; static QPixmap cacheText[lines]; if (first) { for (int i = 0; i < lines; ++i) { QRectF trueSize; trueSize = p.boundingRect(QRectF(QPointF(0,0), size), 0, strings[i]); cacheText[i] = QPixmap(trueSize.size().toSize()); cacheText[i].fill(Qt::transparent); QPainter paint(&cacheText[i]); paint.setPen(Qt::black); paint.drawText(QRectF(QPointF(0,0), trueSize.size().toSize()), strings[i]); } first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap(0,j*spacing,cacheText[j]); } } } void paint_RoundedRect(QPainter &p) { static bool first = true; if (first) { if (testWidget) { QGLFormat format = testWidget->format(); if (!format.sampleBuffers()) qWarning() << "Cannot paint antialiased rounded rect without sampleBuffers"; } first = false; } p.setRenderHint(QPainter::Antialiasing, true); p.setPen(Qt::black); p.setBrush(Qt::red); for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { QSize size((j+1)*50, spacing-1); p.drawRoundedRect(QRectF(QPointF(0,j*spacing), size), 8, 8); } } } void paint_QPixmapCachedRoundedRect(QPainter &p) { static bool first = true; static QPixmap cacheRect; if (first) { const int pw = 0; const int radius = 8; cacheRect = QPixmap(radius*2 + 3 + pw*2, radius*2 + 3 + pw*2); cacheRect.fill(Qt::transparent); QPainter paint(&cacheRect); paint.setRenderHint(QPainter::Antialiasing); paint.setPen(Qt::black); paint.setBrush(Qt::red); if (pw%2) paint.drawRoundedRect(QRectF(qreal(pw)/2+1, qreal(pw)/2+1, cacheRect.width()-(pw+1), cacheRect.height()-(pw+1)), radius, radius); else paint.drawRoundedRect(QRectF(qreal(pw)/2, qreal(pw)/2, cacheRect.width()-pw, cacheRect.height()-pw), radius, radius); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { QSize size((j+1)*50, spacing-1); p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, true); const int pw = 0; int xOffset = (cacheRect.width()-1)/2; int yOffset = (cacheRect.height()-1)/2; QMargins margins(xOffset, yOffset, xOffset, yOffset); QTileRules rules(Qt::StretchTile, Qt::StretchTile); //NOTE: even though our item may have qreal-based width and height, qDrawBorderPixmap only supports QRects qDrawBorderPixmap(&p, QRect(-pw/2, j*spacing-pw/2, size.width()+pw, size.height()+pw), margins, cacheRect, cacheRect.rect(), margins, rules); } } } void paint_QPixmap63x63_opaque(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/63x63_opaque.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } void paint_QPixmap64x64_opaque(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/64x64_opaque.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } void paint_QPixmap63x63(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/63x63.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } void paint_QPixmap64x64(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/64x64.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } typedef void(*PaintFunc)(QPainter &); struct { const char *name; PaintFunc func; } funcs[] = { { "QTextLayoutNoCache", &paint_QTextLayout_noCache }, { "QTextLayoutWithCache", &paint_QTextLayout_cache }, { "QStaticTextNoBackendOptimizations", &paint_QStaticText_noOptimizations }, { "QStaticTextWithBackendOptimizations", &paint_QStaticText_optimizations }, { "CachedText", &paint_QPixmapCachedText }, { "RoundedRect", &paint_RoundedRect }, { "CachedRoundedRect", &paint_QPixmapCachedRoundedRect }, { "QPixmap63x63_opaque", &paint_QPixmap63x63_opaque }, { "QPixmap64x64_opaque", &paint_QPixmap64x64_opaque }, { "QPixmap63x63", &paint_QPixmap63x63 }, { "QPixmap64x64", &paint_QPixmap64x64 }, { 0, 0 } }; PaintFunc testFunc = 0; class MyGLWidget : public QGLWidget { public: MyGLWidget(const QGLFormat &format) : QGLWidget(format), frames(0) { const char chars[] = "abcd efgh ijkl mnop qrst uvwx yz!$. ABCD 1234"; int len = strlen(chars); for (int i = 0; i < lines; ++i) { for (int j = 0; j < 60; j++) { strings[i] += QChar(chars[rand() % len]); } } } void paintEvent(QPaintEvent *) { static int last = 0; static bool firstRun = true; if (firstRun) { timer.start(); firstRun = false; } else { int elapsed = timer.elapsed(); qDebug() << "frame elapsed:" << elapsed - last; last = elapsed; } QPainter p(this); p.fillRect(rect(), Qt::white); p.setPen(Qt::black); QTime drawTimer; drawTimer.start(); testFunc(p); qDebug() << "draw time" << drawTimer.elapsed(); if (iterations--) update(); else qApp->quit(); } QTime timer; int frames; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); bool sampleBuffers = false; for (int i = 1; i < argc; ++i) { QString arg = argv[i]; if (arg == "-test") { arg = argv[++i]; int j = 0; while (funcs[j].name) { if (arg == funcs[j].name) { testFunc = funcs[j].func; qDebug() << "Running test" << arg; break; } ++j; } } else if (arg == "-iterations") { arg = argv[++i]; iterations = arg.toInt(); } else if (arg == "-sampleBuffers") { sampleBuffers = true; } } if (testFunc == 0) { qDebug() << "Usage: textspeed -test <test> [-sampleBuffers] [-iterations n]"; qDebug() << "where <test> can be:"; int j = 0; while (funcs[j].name) { qDebug() << " " << funcs[j].name; ++j; } exit(1); } QWidget w; QGLFormat format = QGLFormat::defaultFormat(); format.setSampleBuffers(sampleBuffers); testWidget = new MyGLWidget(format); testWidget->setAutoFillBackground(false); QVBoxLayout *layout = new QVBoxLayout(&w); w.setLayout(layout); layout->addWidget(testWidget); w.showFullScreen(); app.exec(); return 0; }
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QPixmap> #include <QImage> #include <QPainter> #include <QPainterPath> #include <QGLWidget> #include <QTextLayout> #include <QVBoxLayout> #include <QTime> #include <QDebug> #include <QStaticText> int iterations = 20; const int count = 600; const int lines = 12; const int spacing = 36; QSizeF size(1000, 800); const qreal lineWidth = 1000; QString strings[lines]; QGLWidget *testWidget = 0; void paint_QTextLayout(QPainter &p, bool useCache) { static bool first = true; static QTextLayout *textLayout[lines]; if (first) { for (int i = 0; i < lines; ++i) { textLayout[i] = new QTextLayout(strings[i]); int leading = p.fontMetrics().leading(); qreal height = 0; qreal widthUsed = 0; textLayout[i]->setCacheEnabled(useCache); textLayout[i]->beginLayout(); while (1) { QTextLine line = textLayout[i]->createLine(); if (!line.isValid()) break; line.setLineWidth(lineWidth); height += leading; line.setPosition(QPointF(0, height)); height += line.height(); widthUsed = qMax(widthUsed, line.naturalTextWidth()); } textLayout[i]->endLayout(); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { textLayout[j]->draw(&p, QPoint(0, j*spacing)); } } } void paint_QTextLayout_noCache(QPainter &p) { paint_QTextLayout(p, false); } void paint_QTextLayout_cache(QPainter &p) { paint_QTextLayout(p, true); } void paint_QStaticText(QPainter &p, bool useOptimizations) { static QStaticText *staticText[lines]; static bool first = true; if (first) { for (int i = 0; i < lines; ++i) { staticText[i] = new QStaticText(strings[i]); if (useOptimizations) staticText[i]->setPerformanceHint(QStaticText::AggressiveCaching); else staticText[i]->setPerformanceHint(QStaticText::ModerateCaching); } first = false; } for (int i = 0; i < count; ++i) { for (int j = 0; j < lines; ++j) { p.drawStaticText(QPointF(0, 30 + j*spacing), *staticText[j]); } } } void paint_QStaticText_noOptimizations(QPainter &p) { paint_QStaticText(p, false); } void paint_QStaticText_optimizations(QPainter &p) { paint_QStaticText(p, true); } void paint_QPixmapCachedText(QPainter &p) { static bool first = true; static QPixmap cacheText[lines]; if (first) { for (int i = 0; i < lines; ++i) { QRectF trueSize; trueSize = p.boundingRect(QRectF(QPointF(0,0), size), 0, strings[i]); cacheText[i] = QPixmap(trueSize.size().toSize()); cacheText[i].fill(Qt::transparent); QPainter paint(&cacheText[i]); paint.setPen(Qt::black); paint.drawText(QRectF(QPointF(0,0), trueSize.size().toSize()), strings[i]); } first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap(0,j*spacing,cacheText[j]); } } } void paint_RoundedRect(QPainter &p) { static bool first = true; if (first) { if (testWidget) { QGLFormat format = testWidget->format(); if (!format.sampleBuffers()) qWarning() << "Cannot paint antialiased rounded rect without sampleBuffers"; } first = false; } p.setRenderHint(QPainter::Antialiasing, true); p.setPen(Qt::black); p.setBrush(Qt::red); for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { QSize size((j+1)*50, spacing-1); p.drawRoundedRect(QRectF(QPointF(0,j*spacing), size), 8, 8); } } } void paint_QPixmapCachedRoundedRect(QPainter &p) { static bool first = true; static QPixmap cacheRect; if (first) { const int pw = 0; const int radius = 8; cacheRect = QPixmap(radius*2 + 3 + pw*2, radius*2 + 3 + pw*2); cacheRect.fill(Qt::transparent); QPainter paint(&cacheRect); paint.setRenderHint(QPainter::Antialiasing); paint.setPen(Qt::black); paint.setBrush(Qt::red); if (pw%2) paint.drawRoundedRect(QRectF(qreal(pw)/2+1, qreal(pw)/2+1, cacheRect.width()-(pw+1), cacheRect.height()-(pw+1)), radius, radius); else paint.drawRoundedRect(QRectF(qreal(pw)/2, qreal(pw)/2, cacheRect.width()-pw, cacheRect.height()-pw), radius, radius); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { QSize size((j+1)*50, spacing-1); p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, true); const int pw = 0; int xOffset = (cacheRect.width()-1)/2; int yOffset = (cacheRect.height()-1)/2; QMargins margins(xOffset, yOffset, xOffset, yOffset); QTileRules rules(Qt::StretchTile, Qt::StretchTile); //NOTE: even though our item may have qreal-based width and height, qDrawBorderPixmap only supports QRects qDrawBorderPixmap(&p, QRect(-pw/2, j*spacing-pw/2, size.width()+pw, size.height()+pw), margins, cacheRect, cacheRect.rect(), margins, rules); } } } void paint_pathCacheRoundedRect(QPainter &p) { static bool first = true; static QPainterPath path[lines]; if (first) { for (int j = 0; j < lines; ++j) { path[j].addRoundedRect(QRectF(0,0,(j+1)*50, spacing-1), 8, 8); } first = false; } p.setRenderHint(QPainter::Antialiasing, true); p.setPen(Qt::black); p.setBrush(Qt::red); for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.translate(0,j*spacing); p.drawPath(path[j]); p.translate(0,-j*spacing); } } } void paint_QPixmap63x63_opaque(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/63x63_opaque.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } void paint_QPixmap64x64_opaque(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/64x64_opaque.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } void paint_QPixmap63x63(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/63x63.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } void paint_QPixmap64x64(QPainter &p) { static bool first = true; static QPixmap pm; if (first) { pm.load("data/64x64.png"); first = false; } for (int i = 0; i < count; i++) { for (int j = 0; j < lines; ++j) { p.drawPixmap((i%10) * 64,j*spacing, pm); } } } typedef void(*PaintFunc)(QPainter &); struct { const char *name; PaintFunc func; } funcs[] = { { "QTextLayoutNoCache", &paint_QTextLayout_noCache }, { "QTextLayoutWithCache", &paint_QTextLayout_cache }, { "QStaticTextNoBackendOptimizations", &paint_QStaticText_noOptimizations }, { "QStaticTextWithBackendOptimizations", &paint_QStaticText_optimizations }, { "CachedText", &paint_QPixmapCachedText }, { "RoundedRect", &paint_RoundedRect }, { "CachedRoundedRect", &paint_QPixmapCachedRoundedRect }, { "PathCacheRoundedRect", &paint_pathCacheRoundedRect }, { "QPixmap63x63_opaque", &paint_QPixmap63x63_opaque }, { "QPixmap64x64_opaque", &paint_QPixmap64x64_opaque }, { "QPixmap63x63", &paint_QPixmap63x63 }, { "QPixmap64x64", &paint_QPixmap64x64 }, { 0, 0 } }; PaintFunc testFunc = 0; class MyGLWidget : public QGLWidget { public: MyGLWidget(const QGLFormat &format) : QGLWidget(format), frames(0) { const char chars[] = "abcd efgh ijkl mnop qrst uvwx yz!$. ABCD 1234"; int len = strlen(chars); for (int i = 0; i < lines; ++i) { for (int j = 0; j < 60; j++) { strings[i] += QChar(chars[rand() % len]); } } } void paintEvent(QPaintEvent *) { static int last = 0; static bool firstRun = true; if (firstRun) { timer.start(); firstRun = false; } else { int elapsed = timer.elapsed(); qDebug() << "frame elapsed:" << elapsed - last; last = elapsed; } QPainter p(this); p.fillRect(rect(), Qt::white); p.setPen(Qt::black); QTime drawTimer; drawTimer.start(); testFunc(p); qDebug() << "draw time" << drawTimer.elapsed(); if (iterations--) update(); else qApp->quit(); } QTime timer; int frames; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); bool sampleBuffers = false; for (int i = 1; i < argc; ++i) { QString arg = argv[i]; if (arg == "-test") { arg = argv[++i]; int j = 0; while (funcs[j].name) { if (arg == funcs[j].name) { testFunc = funcs[j].func; qDebug() << "Running test" << arg; break; } ++j; } } else if (arg == "-iterations") { arg = argv[++i]; iterations = arg.toInt(); } else if (arg == "-sampleBuffers") { sampleBuffers = true; } } if (testFunc == 0) { qDebug() << "Usage: textspeed -test <test> [-sampleBuffers] [-iterations n]"; qDebug() << "where <test> can be:"; int j = 0; while (funcs[j].name) { qDebug() << " " << funcs[j].name; ++j; } exit(1); } QWidget w; QGLFormat format = QGLFormat::defaultFormat(); format.setSampleBuffers(sampleBuffers); testWidget = new MyGLWidget(format); testWidget->setAutoFillBackground(false); QVBoxLayout *layout = new QVBoxLayout(&w); w.setLayout(layout); layout->addWidget(testWidget); w.showFullScreen(); app.exec(); return 0; }
Add cached path rounded rect painting benchmark.
Add cached path rounded rect painting benchmark.
C++
lgpl-2.1
pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk
8e1a1e1eedbf5b551b4fe4799dab8b36267638ba
thrift/lib/cpp2/security/KerberosSASLHandshakeServer.cpp
thrift/lib/cpp2/security/KerberosSASLHandshakeServer.cpp
/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/security/KerberosSASLHandshakeServer.h> #include <gssapi/gssapi_generic.h> #include <gssapi/gssapi_krb5.h> #include <krb5.h> #include <stdlib.h> #include <folly/io/IOBuf.h> #include <folly/io/Cursor.h> using namespace std; using namespace apache::thrift; using namespace folly; /** * Server functions. */ KerberosSASLHandshakeServer::KerberosSASLHandshakeServer() : phase_(INIT), securityMech_(SecurityMech::KRB5_SASL) { // Set required security properties, we can define setters for these if // they need to be modified later. minimumRequiredSecContextFlags_ = GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG | GSS_C_INTEG_FLAG | GSS_C_CONF_FLAG; serverName_ = GSS_C_NO_NAME; serverCreds_ = GSS_C_NO_CREDENTIAL; client_ = GSS_C_NO_NAME; context_ = GSS_C_NO_CONTEXT; contextStatus_ = GSS_S_NO_CONTEXT; // Bitmask specifying a requirement for all security layers and max // buffer length from the protocol. If we ever allow different security layer // properties, this would need to become more dynamic. securityLayerBitmask_ = 0x07ffffff; securityLayerBitmaskBuffer_ = IOBuf::create(sizeof(securityLayerBitmask_)); io::Appender b(securityLayerBitmaskBuffer_.get(), 0); b.writeBE(securityLayerBitmask_); } KerberosSASLHandshakeServer::~KerberosSASLHandshakeServer() { OM_uint32 min_stat; if (context_ != GSS_C_NO_CONTEXT) { gss_delete_sec_context(&min_stat, &context_, GSS_C_NO_BUFFER); } if (serverName_ != GSS_C_NO_NAME) { gss_release_name(&min_stat, &serverName_); } if (serverCreds_ != GSS_C_NO_CREDENTIAL) { gss_release_cred(&min_stat, &serverCreds_); } if (client_ != GSS_C_NO_NAME) { gss_release_name(&min_stat, &client_); } } void KerberosSASLHandshakeServer::setSecurityMech(const SecurityMech mech) { securityMech_ = mech; if (mech == SecurityMech::KRB5_GSS_NO_MUTUAL) { minimumRequiredSecContextFlags_ &= ~GSS_C_MUTUAL_FLAG; } else { minimumRequiredSecContextFlags_ |= GSS_C_MUTUAL_FLAG; } } SecurityMech KerberosSASLHandshakeServer::getSecurityMech() { return securityMech_; } void KerberosSASLHandshakeServer::initServer() { assert(phase_ == INIT); OM_uint32 maj_stat, min_stat; context_ = GSS_C_NO_CONTEXT; if (servicePrincipal_.size() > 0) { gss_buffer_desc service_principal_token; service_principal_token.value = (void *)servicePrincipal_.c_str(); service_principal_token.length = servicePrincipal_.size() + 1; maj_stat = gss_import_name( &min_stat, &service_principal_token, (gss_OID) gss_nt_krb5_name, &serverName_); if (maj_stat != GSS_S_COMPLETE) { KerberosSASLHandshakeUtils::throwGSSException( "Error initiating server credentials", maj_stat, min_stat); } maj_stat = gss_acquire_cred( &min_stat, serverName_, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_ACCEPT, &serverCreds_, nullptr, nullptr ); if (maj_stat != GSS_S_COMPLETE) { KerberosSASLHandshakeUtils::throwGSSException( "Error establishing server credentials", maj_stat, min_stat); } } phase_ = ESTABLISH_CONTEXT; } void KerberosSASLHandshakeServer::acceptSecurityContext() { assert(phase_ == ESTABLISH_CONTEXT); OM_uint32 min_stat; outputToken_.reset(new gss_buffer_desc); *outputToken_ = GSS_C_EMPTY_BUFFER; if (client_ != GSS_C_NO_NAME) { gss_release_name(&min_stat, &client_); } contextStatus_ = gss_accept_sec_context( &min_stat, &context_, serverCreds_, inputToken_.get(), GSS_C_NO_CHANNEL_BINDINGS, &client_, &doid_, outputToken_.get(), &retFlags_, nullptr, // time_rec nullptr // del_cred_handle ); if (contextStatus_ != GSS_S_COMPLETE && contextStatus_ != GSS_S_CONTINUE_NEEDED) { KerberosSASLHandshakeUtils::throwGSSException( "Error initiating server context", contextStatus_, min_stat); } if (contextStatus_ == GSS_S_COMPLETE) { KerberosSASLHandshakeUtils::getContextData( context_, contextLifetime_, contextSecurityFlags_, establishedClientPrincipal_, establishedServicePrincipal_); if ((minimumRequiredSecContextFlags_ & contextSecurityFlags_) != minimumRequiredSecContextFlags_) { throw TKerberosException("Not all security properties established"); } phase_ = (securityMech_ == SecurityMech::KRB5_GSS_NO_MUTUAL || securityMech_ == SecurityMech::KRB5_GSS) ? COMPLETE : CONTEXT_NEGOTIATION_COMPLETE; } } std::unique_ptr<std::string> KerberosSASLHandshakeServer::getTokenToSend() { switch(phase_) { case INIT: // Should not call this function if in INIT state assert(false); case ESTABLISH_CONTEXT: case CONTEXT_NEGOTIATION_COMPLETE: // If the server is establishing a security context or has completed // it, it may still need to send a token back so the client can // finish establishing it's context. return unique_ptr<string>( new string((const char*) outputToken_->value, outputToken_->length)); break; case SELECT_SECURITY_LAYER: { unique_ptr<IOBuf> wrapped_sec_layer_message = wrapMessage( IOBuf::copyBuffer( securityLayerBitmaskBuffer_->data(), securityLayerBitmaskBuffer_->length())); wrapped_sec_layer_message->coalesce(); return unique_ptr<string>(new string( (char *)wrapped_sec_layer_message->data(), wrapped_sec_layer_message->length() )); break; } case COMPLETE: { if (securityMech_ == SecurityMech::KRB5_GSS_NO_MUTUAL) { // Don't send anything back to the client if we're not doing mutual auth break; } // In the gss only case, we still want to send the token to the client, // even if the server handshake completed. if (securityMech_ == SecurityMech::KRB5_GSS) { return unique_ptr<string>( new string((const char*) outputToken_->value, outputToken_->length)); } else { // Send empty token back return unique_ptr<string>(new string("")); } break; } default: break; } return nullptr; } void KerberosSASLHandshakeServer::handleResponse(const string& msg) { unique_ptr<IOBuf> unwrapped_security_layer_msg; switch(phase_) { case INIT: initServer(); phase_ = ESTABLISH_CONTEXT; // fall through to phase 1 case ESTABLISH_CONTEXT: if (inputToken_ == nullptr) { inputToken_.reset(new gss_buffer_desc); } inputToken_->length = msg.length(); inputTokenValue_ = vector<unsigned char>(msg.begin(), msg.end()); inputToken_->value = &inputTokenValue_[0]; acceptSecurityContext(); break; case CONTEXT_NEGOTIATION_COMPLETE: // This state will send out a security layer bitmask, // max buffer size, and authorization identity. phase_ = SELECT_SECURITY_LAYER; break; case SELECT_SECURITY_LAYER: { // Here we unwrap the message and make sure that it has the correct // security properties. unique_ptr<IOBuf> unwrapped_security_layer_msg = unwrapMessage( IOBuf::copyBuffer(msg)); io::Cursor c = io::Cursor(unwrapped_security_layer_msg.get()); uint32_t security_layers = c.readBE<uint32_t>(); if ((security_layers & securityLayerBitmask_) >> 24 == 0 || (security_layers & 0x00ffffff) != 0x00ffffff) { // the top 8 bits contain: // in security_layers (received from client): // selected layer // in securityLayerBitmask_ (local): // a bitmask of the available layers // bottom 3 bytes contain the max buffer size throw TKerberosException("Security layer negotiation failed"); } phase_ = COMPLETE; break; } default: break; } } bool KerberosSASLHandshakeServer::isContextEstablished() { return phase_ == COMPLETE; } PhaseType KerberosSASLHandshakeServer::getPhase() { return phase_; } void KerberosSASLHandshakeServer::setRequiredServicePrincipal( const std::string& service) { assert(phase_ == INIT); servicePrincipal_ = service; } const string& KerberosSASLHandshakeServer::getEstablishedServicePrincipal() const { assert(phase_ == COMPLETE); return establishedServicePrincipal_; } const string& KerberosSASLHandshakeServer::getEstablishedClientPrincipal() const { assert(phase_ == COMPLETE); return establishedClientPrincipal_; } unique_ptr<folly::IOBuf> KerberosSASLHandshakeServer::wrapMessage( unique_ptr<folly::IOBuf>&& buf) { assert(contextStatus_ == GSS_S_COMPLETE); return KerberosSASLHandshakeUtils::wrapMessage( context_, std::move(buf) ); } unique_ptr<folly::IOBuf> KerberosSASLHandshakeServer::unwrapMessage( unique_ptr<folly::IOBuf>&& buf) { assert(contextStatus_ == GSS_S_COMPLETE); return KerberosSASLHandshakeUtils::unwrapMessage( context_, std::move(buf) ); }
/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/security/KerberosSASLHandshakeServer.h> #include <gssapi/gssapi_generic.h> #include <gssapi/gssapi_krb5.h> #include <krb5.h> #include <stdlib.h> #include <folly/io/IOBuf.h> #include <folly/io/Cursor.h> using namespace std; using namespace apache::thrift; using namespace folly; /** * Server functions. */ KerberosSASLHandshakeServer::KerberosSASLHandshakeServer() : phase_(INIT), securityMech_(SecurityMech::KRB5_SASL) { // Set required security properties, we can define setters for these if // they need to be modified later. minimumRequiredSecContextFlags_ = GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG | GSS_C_INTEG_FLAG | GSS_C_CONF_FLAG; serverName_ = GSS_C_NO_NAME; serverCreds_ = GSS_C_NO_CREDENTIAL; client_ = GSS_C_NO_NAME; context_ = GSS_C_NO_CONTEXT; contextStatus_ = GSS_S_NO_CONTEXT; // Bitmask specifying a requirement for all security layers and max // buffer length from the protocol. If we ever allow different security layer // properties, this would need to become more dynamic. securityLayerBitmask_ = 0x07ffffff; securityLayerBitmaskBuffer_ = IOBuf::create(sizeof(securityLayerBitmask_)); io::Appender b(securityLayerBitmaskBuffer_.get(), 0); b.writeBE(securityLayerBitmask_); } KerberosSASLHandshakeServer::~KerberosSASLHandshakeServer() { OM_uint32 min_stat; if (context_ != GSS_C_NO_CONTEXT) { gss_delete_sec_context(&min_stat, &context_, GSS_C_NO_BUFFER); } if (serverName_ != GSS_C_NO_NAME) { gss_release_name(&min_stat, &serverName_); } if (serverCreds_ != GSS_C_NO_CREDENTIAL) { gss_release_cred(&min_stat, &serverCreds_); } if (client_ != GSS_C_NO_NAME) { gss_release_name(&min_stat, &client_); } } void KerberosSASLHandshakeServer::setSecurityMech(const SecurityMech mech) { securityMech_ = mech; if (mech == SecurityMech::KRB5_GSS_NO_MUTUAL) { minimumRequiredSecContextFlags_ &= ~GSS_C_MUTUAL_FLAG; } else { minimumRequiredSecContextFlags_ |= GSS_C_MUTUAL_FLAG; } } SecurityMech KerberosSASLHandshakeServer::getSecurityMech() { return securityMech_; } void KerberosSASLHandshakeServer::initServer() { assert(phase_ == INIT); OM_uint32 maj_stat, min_stat; context_ = GSS_C_NO_CONTEXT; if (servicePrincipal_.size() > 0) { gss_buffer_desc service_principal_token; service_principal_token.value = (void *)servicePrincipal_.c_str(); service_principal_token.length = servicePrincipal_.size() + 1; maj_stat = gss_import_name( &min_stat, &service_principal_token, (gss_OID) gss_nt_krb5_name, &serverName_); if (maj_stat != GSS_S_COMPLETE) { KerberosSASLHandshakeUtils::throwGSSException( "Error initiating server credentials", maj_stat, min_stat); } maj_stat = gss_acquire_cred( &min_stat, serverName_, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_ACCEPT, &serverCreds_, nullptr, nullptr ); if (maj_stat != GSS_S_COMPLETE) { KerberosSASLHandshakeUtils::throwGSSException( "Error establishing server credentials", maj_stat, min_stat); } } phase_ = ESTABLISH_CONTEXT; } void KerberosSASLHandshakeServer::acceptSecurityContext() { assert(phase_ == ESTABLISH_CONTEXT); OM_uint32 min_stat; outputToken_.reset(new gss_buffer_desc); *outputToken_ = GSS_C_EMPTY_BUFFER; if (client_ != GSS_C_NO_NAME) { gss_release_name(&min_stat, &client_); } contextStatus_ = gss_accept_sec_context( &min_stat, &context_, serverCreds_, inputToken_.get(), GSS_C_NO_CHANNEL_BINDINGS, &client_, &doid_, outputToken_.get(), &retFlags_, nullptr, // time_rec nullptr // del_cred_handle ); if (contextStatus_ != GSS_S_COMPLETE && contextStatus_ != GSS_S_CONTINUE_NEEDED) { KerberosSASLHandshakeUtils::throwGSSException( "Error initiating server context", contextStatus_, min_stat); } if (contextStatus_ == GSS_S_COMPLETE) { KerberosSASLHandshakeUtils::getContextData( context_, contextLifetime_, contextSecurityFlags_, establishedClientPrincipal_, establishedServicePrincipal_); if ((minimumRequiredSecContextFlags_ & contextSecurityFlags_) != minimumRequiredSecContextFlags_) { throw TKerberosException("Not all security properties established"); } phase_ = (securityMech_ == SecurityMech::KRB5_GSS_NO_MUTUAL || securityMech_ == SecurityMech::KRB5_GSS) ? COMPLETE : CONTEXT_NEGOTIATION_COMPLETE; } } std::unique_ptr<std::string> KerberosSASLHandshakeServer::getTokenToSend() { switch(phase_) { case INIT: // Should not call this function if in INIT state assert(false); case ESTABLISH_CONTEXT: case CONTEXT_NEGOTIATION_COMPLETE: // If the server is establishing a security context or has completed // it, it may still need to send a token back so the client can // finish establishing it's context. return unique_ptr<string>( new string((const char*) outputToken_->value, outputToken_->length)); break; case SELECT_SECURITY_LAYER: { unique_ptr<IOBuf> wrapped_sec_layer_message = wrapMessage( IOBuf::copyBuffer( securityLayerBitmaskBuffer_->data(), securityLayerBitmaskBuffer_->length())); wrapped_sec_layer_message->coalesce(); return unique_ptr<string>(new string( (char *)wrapped_sec_layer_message->data(), wrapped_sec_layer_message->length() )); break; } case COMPLETE: { if (securityMech_ == SecurityMech::KRB5_GSS_NO_MUTUAL) { // Don't send anything back to the client if we're not doing mutual auth break; } // In the gss only case, we still want to send the token to the client, // even if the server handshake completed. if (securityMech_ == SecurityMech::KRB5_GSS) { return unique_ptr<string>( new string((const char*) outputToken_->value, outputToken_->length)); } else { // Send empty token back return unique_ptr<string>(new string("")); } break; } default: break; } return nullptr; } void KerberosSASLHandshakeServer::handleResponse(const string& msg) { switch(phase_) { case INIT: initServer(); phase_ = ESTABLISH_CONTEXT; // fall through to phase 1 case ESTABLISH_CONTEXT: if (inputToken_ == nullptr) { inputToken_.reset(new gss_buffer_desc); } inputToken_->length = msg.length(); inputTokenValue_ = vector<unsigned char>(msg.begin(), msg.end()); inputToken_->value = &inputTokenValue_[0]; acceptSecurityContext(); break; case CONTEXT_NEGOTIATION_COMPLETE: // This state will send out a security layer bitmask, // max buffer size, and authorization identity. phase_ = SELECT_SECURITY_LAYER; break; case SELECT_SECURITY_LAYER: { // Here we unwrap the message and make sure that it has the correct // security properties. unique_ptr<IOBuf> unwrapped_security_layer_msg = unwrapMessage( IOBuf::copyBuffer(msg)); io::Cursor c = io::Cursor(unwrapped_security_layer_msg.get()); uint32_t security_layers = c.readBE<uint32_t>(); if ((security_layers & securityLayerBitmask_) >> 24 == 0 || (security_layers & 0x00ffffff) != 0x00ffffff) { // the top 8 bits contain: // in security_layers (received from client): // selected layer // in securityLayerBitmask_ (local): // a bitmask of the available layers // bottom 3 bytes contain the max buffer size throw TKerberosException("Security layer negotiation failed"); } phase_ = COMPLETE; break; } default: break; } } bool KerberosSASLHandshakeServer::isContextEstablished() { return phase_ == COMPLETE; } PhaseType KerberosSASLHandshakeServer::getPhase() { return phase_; } void KerberosSASLHandshakeServer::setRequiredServicePrincipal( const std::string& service) { assert(phase_ == INIT); servicePrincipal_ = service; } const string& KerberosSASLHandshakeServer::getEstablishedServicePrincipal() const { assert(phase_ == COMPLETE); return establishedServicePrincipal_; } const string& KerberosSASLHandshakeServer::getEstablishedClientPrincipal() const { assert(phase_ == COMPLETE); return establishedClientPrincipal_; } unique_ptr<folly::IOBuf> KerberosSASLHandshakeServer::wrapMessage( unique_ptr<folly::IOBuf>&& buf) { assert(contextStatus_ == GSS_S_COMPLETE); return KerberosSASLHandshakeUtils::wrapMessage( context_, std::move(buf) ); } unique_ptr<folly::IOBuf> KerberosSASLHandshakeServer::unwrapMessage( unique_ptr<folly::IOBuf>&& buf) { assert(contextStatus_ == GSS_S_COMPLETE); return KerberosSASLHandshakeUtils::unwrapMessage( context_, std::move(buf) ); }
remove bogus declaration
thrift/lib/cpp2/security/KerberosSASLHandshakeServer.cpp: remove bogus declaration Summary: Remove unused (shadowing) declaration. Reviewed By: mhorowitz Differential Revision: D3979027 fbshipit-source-id: 09bb982d4862989ccce8800a3ccb1670bc50d35c
C++
apache-2.0
getyourguide/fbthrift,getyourguide/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,facebook/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,getyourguide/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,SergeyMakarenko/fbthrift
cae3aae99e2106d7c61d469cb64d7d882b8f2097
mjolnir/core/NeighborList.hpp
mjolnir/core/NeighborList.hpp
#ifndef MJOLNIR_CORE_NEIGHBOR_LIST_HPP #define MJOLNIR_CORE_NEIGHBOR_LIST_HPP #include <mjolnir/util/range.hpp> #include <mjolnir/util/empty.hpp> #include <type_traits> #include <algorithm> #include <iterator> #include <utility> #include <vector> //! a container for verlet-list, cell-list, and other spatial indexing methods. //! the objectives are //! - store indices of possible partners that has interaction. //! - store pre-calculated parameters. e.g. epsilon_ij = sqrt(eps_i * eps_j) //! for Lennard-Jones takes relatively large computational cost to obtain. //! calculate it for all the possible pairs to make force calculation fast. namespace mjolnir { // google with "empty base optimization(EBO)". // By using EBO, we can compress the object size when `paramT` is a empty class. // without this, empty parameter type consumes 8 byte (on x86_64) because // std::size_t requires 8-byte alignment. namespace detail { // In order to handle `double` or other non-class object, neighbor_element need // another layer that checks `std::is_empty`. If empty, it inherits it and EBO // removes the overhead. If not empty(like `double`), it keeps storage for the // value. `neighbor_elmenet_impl` stores value if `std::true_type` is passed. template<typename paramT, bool IsEmpty> struct neighbor_element_impl; template<typename paramT> struct neighbor_element_impl<paramT, true> : private paramT // for EBO { using parameter_type = paramT; explicit neighbor_element_impl(const parameter_type&) {} explicit neighbor_element_impl(parameter_type&&) {} neighbor_element_impl() = default; ~neighbor_element_impl() = default; neighbor_element_impl(const neighbor_element_impl&) = default; neighbor_element_impl(neighbor_element_impl&&) = default; neighbor_element_impl& operator=(const neighbor_element_impl&) = default; neighbor_element_impl& operator=(neighbor_element_impl&&) = default; parameter_type& parameter() noexcept {return *this;} parameter_type const& parameter() const noexcept {return *this;} }; template<typename paramT> struct neighbor_element_impl<paramT, false> { using parameter_type = paramT; explicit neighbor_element_impl(const parameter_type& p): param(p) {} explicit neighbor_element_impl(parameter_type&& p): param(std::move(p)) {} neighbor_element_impl() = default; ~neighbor_element_impl() = default; neighbor_element_impl(const neighbor_element_impl&) = default; neighbor_element_impl(neighbor_element_impl&&) = default; neighbor_element_impl& operator=(const neighbor_element_impl&) = default; neighbor_element_impl& operator=(neighbor_element_impl&&) = default; parameter_type& parameter() noexcept {return param;} parameter_type const& parameter() const noexcept {return param;} paramT param; }; } // detail template<typename paramT> struct neighbor_element : private detail::neighbor_element_impl<paramT, std::is_empty<paramT>::value> { using base_type = detail::neighbor_element_impl<paramT, std::is_empty<paramT>::value>; using parameter_type = typename base_type::parameter_type; neighbor_element(std::size_t idx, const paramT& p) : base_type(p), index(idx) {} neighbor_element(std::size_t idx, paramT&& p) : base_type(std::move(p)), index(idx) {} neighbor_element() = default; ~neighbor_element() = default; neighbor_element(const neighbor_element&) = default; neighbor_element(neighbor_element&&) = default; neighbor_element& operator=(const neighbor_element&) = default; neighbor_element& operator=(neighbor_element&&) = default; parameter_type& parameter() noexcept {return base_type::parameter();} parameter_type const& parameter() const noexcept {return base_type::parameter();} // paramT param; // derived from neighbor_element_impl std::size_t index; }; // Check the EBO works and the size of neighbor_element with empty class // is equal to the size of `std::size_t index;`. static_assert(sizeof(std::size_t) == sizeof(neighbor_element<empty_t>), "checking neighbor_element reduces size of empty object"); template<typename paramT> inline bool operator==( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index == rhs.index; } template<typename paramT> inline bool operator!=( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index != rhs.index; } template<typename paramT> inline bool operator<( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index < rhs.index; } template<typename paramT> inline bool operator>( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index > rhs.index; } template<typename paramT> inline bool operator<=( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index <= rhs.index; } template<typename paramT> inline bool operator>=( const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs) { return lhs.index >= rhs.index; } // ---------------------------------------------------------------------------- // neighbor list template<typename parameterT> class NeighborList { public: using parameter_type = parameterT; using neighbor_type = neighbor_element<parameter_type>; using container_type = std::vector<neighbor_type>; using range_type = range<typename container_type::const_iterator>; // XXX this contains the list in the following way. // // 1. The neighboring list that has interaction partners of each particle // and the parameter for each pairs (e.g. `q_i*q_j` for electrostatics). // // __partner of p1__ __partner of p2___________ ____ ... pN__ // ' ' ' ' // |{p2,q12}|{p3,q13}|{p4,q24}|{p6,q26}|{p7,q27}|{ ... }| // 0th 1st 2nd 3rd 4th 5th ... M-1 th element // // 2. The range list that contains from where to where the partners are // contained. // +---- partner of p1 starts from 0th element of the above array // | +-- partner of p2 starts from 2nd element of the above array // v v // |0|2|5|...|M| // ^ ^ ^ // +-+-----+-- the last partner of p1 is 2-1 = 1. // +-----+-- the last pertner of p2 is 5-1 = 4. // +-- the last element of pN is M-1. // // This list should have N+1 elements because i-th and (i+1)-th elements of // the list is needed to obtain the partner. // // By doing this, we can reduce the memory resource to have the list. public: NeighborList() = default; ~NeighborList() = default; NeighborList(const NeighborList&) = default; NeighborList(NeighborList&&) = default; NeighborList& operator=(const NeighborList&) = default; NeighborList& operator=(NeighborList&&) = default; void clear() { this->neighbors_.clear(); this->ranges_ .clear(); return; } // assign the partners in range [first, last) as the partner of particle i. template<typename Iterator> void add_list_for(const std::size_t i, Iterator first, Iterator last) { static_assert(std::is_same< typename std::iterator_traits<Iterator>::value_type, neighbor_type >::value, "The iterator must points neighbor type."); if(this->ranges_.size() <= i+1) { this->ranges_.resize(i+2, 0); } assert(ranges_[i] == 0 || ranges_[i] == this->neighbors_.size()); this->ranges_[i] = this->neighbors_.size(); this->ranges_[i+1] = this->neighbors_.size() + std::distance(first, last); // allcoate if the current size is not enough. // XXX // This invalidates iterators because of the re-allocation. // So the `ranges_` cannot have iterators. // The elements of `ranges_` must be indices. this->neighbors_.reserve(neighbors_.size() + std::distance(first, last)); std::copy(first, last, std::back_inserter(this->neighbors_)); return ; } void reserve(const std::size_t approx_neighbors, const std::size_t num_participants, const std::size_t num_particles) { neighbors_.reserve(approx_neighbors * num_participants); ranges_.reserve(num_particles); } std::size_t num_neighbors() const noexcept {return neighbors_.size();} range_type operator[](const std::size_t i) const noexcept { return range_type{ this->neighbors_.begin() + this->ranges_[i], this->neighbors_.begin() + this->ranges_[i+1] }; } range_type at(const std::size_t i) const { return range_type{ this->neighbors_.begin() + this->ranges_.at(i), this->neighbors_.begin() + this->ranges_.at(i+1) }; } // ------------------------------------------------------------------------ // Caution: take great care when you use the following functions. // If possible, use `add_list_for` instead. container_type& neighbors() noexcept {return neighbors_;} std::vector<std::size_t>& ranges() noexcept {return ranges_;} private: container_type neighbors_; std::vector<std::size_t> ranges_; }; } // mjolnir #endif// MJOLNIR_NEIGHBOR_LIST_HPP
#ifndef MJOLNIR_CORE_NEIGHBOR_LIST_HPP #define MJOLNIR_CORE_NEIGHBOR_LIST_HPP #include <mjolnir/util/range.hpp> #include <mjolnir/util/empty.hpp> #include <type_traits> #include <algorithm> #include <iterator> #include <utility> #include <vector> //! a container for verlet-list, cell-list, and other spatial indexing methods. //! the objectives are //! - store indices of possible partners that has interaction. //! - store pre-calculated parameters. e.g. epsilon_ij = sqrt(eps_i * eps_j) //! for Lennard-Jones takes relatively large computational cost to obtain. //! calculate it for all the possible pairs to make force calculation fast. namespace mjolnir { // google with "empty base optimization(EBO)". // By using EBO, we can compress the object size when `paramT` is a empty class. // without this, empty parameter type consumes 8 byte (on x86_64) because // std::size_t requires 8-byte alignment. namespace detail { // In order to handle `double` or other non-class object, neighbor_element need // another layer that checks `std::is_empty`. If empty, it inherits it and EBO // removes the overhead. If not empty(like `double`), it keeps storage for the // value. `neighbor_elmenet_impl` stores value if `std::true_type` is passed. template<typename paramT, bool IsEmpty> struct neighbor_element_impl; template<typename paramT> struct neighbor_element_impl<paramT, true> : private paramT // for EBO { using parameter_type = paramT; explicit neighbor_element_impl(const parameter_type&) {} explicit neighbor_element_impl(parameter_type&&) {} neighbor_element_impl() = default; ~neighbor_element_impl() = default; neighbor_element_impl(const neighbor_element_impl&) = default; neighbor_element_impl(neighbor_element_impl&&) = default; neighbor_element_impl& operator=(const neighbor_element_impl&) = default; neighbor_element_impl& operator=(neighbor_element_impl&&) = default; parameter_type& parameter() noexcept {return *this;} parameter_type const& parameter() const noexcept {return *this;} }; template<typename paramT> struct neighbor_element_impl<paramT, false> { using parameter_type = paramT; explicit neighbor_element_impl(const parameter_type& p): param(p) {} explicit neighbor_element_impl(parameter_type&& p): param(std::move(p)) {} neighbor_element_impl() = default; ~neighbor_element_impl() = default; neighbor_element_impl(const neighbor_element_impl&) = default; neighbor_element_impl(neighbor_element_impl&&) = default; neighbor_element_impl& operator=(const neighbor_element_impl&) = default; neighbor_element_impl& operator=(neighbor_element_impl&&) = default; parameter_type& parameter() noexcept {return param;} parameter_type const& parameter() const noexcept {return param;} paramT param; }; } // detail template<typename paramT> struct neighbor_element : private detail::neighbor_element_impl<paramT, std::is_empty<paramT>::value> { using base_type = detail::neighbor_element_impl<paramT, std::is_empty<paramT>::value>; using parameter_type = typename base_type::parameter_type; neighbor_element(std::size_t idx, const paramT& p) : base_type(p), index(idx) {} neighbor_element(std::size_t idx, paramT&& p) : base_type(std::move(p)), index(idx) {} neighbor_element() = default; ~neighbor_element() = default; neighbor_element(const neighbor_element&) = default; neighbor_element(neighbor_element&&) = default; neighbor_element& operator=(const neighbor_element&) = default; neighbor_element& operator=(neighbor_element&&) = default; parameter_type& parameter() noexcept {return base_type::parameter();} parameter_type const& parameter() const noexcept {return base_type::parameter();} // paramT param; // derived from neighbor_element_impl std::size_t index; }; // Check the EBO works and the size of neighbor_element with empty class // is equal to the size of `std::size_t index;`. static_assert(sizeof(std::size_t) == sizeof(neighbor_element<empty_t>), "checking neighbor_element reduces size of empty object"); template<typename paramT> inline bool operator==( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index == rhs.index; } template<typename paramT> inline bool operator!=( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index != rhs.index; } template<typename paramT> inline bool operator<( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index < rhs.index; } template<typename paramT> inline bool operator>( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index > rhs.index; } template<typename paramT> inline bool operator<=( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index <= rhs.index; } template<typename paramT> inline bool operator>=( const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs) { return lhs.index >= rhs.index; } // ---------------------------------------------------------------------------- // neighbor list template<typename parameterT> class NeighborList { public: using parameter_type = parameterT; using neighbor_type = neighbor_element<parameter_type>; using container_type = std::vector<neighbor_type>; using range_type = range<typename container_type::const_iterator>; // XXX this contains the list in the following way. // // 1. The neighboring list that has interaction partners of each particle // and the parameter for each pairs (e.g. `q_i*q_j` for electrostatics). // // __partner of p1__ __partner of p2___________ ____ ... pN__ // ' ' ' ' // |{p2,q12}|{p3,q13}|{p4,q24}|{p6,q26}|{p7,q27}|{ ... }| // 0th 1st 2nd 3rd 4th 5th ... M-1 th element // // 2. The range list that contains from where to where the partners are // contained. // +---- partner of p1 starts from 0th element of the above array // | +-- partner of p2 starts from 2nd element of the above array // v v // |0|2|5|...|M| // ^ ^ ^ // +-+-----+-- the last partner of p1 is 2-1 = 1. // +-----+-- the last pertner of p2 is 5-1 = 4. // +-- the last element of pN is M-1. // // This list should have N+1 elements because i-th and (i+1)-th elements of // the list is needed to obtain the partner. // // By doing this, we can reduce the memory resource to have the list. public: NeighborList() = default; ~NeighborList() = default; NeighborList(const NeighborList&) = default; NeighborList(NeighborList&&) = default; NeighborList& operator=(const NeighborList&) = default; NeighborList& operator=(NeighborList&&) = default; void clear() { this->neighbors_.clear(); this->ranges_ .clear(); return; } // assign the partners in range [first, last) as the partner of particle i. template<typename Iterator> void add_list_for(const std::size_t i, Iterator first, Iterator last) { static_assert(std::is_same< typename std::iterator_traits<Iterator>::value_type, neighbor_type >::value, "The iterator must points neighbor type."); if(this->ranges_.size() <= i+1) { this->ranges_.resize(i+2, 0); } assert(ranges_[i] == 0 || ranges_[i] == this->neighbors_.size()); this->ranges_[i] = this->neighbors_.size(); this->ranges_[i+1] = this->neighbors_.size() + std::distance(first, last); // allcoate if the current size is not enough. // XXX // This invalidates iterators because of the re-allocation. // So the `ranges_` cannot have iterators. // The elements of `ranges_` must be indices. this->neighbors_.reserve(neighbors_.size() + std::distance(first, last)); std::copy(first, last, std::back_inserter(this->neighbors_)); return ; } void reserve(const std::size_t approx_neighbors, const std::size_t num_participants, const std::size_t num_particles) { neighbors_.reserve(approx_neighbors * num_participants); ranges_.reserve(num_particles); } std::size_t num_neighbors() const noexcept {return neighbors_.size();} range_type operator[](const std::size_t i) const noexcept { return range_type{ this->neighbors_.begin() + this->ranges_[i], this->neighbors_.begin() + this->ranges_[i+1] }; } range_type at(const std::size_t i) const { return range_type{ this->neighbors_.begin() + this->ranges_.at(i), this->neighbors_.begin() + this->ranges_.at(i+1) }; } // ------------------------------------------------------------------------ // Caution: take great care when you use the following functions. // If possible, use `add_list_for` instead. container_type& neighbors() noexcept {return neighbors_;} std::vector<std::size_t>& ranges() noexcept {return ranges_;} private: container_type neighbors_; std::vector<std::size_t> ranges_; }; } // mjolnir #endif// MJOLNIR_NEIGHBOR_LIST_HPP
fix type error in neighbor comparison
fix: fix type error in neighbor comparison
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
78b11aa1bd2b01aa4566a07aa5c1c94ecfd59a0a
source/fe/fe_q.cc
source/fe/fe_q.cc
// --------------------------------------------------------------------- // // Copyright (C) 2000 - 2014 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/base/quadrature_lib.h> #include <deal.II/fe/fe_q.h> #include <vector> #include <sstream> DEAL_II_NAMESPACE_OPEN template <int dim, int spacedim> FE_Q<dim,spacedim>::FE_Q (const unsigned int degree) : FE_Q_Base<TensorProductPolynomials<dim>, dim, spacedim> ( TensorProductPolynomials<dim>(Polynomials::LagrangeEquidistant::generate_complete_basis(degree)), FiniteElementData<dim>(this->get_dpo_vector(degree), 1, degree, FiniteElementData<dim>::H1), std::vector<bool> (1, false)) { Assert (degree > 0, ExcMessage ("This element can only be used for polynomial degrees " "greater than zero")); std::vector<Point<1> > support_points_1d(degree+1); for (unsigned int i=0; i<=degree; ++i) support_points_1d[i][0] = static_cast<double>(i)/degree; this->initialize(support_points_1d); } template <int dim, int spacedim> FE_Q<dim,spacedim>::FE_Q (const Quadrature<1> &points) : FE_Q_Base<TensorProductPolynomials<dim>, dim, spacedim> ( TensorProductPolynomials<dim>(Polynomials::generate_complete_Lagrange_basis(points.get_points())), FiniteElementData<dim>(this->get_dpo_vector(points.size()-1), 1, points.size()-1, FiniteElementData<dim>::H1), std::vector<bool> (1, false)) { const unsigned int degree = points.size()-1; Assert (degree > 0, ExcMessage ("This element can only be used for polynomial degrees " "at least zero")); this->initialize(points.get_points()); } template <int dim, int spacedim> std::string FE_Q<dim,spacedim>::get_name () const { // note that the FETools::get_fe_from_name function depends on the // particular format of the string this function returns, so they have to be // kept in synch std::ostringstream namebuf; bool equidistant = true; std::vector<double> points(this->degree+1); // Decode the support points in one coordinate direction. std::vector<unsigned int> lexicographic = this->poly_space.get_numbering_inverse(); for (unsigned int j=0; j<=this->degree; j++) points[j] = this->unit_support_points[lexicographic[j]][0]; // Check whether the support points are equidistant. for (unsigned int j=0; j<=this->degree; j++) if (std::fabs(points[j] - (double)j/this->degree) > 1e-15) { equidistant = false; break; } if (equidistant == true) namebuf << "FE_Q<" << Utilities::dim_string(dim,spacedim) << ">(" << this->degree << ")"; else { // Check whether the support points come from QGaussLobatto. const QGaussLobatto<1> points_gl(this->degree+1); bool gauss_lobatto = true; for (unsigned int j=0; j<=this->degree; j++) if (points[j] != points_gl.point(j)(0)) { gauss_lobatto = false; break; } if (gauss_lobatto == true) namebuf << "FE_Q<" << Utilities::dim_string(dim,spacedim) << ">(QGaussLobatto(" << this->degree+1 << "))"; else namebuf << "FE_Q<" << Utilities::dim_string(dim,spacedim) << ">(QUnknownNodes(" << this->degree << "))"; } return namebuf.str(); } template <int dim, int spacedim> FiniteElement<dim,spacedim> * FE_Q<dim,spacedim>::clone() const { return new FE_Q<dim,spacedim>(*this); } // explicit instantiations #include "fe_q.inst" DEAL_II_NAMESPACE_CLOSE
// --------------------------------------------------------------------- // // Copyright (C) 2000 - 2014 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/base/quadrature_lib.h> #include <deal.II/fe/fe_q.h> #include <vector> #include <sstream> DEAL_II_NAMESPACE_OPEN template <int dim, int spacedim> FE_Q<dim,spacedim>::FE_Q (const unsigned int degree) : FE_Q_Base<TensorProductPolynomials<dim>, dim, spacedim> ( TensorProductPolynomials<dim>(Polynomials::LagrangeEquidistant::generate_complete_basis(degree)), FiniteElementData<dim>(this->get_dpo_vector(degree), 1, degree, FiniteElementData<dim>::H1), std::vector<bool> (1, false)) { Assert (degree > 0, ExcMessage ("This element can only be used for polynomial degrees " "greater than zero. If you want an element of polynomial " "degree zero, then it cannot be continuous and you " "will want to use FE_DGQ<dim>(0).")); std::vector<Point<1> > support_points_1d(degree+1); for (unsigned int i=0; i<=degree; ++i) support_points_1d[i][0] = static_cast<double>(i)/degree; this->initialize(support_points_1d); } template <int dim, int spacedim> FE_Q<dim,spacedim>::FE_Q (const Quadrature<1> &points) : FE_Q_Base<TensorProductPolynomials<dim>, dim, spacedim> ( TensorProductPolynomials<dim>(Polynomials::generate_complete_Lagrange_basis(points.get_points())), FiniteElementData<dim>(this->get_dpo_vector(points.size()-1), 1, points.size()-1, FiniteElementData<dim>::H1), std::vector<bool> (1, false)) { const unsigned int degree = points.size()-1; Assert (degree > 0, ExcMessage ("This element can only be used for polynomial degrees " "at least zero")); this->initialize(points.get_points()); } template <int dim, int spacedim> std::string FE_Q<dim,spacedim>::get_name () const { // note that the FETools::get_fe_from_name function depends on the // particular format of the string this function returns, so they have to be // kept in synch std::ostringstream namebuf; bool equidistant = true; std::vector<double> points(this->degree+1); // Decode the support points in one coordinate direction. std::vector<unsigned int> lexicographic = this->poly_space.get_numbering_inverse(); for (unsigned int j=0; j<=this->degree; j++) points[j] = this->unit_support_points[lexicographic[j]][0]; // Check whether the support points are equidistant. for (unsigned int j=0; j<=this->degree; j++) if (std::fabs(points[j] - (double)j/this->degree) > 1e-15) { equidistant = false; break; } if (equidistant == true) namebuf << "FE_Q<" << Utilities::dim_string(dim,spacedim) << ">(" << this->degree << ")"; else { // Check whether the support points come from QGaussLobatto. const QGaussLobatto<1> points_gl(this->degree+1); bool gauss_lobatto = true; for (unsigned int j=0; j<=this->degree; j++) if (points[j] != points_gl.point(j)(0)) { gauss_lobatto = false; break; } if (gauss_lobatto == true) namebuf << "FE_Q<" << Utilities::dim_string(dim,spacedim) << ">(QGaussLobatto(" << this->degree+1 << "))"; else namebuf << "FE_Q<" << Utilities::dim_string(dim,spacedim) << ">(QUnknownNodes(" << this->degree << "))"; } return namebuf.str(); } template <int dim, int spacedim> FiniteElement<dim,spacedim> * FE_Q<dim,spacedim>::clone() const { return new FE_Q<dim,spacedim>(*this); } // explicit instantiations #include "fe_q.inst" DEAL_II_NAMESPACE_CLOSE
Improve an error message and provide guidance.
Improve an error message and provide guidance. In response to a recent question on the mailing list.
C++
lgpl-2.1
spco/dealii,kalj/dealii,gpitton/dealii,ibkim11/dealii,mtezzele/dealii,johntfoster/dealii,maieneuro/dealii,YongYang86/dealii,nicolacavallini/dealii,pesser/dealii,angelrca/dealii,rrgrove6/dealii,msteigemann/dealii,JaeryunYim/dealii,pesser/dealii,nicolacavallini/dealii,jperryhouts/dealii,pesser/dealii,kalj/dealii,rrgrove6/dealii,EGP-CIG-REU/dealii,lpolster/dealii,YongYang86/dealii,ibkim11/dealii,lue/dealii,andreamola/dealii,lpolster/dealii,ESeNonFossiIo/dealii,danshapero/dealii,sairajat/dealii,mtezzele/dealii,EGP-CIG-REU/dealii,nicolacavallini/dealii,adamkosik/dealii,EGP-CIG-REU/dealii,maieneuro/dealii,mac-a/dealii,andreamola/dealii,johntfoster/dealii,msteigemann/dealii,shakirbsm/dealii,nicolacavallini/dealii,nicolacavallini/dealii,YongYang86/dealii,ESeNonFossiIo/dealii,lpolster/dealii,shakirbsm/dealii,sairajat/dealii,pesser/dealii,JaeryunYim/dealii,natashasharma/dealii,danshapero/dealii,mtezzele/dealii,gpitton/dealii,mac-a/dealii,natashasharma/dealii,Arezou-gh/dealii,ibkim11/dealii,johntfoster/dealii,natashasharma/dealii,EGP-CIG-REU/dealii,shakirbsm/dealii,msteigemann/dealii,shakirbsm/dealii,angelrca/dealii,naliboff/dealii,jperryhouts/dealii,ibkim11/dealii,gpitton/dealii,sriharisundar/dealii,EGP-CIG-REU/dealii,danshapero/dealii,spco/dealii,nicolacavallini/dealii,maieneuro/dealii,ESeNonFossiIo/dealii,ibkim11/dealii,mac-a/dealii,gpitton/dealii,lue/dealii,adamkosik/dealii,spco/dealii,ESeNonFossiIo/dealii,lpolster/dealii,mac-a/dealii,natashasharma/dealii,JaeryunYim/dealii,jperryhouts/dealii,johntfoster/dealii,rrgrove6/dealii,adamkosik/dealii,Arezou-gh/dealii,Arezou-gh/dealii,lue/dealii,spco/dealii,angelrca/dealii,pesser/dealii,lpolster/dealii,adamkosik/dealii,Arezou-gh/dealii,maieneuro/dealii,sriharisundar/dealii,shakirbsm/dealii,natashasharma/dealii,andreamola/dealii,Arezou-gh/dealii,sairajat/dealii,angelrca/dealii,YongYang86/dealii,jperryhouts/dealii,sriharisundar/dealii,naliboff/dealii,shakirbsm/dealii,johntfoster/dealii,mac-a/dealii,angelrca/dealii,naliboff/dealii,pesser/dealii,JaeryunYim/dealii,gpitton/dealii,msteigemann/dealii,naliboff/dealii,adamkosik/dealii,maieneuro/dealii,kalj/dealii,ESeNonFossiIo/dealii,danshapero/dealii,YongYang86/dealii,rrgrove6/dealii,kalj/dealii,msteigemann/dealii,mtezzele/dealii,angelrca/dealii,sairajat/dealii,naliboff/dealii,sriharisundar/dealii,nicolacavallini/dealii,Arezou-gh/dealii,jperryhouts/dealii,danshapero/dealii,johntfoster/dealii,lue/dealii,sriharisundar/dealii,jperryhouts/dealii,msteigemann/dealii,sairajat/dealii,ESeNonFossiIo/dealii,kalj/dealii,lpolster/dealii,maieneuro/dealii,natashasharma/dealii,ibkim11/dealii,EGP-CIG-REU/dealii,Arezou-gh/dealii,spco/dealii,rrgrove6/dealii,sriharisundar/dealii,sairajat/dealii,johntfoster/dealii,kalj/dealii,maieneuro/dealii,mtezzele/dealii,sriharisundar/dealii,danshapero/dealii,andreamola/dealii,YongYang86/dealii,rrgrove6/dealii,gpitton/dealii,lpolster/dealii,lue/dealii,mac-a/dealii,natashasharma/dealii,YongYang86/dealii,danshapero/dealii,shakirbsm/dealii,EGP-CIG-REU/dealii,JaeryunYim/dealii,msteigemann/dealii,sairajat/dealii,lue/dealii,andreamola/dealii,andreamola/dealii,pesser/dealii,kalj/dealii,angelrca/dealii,rrgrove6/dealii,gpitton/dealii,mtezzele/dealii,JaeryunYim/dealii,ESeNonFossiIo/dealii,mtezzele/dealii,lue/dealii,mac-a/dealii,naliboff/dealii,JaeryunYim/dealii,jperryhouts/dealii,naliboff/dealii,andreamola/dealii,ibkim11/dealii,adamkosik/dealii,spco/dealii,spco/dealii,adamkosik/dealii
d860a65195551fbecf71543ede0cbe2b6bea9a9b
Socket.cpp
Socket.cpp
/************************************************************** * Copyright (c) 2011, Dynamic Network Services, Inc. * Jake Montgomery ([email protected]) & Tom Daly ([email protected]) * Distributed under the FreeBSD License - see LICENSE ***************************************************************/ #include "common.h" #include "Socket.h" #include "utils.h" #include <errno.h> #include <fcntl.h> #include <sys/socket.h> #include <string.h> #include <cstdarg> using namespace std; namespace openbfdd { void Socket::clear() { m_socket = -1; m_address.clear(); m_owned = false; m_error = 0; } Socket::Socket() : m_logName(), m_quiet(false) { clear(); } Socket::Socket(int sock, Addr::Type family, bool owned /*false*/) : m_logName(), m_quiet(false) { clear(); m_socket = sock; m_address.SetAny(family); m_owned = owned; } Socket::Socket(const Socket &src) : m_logName(), m_quiet(false) { clear(); copy(src); } /** * Copies the socket. This will NOT own the socket. * Does not copy quiet or log name settings. * * @param src */ void Socket::copy(const Socket &src) { Close(); m_socket = src.m_socket; m_address = src.m_address; m_error = src.m_error; } Socket::~Socket() { Close(); } Socket &Socket::operator=(const Socket& src) { Close(); copy(src); return *this; } bool Socket::Open(Addr::Type family, int type, int protocol) { Close(); m_socket = ::socket(Addr::TypeToFamily(family), type, protocol); if (empty()) return logAndSetError(errno, "Failed create socket. family %d, type %d proto %d", family, type, protocol); m_address.SetAny(family); m_owned = true; return true; } bool Socket::OpenUDP( Addr::Type family) { return Open(family, SOCK_DGRAM, IPPROTO_UDP); } bool Socket::OpenTCP( Addr::Type family) { return Open(family, SOCK_STREAM, IPPROTO_TCP); } void Socket::Attach(int sock, Addr::Type family, bool owned /*false*/) { Close(); m_socket = sock; m_address.SetAny(family); m_owned = owned; } void Socket::Attach(int sock, const sockaddr *addr, socklen_t addrlen, bool owned /*false*/) { Close(); m_socket = sock; m_address = SockAddr(addr, addrlen); m_owned = owned; } void Socket::Transfer(Socket &src) { Close(); if(src.m_owned) { copy(src.Detach()); TakeOwnership(); } else copy(src); } void Socket::SetLogName(const char *str) { if (!str || !*str) m_logName.clear(); else m_logName = str; } bool Socket::SetQuiet(bool quiet) { bool old = m_quiet; m_quiet = quiet; return old; } void Socket::Close() { if (!empty() && m_owned) ::close(m_socket); clear(); // must do full clear, because internally we rely on that behavior. } void Socket::AlwaysClose() { if (!empty()) ::close(m_socket); clear(); // must do full clear, because internally we rely on that behavior. } bool Socket::SetBlocking(bool block) { if (!ensureSocket()) return false; int flags; flags = ::fcntl(m_socket, F_GETFL); if (flags == -1) return logAndSetError(errno, "Failed to get socket flags to set to %sblocking", block ? "":"non-"); if (block) flags &= ~(int)O_NONBLOCK; else flags |= O_NONBLOCK; if (-1 == ::fcntl(m_socket, F_SETFL, flags)) return logAndSetError(errno, "Failed to set socket to %sblocking", block ? "":"non-"); return true; } /** * Calls setsockopt. * * will set m_error * * @param level * @param optname * @param name * @param value * * @return bool */ bool Socket::setIntSockOpt(int level, int optname, const char *name, int value) { if (!ensureSocket()) return false; int on = value; if (0 > ::setsockopt(m_socket, level, optname, &on, sizeof(on))) return logAndSetError(errno, "Failed to set socket %s to %d", name, value); return true; } /** * Calls getsockopt. * * @param level * @param optname * @param name * @param value [out] - set on success * * @return bool */ bool Socket::getIntSockOpt(int level, int optname, const char *name, int &out_value) { if (!ensureSocket()) return false; socklen_t out_len = sizeof(int); out_value = 0; if (0 > ::getsockopt(m_socket, level, optname, &out_value, &out_len)) return logAndSetError(errno, "Failed to get socket %s", name); return true; } bool Socket::SetReusePort(bool reuse) { return setIntSockOpt(SOL_SOCKET, SO_REUSEADDR, "SO_REUSEADDR", reuse ? 1:0); } bool Socket::SetSendBufferSize(int bufsize) { return setIntSockOpt(SOL_SOCKET, SO_SNDBUF, "SO_SNDBUF", bufsize); } bool Socket::GetSendBufferSize(int &out_bufsize) { return getIntSockOpt(SOL_SOCKET, SO_SNDBUF, "SO_SNDBUF", out_bufsize); } bool Socket::SetUseTimestamp(bool timestamp) { return setIntSockOpt(SOL_SOCKET, SO_TIMESTAMP, "SO_TIMESTAMP", timestamp ? 1:0); } bool Socket::SetTTLOrHops(int hops) { if (!ensureSocket()) return false; if (GetAddress().IsIPv4()) { // Is there a 255 limit? return setIntSockOpt(IPPROTO_IP, IP_TTL, "IP_TTL", hops); } else return setIntSockOpt(IPPROTO_IPV6, IPV6_UNICAST_HOPS, "IPV6_UNICAST_HOPS", hops); } bool Socket::SetRecieveTTLOrHops(bool receive) { int val = receive ? 1:0; if (!ensureSocket()) return false; else if (GetAddress().IsIPv4()) { // Is there a 255 limit? return setIntSockOpt(IPPROTO_IP, IP_RECVTTL, "IP_RECVTTL", val); } else return setIntSockOpt(IPPROTO_IPV6, IPV6_RECVHOPLIMIT, "IPV6_RECVHOPLIMIT", val); } bool Socket::SetReceiveDestinationAddress(bool receive) { int val = receive ? 1:0; if (!ensureSocket()) return false; else if (GetAddress().IsIPv4()) { #ifdef IP_RECVDSTADDR return setIntSockOpt(IPPROTO_IP, IP_RECVDSTADDR, "IP_RECVDSTADDR", val); #elif defined IP_PKTINFO return setIntSockOpt(IPPROTO_IP, IP_PKTINFO, "IP_PKTINFO", val); #endif m_error = ENOTSUP; return logError("Platform does not support IP_RECVDSTADDR or IP_PKTINFO"); } else return setIntSockOpt(IPPROTO_IPV6, IPV6_RECVPKTINFO, "IPV6_RECVPKTINFO", val); } bool Socket::SetIPv6Only(bool ipv6Only) { if (!ensureSocket()) return false; if (GetAddress().IsIPv6()) return setIntSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, "IPV6_V6ONLY", ipv6Only ? 1:0); else { m_error = ENOTSUP; return logError("IPV6_V6ONLY not supported on IPv4 socket"); } } bool Socket::Bind(const SockAddr &address) { if (!ensureSocket()) return false; m_address.clear(); if (::bind(m_socket, &address.GetSockAddr(), address.GetSize()) < 0) return logAndSetError(errno, "Failed to bind socket to %s", address.ToString()); m_address = address; return true; } bool Socket::Connect(const SockAddr &address) { if (!ensureSocket()) return false; m_address.clear(); if (::connect(m_socket, &address.GetSockAddr(), address.GetSize()) < 0) return logAndSetError(errno, "Failed to connect socket to %s", address.ToString()); m_address = address; return true; } bool Socket::Listen(int backlog) { if (!ensureSocket()) return false; if (::listen(m_socket, backlog) < 0) return logAndSetError(errno, "Failed to listen on socket"); return true; } bool Socket::SendTo(const void *buffer, size_t bufferLen, const SockAddr &toAddress, int flags /*0*/) { if (!ensureSocket()) return false; if (::sendto(m_socket, buffer, bufferLen, flags, &toAddress.GetSockAddr(), toAddress.GetSize()) < 0) return logAndSetError(errno, "Error sending packet using sendto to %s", toAddress.ToString()); return true; } bool Socket::Send(const void *buffer, size_t bufferLen, int flags /*0*/) { if (!ensureSocket()) return false; if (::send(m_socket, buffer, bufferLen, flags) < 0) return logAndSetError(errno, "Error sending packet using send"); return true; } bool Socket::Accept(Socket &outResult) { if (!ensureSocket()) return false; outResult.Close(); sockaddr_storage faddr; socklen_t fromlen = sizeof(faddr); int sock = ::accept(m_socket, (sockaddr*)&faddr, &fromlen); if (sock == -1) return logAndSetError(errno, "Failed to accept on socket"); // It is always success, when if we can not read from addr outResult.m_socket = sock; outResult.m_address = SockAddr((sockaddr*)&faddr, fromlen); outResult.m_owned= true; if (!outResult.m_address.IsValid()) gLog.LogError("Unexpected invalid address from accept. Size %zu", size_t(fromlen)); return true; } size_t Socket::GetMaxControlSizeRecieveTTLOrHops() { // IP_TTL and IPV6_HOPLIMIT use int, and IP_RECVTTL may use byte. return (CMSG_SPACE(int)); } size_t Socket::GetMaxControlSizeReceiveDestinationAddress() { // We could assume that in6_pktinfo is going to be the largest, but the // following actually models what we do. size_t size = 0; size = max(size, CMSG_SPACE(sizeof(in6_pktinfo))); #ifdef IP_RECVDSTADDR size = max(size, CMSG_SPACE(sizeof(in_addr))); #endif #ifdef IP_PKTINFO size = max(size, CMSG_SPACE(sizeof(in6_pktinfo))); #endif return size; } /** * Same as !empty(), but sets m_error and logs a message on failure. * * @return bool */ bool Socket::ensureSocket() { if (!empty()) return true; m_error = EBADF; return logError("Socket is invalid"); } /** * Sets m_error to error, and logs the message, if settings allow. * Will prepend the socket name, if any. Will append the error string. * * @param error * @param format * * @return - false always! */ bool Socket::logAndSetError(int error, const char* format, ...) { m_error = error; if (m_quiet) return false; va_list args; va_start(args, format); const char *str = FormatMediumStrVa(format, args); va_end(args); if (!m_logName.empty()) gLog.LogError("%s : %s : (%d) %s", m_logName.c_str(), str, error, strerror(error)); else gLog.LogError("%s : (%d) %s", str, error, strerror(error)); return false; } /** * Logs the message, if settings allow. Will prepend the socket name, if any. * * @param error * @param format * * @return - false always! */ bool Socket::logError(const char* format, ...) { if (m_quiet) return false; va_list args; va_start(args, format); if (!m_logName.empty()) { const char *str = FormatMediumStrVa(format, args); gLog.LogError("%s : %s", m_logName.c_str(), str); } else { gLog.MessageVa(Log::Error, format, args); } va_end(args); return false; } }
/************************************************************** * Copyright (c) 2011, Dynamic Network Services, Inc. * Jake Montgomery ([email protected]) & Tom Daly ([email protected]) * Distributed under the FreeBSD License - see LICENSE ***************************************************************/ #include "common.h" #include "Socket.h" #include "utils.h" #include <errno.h> #include <fcntl.h> #include <sys/socket.h> #include <string.h> #include <cstdarg> #include <unistd.h> using namespace std; namespace openbfdd { void Socket::clear() { m_socket = -1; m_address.clear(); m_owned = false; m_error = 0; } Socket::Socket() : m_logName(), m_quiet(false) { clear(); } Socket::Socket(int sock, Addr::Type family, bool owned /*false*/) : m_logName(), m_quiet(false) { clear(); m_socket = sock; m_address.SetAny(family); m_owned = owned; } Socket::Socket(const Socket &src) : m_logName(), m_quiet(false) { clear(); copy(src); } /** * Copies the socket. This will NOT own the socket. * Does not copy quiet or log name settings. * * @param src */ void Socket::copy(const Socket &src) { Close(); m_socket = src.m_socket; m_address = src.m_address; m_error = src.m_error; } Socket::~Socket() { Close(); } Socket &Socket::operator=(const Socket& src) { Close(); copy(src); return *this; } bool Socket::Open(Addr::Type family, int type, int protocol) { Close(); m_socket = ::socket(Addr::TypeToFamily(family), type, protocol); if (empty()) return logAndSetError(errno, "Failed create socket. family %d, type %d proto %d", family, type, protocol); m_address.SetAny(family); m_owned = true; return true; } bool Socket::OpenUDP( Addr::Type family) { return Open(family, SOCK_DGRAM, IPPROTO_UDP); } bool Socket::OpenTCP( Addr::Type family) { return Open(family, SOCK_STREAM, IPPROTO_TCP); } void Socket::Attach(int sock, Addr::Type family, bool owned /*false*/) { Close(); m_socket = sock; m_address.SetAny(family); m_owned = owned; } void Socket::Attach(int sock, const sockaddr *addr, socklen_t addrlen, bool owned /*false*/) { Close(); m_socket = sock; m_address = SockAddr(addr, addrlen); m_owned = owned; } void Socket::Transfer(Socket &src) { Close(); if(src.m_owned) { copy(src.Detach()); TakeOwnership(); } else copy(src); } void Socket::SetLogName(const char *str) { if (!str || !*str) m_logName.clear(); else m_logName = str; } bool Socket::SetQuiet(bool quiet) { bool old = m_quiet; m_quiet = quiet; return old; } void Socket::Close() { if (!empty() && m_owned) ::close(m_socket); clear(); // must do full clear, because internally we rely on that behavior. } void Socket::AlwaysClose() { if (!empty()) ::close(m_socket); clear(); // must do full clear, because internally we rely on that behavior. } bool Socket::SetBlocking(bool block) { if (!ensureSocket()) return false; int flags; flags = ::fcntl(m_socket, F_GETFL); if (flags == -1) return logAndSetError(errno, "Failed to get socket flags to set to %sblocking", block ? "":"non-"); if (block) flags &= ~(int)O_NONBLOCK; else flags |= O_NONBLOCK; if (-1 == ::fcntl(m_socket, F_SETFL, flags)) return logAndSetError(errno, "Failed to set socket to %sblocking", block ? "":"non-"); return true; } /** * Calls setsockopt. * * will set m_error * * @param level * @param optname * @param name * @param value * * @return bool */ bool Socket::setIntSockOpt(int level, int optname, const char *name, int value) { if (!ensureSocket()) return false; int on = value; if (0 > ::setsockopt(m_socket, level, optname, &on, sizeof(on))) return logAndSetError(errno, "Failed to set socket %s to %d", name, value); return true; } /** * Calls getsockopt. * * @param level * @param optname * @param name * @param value [out] - set on success * * @return bool */ bool Socket::getIntSockOpt(int level, int optname, const char *name, int &out_value) { if (!ensureSocket()) return false; socklen_t out_len = sizeof(int); out_value = 0; if (0 > ::getsockopt(m_socket, level, optname, &out_value, &out_len)) return logAndSetError(errno, "Failed to get socket %s", name); return true; } bool Socket::SetReusePort(bool reuse) { return setIntSockOpt(SOL_SOCKET, SO_REUSEADDR, "SO_REUSEADDR", reuse ? 1:0); } bool Socket::SetSendBufferSize(int bufsize) { return setIntSockOpt(SOL_SOCKET, SO_SNDBUF, "SO_SNDBUF", bufsize); } bool Socket::GetSendBufferSize(int &out_bufsize) { return getIntSockOpt(SOL_SOCKET, SO_SNDBUF, "SO_SNDBUF", out_bufsize); } bool Socket::SetUseTimestamp(bool timestamp) { return setIntSockOpt(SOL_SOCKET, SO_TIMESTAMP, "SO_TIMESTAMP", timestamp ? 1:0); } bool Socket::SetTTLOrHops(int hops) { if (!ensureSocket()) return false; if (GetAddress().IsIPv4()) { // Is there a 255 limit? return setIntSockOpt(IPPROTO_IP, IP_TTL, "IP_TTL", hops); } else return setIntSockOpt(IPPROTO_IPV6, IPV6_UNICAST_HOPS, "IPV6_UNICAST_HOPS", hops); } bool Socket::SetRecieveTTLOrHops(bool receive) { int val = receive ? 1:0; if (!ensureSocket()) return false; else if (GetAddress().IsIPv4()) { // Is there a 255 limit? return setIntSockOpt(IPPROTO_IP, IP_RECVTTL, "IP_RECVTTL", val); } else return setIntSockOpt(IPPROTO_IPV6, IPV6_RECVHOPLIMIT, "IPV6_RECVHOPLIMIT", val); } bool Socket::SetReceiveDestinationAddress(bool receive) { int val = receive ? 1:0; if (!ensureSocket()) return false; else if (GetAddress().IsIPv4()) { #ifdef IP_RECVDSTADDR return setIntSockOpt(IPPROTO_IP, IP_RECVDSTADDR, "IP_RECVDSTADDR", val); #elif defined IP_PKTINFO return setIntSockOpt(IPPROTO_IP, IP_PKTINFO, "IP_PKTINFO", val); #endif m_error = ENOTSUP; return logError("Platform does not support IP_RECVDSTADDR or IP_PKTINFO"); } else return setIntSockOpt(IPPROTO_IPV6, IPV6_RECVPKTINFO, "IPV6_RECVPKTINFO", val); } bool Socket::SetIPv6Only(bool ipv6Only) { if (!ensureSocket()) return false; if (GetAddress().IsIPv6()) return setIntSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, "IPV6_V6ONLY", ipv6Only ? 1:0); else { m_error = ENOTSUP; return logError("IPV6_V6ONLY not supported on IPv4 socket"); } } bool Socket::Bind(const SockAddr &address) { if (!ensureSocket()) return false; m_address.clear(); if (::bind(m_socket, &address.GetSockAddr(), address.GetSize()) < 0) return logAndSetError(errno, "Failed to bind socket to %s", address.ToString()); m_address = address; return true; } bool Socket::Connect(const SockAddr &address) { if (!ensureSocket()) return false; m_address.clear(); if (::connect(m_socket, &address.GetSockAddr(), address.GetSize()) < 0) return logAndSetError(errno, "Failed to connect socket to %s", address.ToString()); m_address = address; return true; } bool Socket::Listen(int backlog) { if (!ensureSocket()) return false; if (::listen(m_socket, backlog) < 0) return logAndSetError(errno, "Failed to listen on socket"); return true; } bool Socket::SendTo(const void *buffer, size_t bufferLen, const SockAddr &toAddress, int flags /*0*/) { if (!ensureSocket()) return false; if (::sendto(m_socket, buffer, bufferLen, flags, &toAddress.GetSockAddr(), toAddress.GetSize()) < 0) return logAndSetError(errno, "Error sending packet using sendto to %s", toAddress.ToString()); return true; } bool Socket::Send(const void *buffer, size_t bufferLen, int flags /*0*/) { if (!ensureSocket()) return false; if (::send(m_socket, buffer, bufferLen, flags) < 0) return logAndSetError(errno, "Error sending packet using send"); return true; } bool Socket::Accept(Socket &outResult) { if (!ensureSocket()) return false; outResult.Close(); sockaddr_storage faddr; socklen_t fromlen = sizeof(faddr); int sock = ::accept(m_socket, (sockaddr*)&faddr, &fromlen); if (sock == -1) return logAndSetError(errno, "Failed to accept on socket"); // It is always success, when if we can not read from addr outResult.m_socket = sock; outResult.m_address = SockAddr((sockaddr*)&faddr, fromlen); outResult.m_owned= true; if (!outResult.m_address.IsValid()) gLog.LogError("Unexpected invalid address from accept. Size %zu", size_t(fromlen)); return true; } size_t Socket::GetMaxControlSizeRecieveTTLOrHops() { // IP_TTL and IPV6_HOPLIMIT use int, and IP_RECVTTL may use byte. return (CMSG_SPACE(int)); } size_t Socket::GetMaxControlSizeReceiveDestinationAddress() { // We could assume that in6_pktinfo is going to be the largest, but the // following actually models what we do. size_t size = 0; size = max(size, CMSG_SPACE(sizeof(in6_pktinfo))); #ifdef IP_RECVDSTADDR size = max(size, CMSG_SPACE(sizeof(in_addr))); #endif #ifdef IP_PKTINFO size = max(size, CMSG_SPACE(sizeof(in6_pktinfo))); #endif return size; } /** * Same as !empty(), but sets m_error and logs a message on failure. * * @return bool */ bool Socket::ensureSocket() { if (!empty()) return true; m_error = EBADF; return logError("Socket is invalid"); } /** * Sets m_error to error, and logs the message, if settings allow. * Will prepend the socket name, if any. Will append the error string. * * @param error * @param format * * @return - false always! */ bool Socket::logAndSetError(int error, const char* format, ...) { m_error = error; if (m_quiet) return false; va_list args; va_start(args, format); const char *str = FormatMediumStrVa(format, args); va_end(args); if (!m_logName.empty()) gLog.LogError("%s : %s : (%d) %s", m_logName.c_str(), str, error, strerror(error)); else gLog.LogError("%s : (%d) %s", str, error, strerror(error)); return false; } /** * Logs the message, if settings allow. Will prepend the socket name, if any. * * @param error * @param format * * @return - false always! */ bool Socket::logError(const char* format, ...) { if (m_quiet) return false; va_list args; va_start(args, format); if (!m_logName.empty()) { const char *str = FormatMediumStrVa(format, args); gLog.LogError("%s : %s", m_logName.c_str(), str); } else { gLog.MessageVa(Log::Error, format, args); } va_end(args); return false; } }
fix for building with gcc/g++ 4.7.x
fix for building with gcc/g++ 4.7.x http://gcc.gnu.org/gcc-4.7/porting_to.html Header dependency changes: Socket.cpp: In member function ‘void openbfdd::Socket::Close()’: Socket.cpp:151:7: error: ‘::close’ has not been declared Socket.cpp: In member function ‘void openbfdd::Socket::AlwaysClose()’: Socket.cpp:158:7: error: ‘::close’ has not been declared make: *** [Socket.o] Error 1
C++
bsd-3-clause
dyninc/OpenBFDD,dyninc/OpenBFDD,dyninc/OpenBFDD
0d5dc6a6e431ade03e14696732445fb7a77fcf64
test/clang-tidy/clang-tidy-__clang_analyzer__macro.cpp
test/clang-tidy/clang-tidy-__clang_analyzer__macro.cpp
// RUN: clang-tidy %s -checks=-*,modernize-use-nullptr -- | count 0 #if !defined(__clang_analyzer__) #error __clang_analyzer__ is not defined #endif // RUN: clang-tidy %s -checks=-*,modernize-use-nullptr -- | count 0 #if !defined(__clang_analyzer__) #error __clang_analyzer__ is not defined #endif
// RUN: clang-tidy %s -checks=-*,modernize-use-nullptr -- | count 0 #if !defined(__clang_analyzer__) #error __clang_analyzer__ is not defined #endif
Simplify test clang-tidy-__clang_analyzer__macro.cpp
Simplify test clang-tidy-__clang_analyzer__macro.cpp git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@331475 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
751c045aa9046ad26313c4091538e2d5d999d7f2
System.cpp
System.cpp
#include <irrlicht.h> #include <btBulletDynamicsCommon.h> #include <cassert> #include <Windows.h> #include "System.h" using namespace irr; using namespace core; System::System() : timer(nullptr), isRunning(true) { } System::~System() { } bool System::init() { InitializeCriticalSection(&cs); return true; } void System::release() { DeleteCriticalSection(&cs); } bool System::initGraphicsContents() { device = createDevice(video::EDT_OPENGL, dimension2d<u32>(800, 600), 32, false, false, false, nullptr); smgr = device->getSceneManager(); driver = device->getVideoDriver(); groundSceneNode = smgr->addCubeSceneNode(1.0f); groundSceneNode->setPosition(vector3df(0, -1, 0)); groundSceneNode->setScale(vector3df(100, 0, 100)); groundSceneNode->setMaterialFlag(irr::video::EMF_LIGHTING, false); groundSceneNode->setMaterialTexture(0, driver->getTexture("blue.png")); camera = smgr->addCameraSceneNodeFPS(); camera->setPosition(vector3df(0, 20, -50)); camera->setTarget(vector3df(0, 0, 0)); return true; } void System::releaseGraphicsContents() { device->drop(); } bool System::initPhysicsContents() { broadphase = new btDbvtBroadphase(); collisionConfiguration = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfiguration); solver = new btSequentialImpulseConstraintSolver(); dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld->setGravity(btVector3(0, -10, 0)); groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1); fallShape = new btSphereShape(1); btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0))); btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0)); groundRigidBody = new btRigidBody(groundRigidBodyCI); dynamicsWorld->addRigidBody(groundRigidBody); return true; } void System::releasePhysicsContents() { for (auto body : rigidBodies) { Sphere* sphere = body.get(); btRigidBody* rigidBody = sphere->rigidBody; dynamicsWorld->removeRigidBody(rigidBody); delete rigidBody->getMotionState(); delete rigidBody->getCollisionShape(); delete rigidBody; delete sphere; } rigidBodies.clear(); delete groundShape; delete dynamicsWorld; delete solver; delete collisionConfiguration; delete dispatcher; delete broadphase; } DWORD WINAPI runGraphics( LPVOID parameter ) { System *sys = (System*)parameter; sys->initGraphicsContents(); sys->timer = sys->device->getTimer(); while (sys->device->run()){ sys->draw(); } sys->releaseGraphicsContents(); sys->isRunning = false; return EXIT_SUCCESS; } void System::run() { CreateThread( NULL, 0, runGraphics, this, 0, nullptr); while (timer == nullptr); u32 lastTime = timer->getRealTime(); globalTimer = 0.0; FPSTimer = 0.0; FPS = 0; initPhysicsContents(); while (isRunning) { u32 currentTime = timer->getRealTime(); double dt = (currentTime - lastTime) / 1000.0; lastTime = currentTime; update(dt); } releasePhysicsContents(); } void System::update(double dt) { dynamicsWorld->stepSimulation(dt, 10); for (unsigned i = 0; i < rigidBodies.size(); ++i) { auto body = rigidBodies[i]; btTransform trans; body->getMotionState()->getWorldTransform(trans); const btVector3& origin = trans.getOrigin(); messageQueue.push(new Message(EMT_UPDATE, new UpdatePacket(origin.getX(), origin.getY(), origin.getZ(), i))); } if (globalTimer > 0.1) { addRigidBody((rand() % SHRT_MAX) / (double)SHRT_MAX, 50, (rand() % SHRT_MAX) / (double)SHRT_MAX, 1.0); globalTimer = 0.0; } if (FPSTimer > 1.0) { printf("%d\n", FPS); FPS = 0; FPSTimer = 0.0; } globalTimer += dt; FPSTimer += dt; ++FPS; } void System::draw() { while (messageQueue.empty() == false) { auto msg = messageQueue.front(); messageQueue.pop(); if (msg->type == EMT_INSERT) { auto packet = reinterpret_cast<InsertPacket*>(msg->user_data); assert(packet); addSceneNode(packet->x, packet->y, packet->z, packet->radius, packet->idx); } else if (msg->type == EMT_ERASE) { auto packet = reinterpret_cast<ErasePacket*>(msg->user_data); eraseSceneNode(packet->idx); } else if (msg->type == EMT_UPDATE) { auto packet = reinterpret_cast<UpdatePacket*>(msg->user_data); updateSceneNode(packet->x, packet->y, packet->z, packet->idx); } else { printf("Invalid message\n"); continue; } delete msg->user_data; msg->user_data = nullptr; msg->drop(); } driver->beginScene(true, true, video::SColor(255, 255, 0, 255)); smgr->drawAll(); driver->endScene(); } void System::addRigidBody(double x, double y, double z, double radius) { btCollisionShape* shape = new btSphereShape(radius); btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(x, y, z))); btScalar mass = 1; btVector3 Inertia(0, 0, 0); shape->calculateLocalInertia(mass, Inertia); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, motionState, shape, Inertia); btRigidBody* rigidBody = new btRigidBody(rigidBodyCI); dynamicsWorld->addRigidBody(rigidBody); int idx = -1; if (unused.empty()) { idx = rigidBodies.size(); } else { idx = unused.front(); unused.pop(); } assert(idx != -1); rigidBodies.push_back(rigidBody); messageQueue.push(new Message(EMT_INSERT, new InsertPacket(x, y, z, radius, idx))); } void System::addSceneNode(double x, double y, double z, double radius, unsigned idx) { scene::ISceneNode* sceneNode = smgr->addSphereSceneNode(radius); sceneNode->setPosition(vector3df(x, y, z)); sceneNode->setMaterialFlag(irr::video::EMF_LIGHTING, false); sceneNode->setMaterialTexture(0, driver->getTexture("red.png")); sceneNodes[idx] = sceneNode; } void System::eraseSceneNode(unsigned idx) { auto it = sceneNodes.find(idx); assert(it != sceneNodes.end()); sceneNodes.erase(it); } void System::updateSceneNode(double x, double y, double z, unsigned idx) { sceneNodes[idx]->setPosition(vector3df(x, y, z)); }
#include <irrlicht.h> #include <btBulletDynamicsCommon.h> #include <cassert> #include <Windows.h> #include "System.h" using namespace irr; using namespace core; System::System() : timer(nullptr), isRunning(true) { } System::~System() { } bool System::init() { InitializeCriticalSection(&cs); return true; } void System::release() { DeleteCriticalSection(&cs); } bool System::initGraphicsContents() { device = createDevice(video::EDT_OPENGL, dimension2d<u32>(800, 600), 32, false, false, false, nullptr); smgr = device->getSceneManager(); driver = device->getVideoDriver(); groundSceneNode = smgr->addCubeSceneNode(1.0f); groundSceneNode->setPosition(vector3df(0, -1, 0)); groundSceneNode->setScale(vector3df(100, 0, 100)); groundSceneNode->setMaterialFlag(irr::video::EMF_LIGHTING, false); groundSceneNode->setMaterialTexture(0, driver->getTexture("blue.png")); camera = smgr->addCameraSceneNodeFPS(); camera->setPosition(vector3df(0, 20, -50)); camera->setTarget(vector3df(0, 0, 0)); return true; } void System::releaseGraphicsContents() { device->drop(); } bool System::initPhysicsContents() { broadphase = new btDbvtBroadphase(); collisionConfiguration = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfiguration); solver = new btSequentialImpulseConstraintSolver(); dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld->setGravity(btVector3(0, -10, 0)); groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1); btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0))); btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0)); groundRigidBody = new btRigidBody(groundRigidBodyCI); dynamicsWorld->addRigidBody(groundRigidBody); rigidBodies.push_back(groundRigidBody); return true; } void System::releasePhysicsContents() { for (auto body : rigidBodies) { dynamicsWorld->removeRigidBody(body); delete body->getMotionState(); delete body->getCollisionShape(); delete body; } rigidBodies.clear(); delete dynamicsWorld; delete solver; delete collisionConfiguration; delete dispatcher; delete broadphase; } DWORD WINAPI runGraphics( LPVOID parameter ) { System *sys = (System*)parameter; sys->initGraphicsContents(); sys->timer = sys->device->getTimer(); while (sys->device->run()){ sys->draw(); } sys->releaseGraphicsContents(); sys->isRunning = false; return EXIT_SUCCESS; } void System::run() { CreateThread( NULL, 0, runGraphics, this, 0, nullptr); while (timer == nullptr); u32 lastTime = timer->getRealTime(); globalTimer = 0.0; FPSTimer = 0.0; FPS = 0; initPhysicsContents(); while (isRunning) { u32 currentTime = timer->getRealTime(); double dt = (currentTime - lastTime) / 1000.0; lastTime = currentTime; update(dt); } releasePhysicsContents(); } void System::update(double dt) { dynamicsWorld->stepSimulation(dt, 10); for (unsigned i = 0; i < rigidBodies.size(); ++i) { auto body = rigidBodies[i]; btTransform trans; body->getMotionState()->getWorldTransform(trans); const btVector3& origin = trans.getOrigin(); messageQueue.push(new Message(EMT_UPDATE, new UpdatePacket(origin.getX(), origin.getY(), origin.getZ(), i))); } if (globalTimer > 0.1) { addRigidBody((rand() % SHRT_MAX) / (double)SHRT_MAX, 50, (rand() % SHRT_MAX) / (double)SHRT_MAX, 1.0); globalTimer = 0.0; } if (FPSTimer > 1.0) { printf("%d\n", FPS); FPS = 0; FPSTimer = 0.0; } globalTimer += dt; FPSTimer += dt; ++FPS; } void System::draw() { while (messageQueue.empty() == false) { auto msg = messageQueue.front(); messageQueue.pop(); if (msg->type == EMT_INSERT) { auto packet = reinterpret_cast<InsertPacket*>(msg->user_data); assert(packet); addSceneNode(packet->x, packet->y, packet->z, packet->radius, packet->idx); } else if (msg->type == EMT_ERASE) { auto packet = reinterpret_cast<ErasePacket*>(msg->user_data); eraseSceneNode(packet->idx); } else if (msg->type == EMT_UPDATE) { auto packet = reinterpret_cast<UpdatePacket*>(msg->user_data); updateSceneNode(packet->x, packet->y, packet->z, packet->idx); } else { printf("Invalid message\n"); continue; } delete msg->user_data; msg->user_data = nullptr; msg->drop(); } driver->beginScene(true, true, video::SColor(255, 255, 0, 255)); smgr->drawAll(); driver->endScene(); } void System::addRigidBody(double x, double y, double z, double radius) { btCollisionShape* shape = new btSphereShape(radius); btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(x, y, z))); btScalar mass = 1; btVector3 Inertia(0, 0, 0); shape->calculateLocalInertia(mass, Inertia); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, motionState, shape, Inertia); btRigidBody* rigidBody = new btRigidBody(rigidBodyCI); dynamicsWorld->addRigidBody(rigidBody); int idx = -1; if (unused.empty()) { idx = rigidBodies.size(); } else { idx = unused.front(); unused.pop(); } assert(idx != -1); rigidBodies.push_back(rigidBody); messageQueue.push(new Message(EMT_INSERT, new InsertPacket(x, y, z, radius, idx))); } void System::addSceneNode(double x, double y, double z, double radius, unsigned idx) { scene::ISceneNode* sceneNode = smgr->addSphereSceneNode(radius); sceneNode->setPosition(vector3df(x, y, z)); sceneNode->setMaterialFlag(irr::video::EMF_LIGHTING, false); sceneNode->setMaterialTexture(0, driver->getTexture("red.png")); sceneNodes[idx] = sceneNode; } void System::eraseSceneNode(unsigned idx) { auto it = sceneNodes.find(idx); assert(it != sceneNodes.end()); sceneNodes.erase(it); } void System::updateSceneNode(double x, double y, double z, unsigned idx) { sceneNodes[idx]->setPosition(vector3df(x, y, z)); }
delete legacy in initializing and releasing physic
delete legacy in initializing and releasing physic
C++
mit
jafffy/concurrentGraphics
8f85977f4b288cf496318dec3471659e1bbe5e8c
clang-query/tool/ClangQuery.cpp
clang-query/tool/ClangQuery.cpp
//===---- ClangQuery.cpp - clang-query tool -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tool is for interactive exploration of the Clang AST using AST matchers. // It currently allows the user to enter a matcher at an interactive prompt and // view the resulting bindings as diagnostics, AST pretty prints or AST dumps. // Example session: // // $ cat foo.c // void foo(void) {} // $ clang-query foo.c -- // clang-query> match functionDecl() // // Match #1: // // foo.c:1:1: note: "root" binds here // void foo(void) {} // ^~~~~~~~~~~~~~~~~ // 1 match. // //===----------------------------------------------------------------------===// #include "Query.h" #include "QueryParser.h" #include "QuerySession.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" #include "llvm/LineEditor/LineEditor.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include <fstream> #include <string> using namespace clang; using namespace clang::ast_matchers; using namespace clang::ast_matchers::dynamic; using namespace clang::query; using namespace clang::tooling; using namespace llvm; static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::OptionCategory ClangQueryCategory("clang-query options"); static cl::list<std::string> Commands("c", cl::desc("Specify command to run"), cl::value_desc("command"), cl::cat(ClangQueryCategory)); static cl::list<std::string> CommandFiles("f", cl::desc("Read commands from file"), cl::value_desc("file"), cl::cat(ClangQueryCategory)); int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory); if (!Commands.empty() && !CommandFiles.empty()) { llvm::errs() << argv[0] << ": cannot specify both -c and -f\n"; return 1; } ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); std::vector<std::unique_ptr<ASTUnit>> ASTs; if (Tool.buildASTs(ASTs) != 0) return 1; QuerySession QS(ASTs); if (!Commands.empty()) { for (cl::list<std::string>::iterator I = Commands.begin(), E = Commands.end(); I != E; ++I) { QueryRef Q = QueryParser::parse(I->c_str(), QS); if (!Q->run(llvm::outs(), QS)) return 1; } } else if (!CommandFiles.empty()) { for (cl::list<std::string>::iterator I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) { std::ifstream Input(I->c_str()); if (!Input.is_open()) { llvm::errs() << argv[0] << ": cannot open " << *I << "\n"; return 1; } while (Input.good()) { std::string Line; std::getline(Input, Line); QueryRef Q = QueryParser::parse(Line.c_str(), QS); if (!Q->run(llvm::outs(), QS)) return 1; } } } else { LineEditor LE("clang-query"); LE.setListCompleter([&QS](StringRef Line, size_t Pos) { return QueryParser::complete(Line, Pos, QS); }); while (llvm::Optional<std::string> Line = LE.readLine()) { QueryRef Q = QueryParser::parse(*Line, QS); Q->run(llvm::outs(), QS); llvm::outs().flush(); if (QS.Terminate) break; } } return 0; }
//===---- ClangQuery.cpp - clang-query tool -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tool is for interactive exploration of the Clang AST using AST matchers. // It currently allows the user to enter a matcher at an interactive prompt and // view the resulting bindings as diagnostics, AST pretty prints or AST dumps. // Example session: // // $ cat foo.c // void foo(void) {} // $ clang-query foo.c -- // clang-query> match functionDecl() // // Match #1: // // foo.c:1:1: note: "root" binds here // void foo(void) {} // ^~~~~~~~~~~~~~~~~ // 1 match. // //===----------------------------------------------------------------------===// #include "Query.h" #include "QueryParser.h" #include "QuerySession.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" #include "llvm/LineEditor/LineEditor.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include <fstream> #include <string> using namespace clang; using namespace clang::ast_matchers; using namespace clang::ast_matchers::dynamic; using namespace clang::query; using namespace clang::tooling; using namespace llvm; static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::OptionCategory ClangQueryCategory("clang-query options"); static cl::list<std::string> Commands("c", cl::desc("Specify command to run"), cl::value_desc("command"), cl::cat(ClangQueryCategory)); static cl::list<std::string> CommandFiles("f", cl::desc("Read commands from file"), cl::value_desc("file"), cl::cat(ClangQueryCategory)); int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory); if (!Commands.empty() && !CommandFiles.empty()) { llvm::errs() << argv[0] << ": cannot specify both -c and -f\n"; return 1; } ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); std::vector<std::unique_ptr<ASTUnit>> ASTs; if (Tool.buildASTs(ASTs) != 0) return 1; QuerySession QS(ASTs); if (!Commands.empty()) { for (cl::list<std::string>::iterator I = Commands.begin(), E = Commands.end(); I != E; ++I) { QueryRef Q = QueryParser::parse(*I, QS); if (!Q->run(llvm::outs(), QS)) return 1; } } else if (!CommandFiles.empty()) { for (cl::list<std::string>::iterator I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) { std::ifstream Input(I->c_str()); if (!Input.is_open()) { llvm::errs() << argv[0] << ": cannot open " << *I << "\n"; return 1; } while (Input.good()) { std::string Line; std::getline(Input, Line); QueryRef Q = QueryParser::parse(Line, QS); if (!Q->run(llvm::outs(), QS)) return 1; } } } else { LineEditor LE("clang-query"); LE.setListCompleter([&QS](StringRef Line, size_t Pos) { return QueryParser::complete(Line, Pos, QS); }); while (llvm::Optional<std::string> Line = LE.readLine()) { QueryRef Q = QueryParser::parse(*Line, QS); Q->run(llvm::outs(), QS); llvm::outs().flush(); if (QS.Terminate) break; } } return 0; }
Fix Clang-tidy readability-redundant-string-cstr warnings
[clang-query] Fix Clang-tidy readability-redundant-string-cstr warnings Reviewers: pcc, dblaikie Subscribers: cfe-commits Differential Revision: https://reviews.llvm.org/D26205 git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@285731 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
14853c3b136e979e228b3b31ac4d90c639880122
tree/tree/src/TFriendElement.cxx
tree/tree/src/TFriendElement.cxx
// @(#)root/tree:$Id$ // Author: Rene Brun 07/04/2001 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFriendElement // // // // A TFriendElement TF describes a TTree object TF in a file. // // When a TFriendElement TF is added to the the list of friends of an // // existing TTree T, any variable from TF can be referenced in a query // // to T. // // // // To add a TFriendElement to an existing TTree T, do: // // T.AddFriend("friendTreename","friendTreeFile"); // // // // See TTree::AddFriend for more information. // // // ////////////////////////////////////////////////////////////////////////// #include "TTree.h" #include "TFriendElement.h" #include "TFile.h" #include "TROOT.h" ClassImp(TFriendElement) //////////////////////////////////////////////////////////////////////////////// ///*-*-*-*-*-*Default constructor for a friend element*-*-*-*-*-*-*-*-*-*-*-*-* ///*-* ======================================= TFriendElement::TFriendElement() : TNamed() { fFile = 0; fTree = 0; fOwnFile = kFALSE; fParentTree = 0; } //////////////////////////////////////////////////////////////////////////////// ///*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ///*-* ====================== /// /// If treename is of the form "a=b", an alias called "a" is created for /// treename = "b" by default the alias name is the name of the tree. TFriendElement::TFriendElement(TTree *tree, const char *treename, const char *filename) :TNamed(treename,filename) { fFile = 0; fTree = 0; fOwnFile = kTRUE; fParentTree = tree; fTreeName = treename; if (treename && strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); if (!equal) return;; *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //////////////////////////////////////////////////////////////////////////////// ///*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ///*-* ====================== /// /// If treename is of the form "a=b", an alias called "a" is created for /// treename = "b" by default the alias name is the name of the tree. /// The passed TFile is managed by the user (i.e. user must delete the TFile). TFriendElement::TFriendElement(TTree *tree, const char *treename, TFile *file) :TNamed(treename,file?file->GetName():"") { fFile = file; fTree = 0; fOwnFile = kFALSE; fParentTree = tree; fTreeName = treename; if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } if (treename && strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); if (!equal) return;; *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //////////////////////////////////////////////////////////////////////////////// /// Create a friend element. TFriendElement::TFriendElement(TTree *tree, TTree* friendtree, const char *alias) : TNamed(friendtree?friendtree->GetName():"", friendtree ? ( friendtree->GetDirectory() ? ( friendtree->GetDirectory()->GetFile() ? friendtree->GetDirectory()->GetFile()->GetName() : "") : "") : "") { fTree = friendtree; fTreeName = ""; fFile = 0; fOwnFile = kFALSE; fParentTree = tree; if (fTree) { fTreeName = fTree->GetName(); if (fTree->GetDirectory()) fFile = fTree->GetDirectory()->GetFile(); if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } } if (alias && strlen(alias)) { char *temp = Compress(alias); SetName(temp); delete [] temp; } // No need to Connect. } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor TFriendElement::TFriendElement(const TFriendElement& tfe) : TNamed(tfe), fParentTree(tfe.fParentTree), fTree(tfe.fTree), fFile(tfe.fFile), fTreeName(tfe.fTreeName), fOwnFile(tfe.fOwnFile) { } //////////////////////////////////////////////////////////////////////////////// /// Equal operator TFriendElement& TFriendElement::operator=(const TFriendElement& tfe) { if(this!=&tfe) { TNamed::operator=(tfe); fParentTree=tfe.fParentTree; fTree=tfe.fTree; fFile=tfe.fFile; fTreeName=tfe.fTreeName; fOwnFile=tfe.fOwnFile; } return *this; } //////////////////////////////////////////////////////////////////////////////// /// Destructor. Disconnect from the owning tree if needed. TFriendElement::~TFriendElement() { DisConnect(); } //////////////////////////////////////////////////////////////////////////////// /// Connect file and return TTree. TTree *TFriendElement::Connect() { GetFile(); return GetTree(); } //////////////////////////////////////////////////////////////////////////////// /// DisConnect file and TTree. TTree *TFriendElement::DisConnect() { if (fOwnFile) delete fFile; fFile = 0; fTree = 0; return 0; } //////////////////////////////////////////////////////////////////////////////// /// Return pointer to TFile containing this friend TTree. TFile *TFriendElement::GetFile() { if (fFile || IsZombie()) return fFile; if (strlen(GetTitle())) { TDirectory::TContext ctxt; fFile = TFile::Open(GetTitle()); fOwnFile = kTRUE; } else { TDirectory *dir = fParentTree->GetDirectory(); if (dir) { fFile = dir->GetFile(); fOwnFile = kFALSE; } } if (fFile && fFile->IsZombie()) { MakeZombie(); delete fFile; fFile = 0; } return fFile; } //////////////////////////////////////////////////////////////////////////////// /// Return pointer to friend TTree. TTree *TFriendElement::GetTree() { if (fTree) return fTree; if (GetFile()) { fFile->GetObject(GetTreeName(),fTree); if (fTree) return fTree; } // This could be a memory tree or chain fTree = dynamic_cast<TTree*>( gROOT->FindObject(GetTreeName()) ); return fTree; } //////////////////////////////////////////////////////////////////////////////// /// List this friend element. void TFriendElement::ls(Option_t *) const { printf(" Friend Tree: %s in file: %s\n",GetName(),GetTitle()); }
// @(#)root/tree:$Id$ // Author: Rene Brun 07/04/2001 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFriendElement // // // // A TFriendElement TF describes a TTree object TF in a file. // // When a TFriendElement TF is added to the the list of friends of an // // existing TTree T, any variable from TF can be referenced in a query // // to T. // // // // To add a TFriendElement to an existing TTree T, do: // // T.AddFriend("friendTreename","friendTreeFile"); // // // // See TTree::AddFriend for more information. // // // ////////////////////////////////////////////////////////////////////////// #include "TTree.h" #include "TFriendElement.h" #include "TFile.h" #include "TROOT.h" ClassImp(TFriendElement) //////////////////////////////////////////////////////////////////////////////// ///*-*-*-*-*-*Default constructor for a friend element*-*-*-*-*-*-*-*-*-*-*-*-* ///*-* ======================================= TFriendElement::TFriendElement() : TNamed() { fFile = 0; fTree = 0; fOwnFile = kFALSE; fParentTree = 0; } //////////////////////////////////////////////////////////////////////////////// ///*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ///*-* ====================== /// /// If treename is of the form "a=b", an alias called "a" is created for /// treename = "b" by default the alias name is the name of the tree. TFriendElement::TFriendElement(TTree *tree, const char *treename, const char *filename) :TNamed(treename,filename) { fFile = 0; fTree = 0; fOwnFile = kTRUE; fParentTree = tree; fTreeName = treename; if (treename && strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); if (!equal) return;; *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //////////////////////////////////////////////////////////////////////////////// ///*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ///*-* ====================== /// /// If treename is of the form "a=b", an alias called "a" is created for /// treename = "b" by default the alias name is the name of the tree. /// The passed TFile is managed by the user (i.e. user must delete the TFile). TFriendElement::TFriendElement(TTree *tree, const char *treename, TFile *file) :TNamed(treename,file?file->GetName():"") { fFile = file; fTree = 0; fOwnFile = kFALSE; fParentTree = tree; fTreeName = treename; if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } if (treename && strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); if (!equal) return;; *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //////////////////////////////////////////////////////////////////////////////// /// Create a friend element. TFriendElement::TFriendElement(TTree *tree, TTree* friendtree, const char *alias) : TNamed(friendtree?friendtree->GetName():"", friendtree ? ( friendtree->GetDirectory() ? ( friendtree->GetDirectory()->GetFile() ? friendtree->GetDirectory()->GetFile()->GetName() : "") : "") : "") { fTree = friendtree; fTreeName = ""; fFile = 0; fOwnFile = kFALSE; fParentTree = tree; if (fTree) { fTreeName = fTree->GetName(); if (fTree->GetDirectory()) fFile = fTree->GetDirectory()->GetFile(); if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } } else { MakeZombie(); // ROOT-7007 } if (alias && strlen(alias)) { char *temp = Compress(alias); SetName(temp); delete [] temp; } // No need to Connect. } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor TFriendElement::TFriendElement(const TFriendElement& tfe) : TNamed(tfe), fParentTree(tfe.fParentTree), fTree(tfe.fTree), fFile(tfe.fFile), fTreeName(tfe.fTreeName), fOwnFile(tfe.fOwnFile) { } //////////////////////////////////////////////////////////////////////////////// /// Equal operator TFriendElement& TFriendElement::operator=(const TFriendElement& tfe) { if(this!=&tfe) { TNamed::operator=(tfe); fParentTree=tfe.fParentTree; fTree=tfe.fTree; fFile=tfe.fFile; fTreeName=tfe.fTreeName; fOwnFile=tfe.fOwnFile; } return *this; } //////////////////////////////////////////////////////////////////////////////// /// Destructor. Disconnect from the owning tree if needed. TFriendElement::~TFriendElement() { DisConnect(); } //////////////////////////////////////////////////////////////////////////////// /// Connect file and return TTree. TTree *TFriendElement::Connect() { GetFile(); auto treePtr = GetTree(); if (!treePtr) MakeZombie(); // ROOT-7007 return treePtr; } //////////////////////////////////////////////////////////////////////////////// /// DisConnect file and TTree. TTree *TFriendElement::DisConnect() { if (fOwnFile) delete fFile; fFile = 0; fTree = 0; return 0; } //////////////////////////////////////////////////////////////////////////////// /// Return pointer to TFile containing this friend TTree. TFile *TFriendElement::GetFile() { if (fFile || IsZombie()) return fFile; if (strlen(GetTitle())) { TDirectory::TContext ctxt; fFile = TFile::Open(GetTitle()); fOwnFile = kTRUE; } else { TDirectory *dir = fParentTree->GetDirectory(); if (dir) { fFile = dir->GetFile(); fOwnFile = kFALSE; } } if (fFile && fFile->IsZombie()) { MakeZombie(); delete fFile; fFile = 0; } return fFile; } //////////////////////////////////////////////////////////////////////////////// /// Return pointer to friend TTree. TTree *TFriendElement::GetTree() { if (fTree) return fTree; if (GetFile()) { fFile->GetObject(GetTreeName(),fTree); if (fTree) return fTree; } // This could be a memory tree or chain fTree = dynamic_cast<TTree*>( gROOT->FindObject(GetTreeName()) ); return fTree; } //////////////////////////////////////////////////////////////////////////////// /// List this friend element. void TFriendElement::ls(Option_t *) const { printf(" Friend Tree: %s in file: %s\n",GetName(),GetTitle()); }
Fix ROOT-7007: make TFriendElment zombie when the tree does not exist
Fix ROOT-7007: make TFriendElment zombie when the tree does not exist
C++
lgpl-2.1
olifre/root,omazapa/root,satyarth934/root,mhuwiler/rootauto,veprbl/root,veprbl/root,olifre/root,zzxuanyuan/root,BerserkerTroll/root,karies/root,georgtroska/root,zzxuanyuan/root,georgtroska/root,beniz/root,root-mirror/root,olifre/root,bbockelm/root,gbitzes/root,esakellari/root,evgeny-boger/root,nilqed/root,abhinavmoudgil95/root,lgiommi/root,gbitzes/root,perovic/root,thomaskeck/root,omazapa/root,BerserkerTroll/root,davidlt/root,beniz/root,perovic/root,root-mirror/root,CristinaCristescu/root,esakellari/root,Duraznos/root,sawenzel/root,beniz/root,lgiommi/root,BerserkerTroll/root,sirinath/root,perovic/root,beniz/root,agarciamontoro/root,simonpf/root,davidlt/root,BerserkerTroll/root,agarciamontoro/root,Y--/root,olifre/root,vukasinmilosevic/root,vukasinmilosevic/root,mattkretz/root,olifre/root,evgeny-boger/root,lgiommi/root,omazapa/root,lgiommi/root,mattkretz/root,buuck/root,georgtroska/root,olifre/root,arch1tect0r/root,davidlt/root,lgiommi/root,krafczyk/root,gbitzes/root,arch1tect0r/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,mkret2/root,karies/root,vukasinmilosevic/root,vukasinmilosevic/root,gbitzes/root,abhinavmoudgil95/root,veprbl/root,mhuwiler/rootauto,satyarth934/root,davidlt/root,evgeny-boger/root,sawenzel/root,CristinaCristescu/root,jrtomps/root,pspe/root,esakellari/root,jrtomps/root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,simonpf/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,Y--/root,omazapa/root,jrtomps/root,satyarth934/root,root-mirror/root,karies/root,bbockelm/root,bbockelm/root,georgtroska/root,arch1tect0r/root,zzxuanyuan/root,veprbl/root,simonpf/root,root-mirror/root,georgtroska/root,esakellari/root,mkret2/root,BerserkerTroll/root,esakellari/root,nilqed/root,nilqed/root,Duraznos/root,gganis/root,satyarth934/root,beniz/root,karies/root,BerserkerTroll/root,gbitzes/root,bbockelm/root,nilqed/root,buuck/root,veprbl/root,veprbl/root,CristinaCristescu/root,mattkretz/root,mkret2/root,omazapa/root,krafczyk/root,esakellari/root,davidlt/root,root-mirror/root,jrtomps/root,CristinaCristescu/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,mkret2/root,vukasinmilosevic/root,arch1tect0r/root,sirinath/root,gganis/root,evgeny-boger/root,Duraznos/root,omazapa/root,omazapa/root,mattkretz/root,sirinath/root,simonpf/root,satyarth934/root,zzxuanyuan/root,thomaskeck/root,satyarth934/root,evgeny-boger/root,pspe/root,lgiommi/root,pspe/root,karies/root,Duraznos/root,perovic/root,abhinavmoudgil95/root,zzxuanyuan/root,simonpf/root,buuck/root,beniz/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,buuck/root,georgtroska/root,evgeny-boger/root,Duraznos/root,Y--/root,abhinavmoudgil95/root,beniz/root,Duraznos/root,agarciamontoro/root,CristinaCristescu/root,georgtroska/root,gganis/root,krafczyk/root,gbitzes/root,bbockelm/root,vukasinmilosevic/root,arch1tect0r/root,satyarth934/root,jrtomps/root,evgeny-boger/root,arch1tect0r/root,esakellari/root,karies/root,mattkretz/root,Y--/root,mhuwiler/rootauto,gbitzes/root,zzxuanyuan/root,Y--/root,esakellari/root,beniz/root,davidlt/root,CristinaCristescu/root,jrtomps/root,nilqed/root,mattkretz/root,zzxuanyuan/root,gbitzes/root,Y--/root,omazapa/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,veprbl/root,buuck/root,zzxuanyuan/root-compressor-dummy,BerserkerTroll/root,CristinaCristescu/root,perovic/root,bbockelm/root,vukasinmilosevic/root,perovic/root,georgtroska/root,agarciamontoro/root,lgiommi/root,pspe/root,sawenzel/root,davidlt/root,olifre/root,krafczyk/root,sirinath/root,bbockelm/root,krafczyk/root,agarciamontoro/root,omazapa/root,root-mirror/root,krafczyk/root,veprbl/root,veprbl/root,sawenzel/root,agarciamontoro/root,pspe/root,buuck/root,thomaskeck/root,mkret2/root,karies/root,lgiommi/root,mhuwiler/rootauto,sirinath/root,pspe/root,krafczyk/root,Y--/root,georgtroska/root,gganis/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,olifre/root,nilqed/root,gbitzes/root,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,davidlt/root,zzxuanyuan/root,gbitzes/root,sirinath/root,karies/root,root-mirror/root,perovic/root,esakellari/root,davidlt/root,olifre/root,root-mirror/root,sawenzel/root,abhinavmoudgil95/root,nilqed/root,georgtroska/root,perovic/root,abhinavmoudgil95/root,vukasinmilosevic/root,arch1tect0r/root,BerserkerTroll/root,evgeny-boger/root,simonpf/root,thomaskeck/root,veprbl/root,bbockelm/root,nilqed/root,sawenzel/root,mhuwiler/rootauto,satyarth934/root,pspe/root,beniz/root,karies/root,mhuwiler/rootauto,pspe/root,vukasinmilosevic/root,olifre/root,sawenzel/root,sirinath/root,mkret2/root,jrtomps/root,zzxuanyuan/root,evgeny-boger/root,agarciamontoro/root,Y--/root,simonpf/root,jrtomps/root,agarciamontoro/root,nilqed/root,perovic/root,mkret2/root,sirinath/root,thomaskeck/root,root-mirror/root,nilqed/root,mhuwiler/rootauto,vukasinmilosevic/root,karies/root,pspe/root,buuck/root,pspe/root,lgiommi/root,arch1tect0r/root,pspe/root,sawenzel/root,buuck/root,esakellari/root,omazapa/root,evgeny-boger/root,gganis/root,mhuwiler/rootauto,zzxuanyuan/root,gbitzes/root,abhinavmoudgil95/root,sawenzel/root,mkret2/root,Duraznos/root,abhinavmoudgil95/root,veprbl/root,CristinaCristescu/root,zzxuanyuan/root,georgtroska/root,buuck/root,CristinaCristescu/root,perovic/root,arch1tect0r/root,beniz/root,root-mirror/root,mattkretz/root,buuck/root,sawenzel/root,thomaskeck/root,agarciamontoro/root,jrtomps/root,Duraznos/root,lgiommi/root,vukasinmilosevic/root,omazapa/root,mhuwiler/rootauto,satyarth934/root,simonpf/root,abhinavmoudgil95/root,mattkretz/root,Y--/root,olifre/root,buuck/root,gganis/root,davidlt/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,gganis/root,BerserkerTroll/root,thomaskeck/root,Duraznos/root,thomaskeck/root,bbockelm/root,simonpf/root,beniz/root,nilqed/root,gganis/root,gganis/root,zzxuanyuan/root,agarciamontoro/root,davidlt/root,simonpf/root,zzxuanyuan/root-compressor-dummy,Y--/root,bbockelm/root,esakellari/root,mkret2/root,simonpf/root,Duraznos/root,thomaskeck/root,Duraznos/root,BerserkerTroll/root,sirinath/root,bbockelm/root,satyarth934/root,agarciamontoro/root,sawenzel/root,CristinaCristescu/root,abhinavmoudgil95/root,sirinath/root,mattkretz/root,mattkretz/root,karies/root,Y--/root,evgeny-boger/root,BerserkerTroll/root,root-mirror/root,krafczyk/root,gganis/root,mattkretz/root,sirinath/root,gganis/root,perovic/root,mkret2/root,mhuwiler/rootauto,lgiommi/root,jrtomps/root,jrtomps/root,mkret2/root,thomaskeck/root
eab4bf77a2d859ecb3a77b77b02f7a7dc27f724c
trunk/extension/src/printing.cpp
trunk/extension/src/printing.cpp
/******************************************************************************\ * File: app.cpp * Purpose: Implementation of wxExPrinting class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/stc/stc.h> #include <wx/extension/printing.h> #include <wx/extension/util.h> wxExPrinting* wxExPrinting::m_Self = NULL; wxExPrinting::wxExPrinting() { #if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE m_HtmlPrinter = new wxHtmlEasyPrinting(); m_HtmlPrinter->SetFonts(wxEmptyString, wxEmptyString); // use defaults m_HtmlPrinter->GetPageSetupData()->SetMarginBottomRight(wxPoint(15, 5)); m_HtmlPrinter->GetPageSetupData()->SetMarginTopLeft(wxPoint(15, 5)); m_HtmlPrinter->SetHeader(wxExPrintHeader(wxFileName())); m_HtmlPrinter->SetFooter(wxExPrintFooter()); #endif #if wxUSE_PRINTING_ARCHITECTURE m_Printer = new wxPrinter; #endif } wxExPrinting::~wxExPrinting() { #if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE delete m_HtmlPrinter; #endif #if wxUSE_PRINTING_ARCHITECTURE delete m_Printer; #endif } wxExPrinting* wxExPrinting::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExPrinting(); } return m_Self; } wxExPrinting* wxExPrinting::Set(wxExPrinting* printing) { wxExPrinting* old = m_Self; m_Self = printing; return old; } #if wxUSE_PRINTING_ARCHITECTURE wxExPrintout::wxExPrintout(wxStyledTextCtrl* owner) : wxPrintout(wxExPrintCaption(owner->GetName())) , m_PageRect() , m_PrintRect() , m_PageBreaks() , m_Owner(owner) { } void wxExPrintout::CountPages() { wxASSERT(GetDC() != NULL); wxBusyCursor wait; m_PageBreaks.clear(); m_PageBreaks.push_back(0); // a page break at pos 0 int pos = 0; while (pos < m_Owner->GetLength()) { SetScale(GetDC()); pos = m_Owner->FormatRange( false, pos, m_Owner->GetLength(), GetDC(), GetDC(), m_PrintRect, m_PageRect); m_PageBreaks.push_back(pos); } } void wxExPrintout::GetPageInfo( int* minPage, int* maxPage, int* pageFrom, int* pageTo) { *minPage = 1; *maxPage = m_PageBreaks.size() - 1; *pageFrom = 1; *pageTo = m_PageBreaks.size() - 1; } void wxExPrintout::OnPreparePrinting() { const double factor = 22.4; wxSize ppiScr; GetPPIScreen(&ppiScr.x, &ppiScr.y); auto* dlg_data = wxExPrinting::Get()->GetHtmlPrinter()->GetPageSetupData(); wxSize page = dlg_data->GetPaperSize(); if (page.x == 0 || page.y == 0) { dlg_data->SetPaperSize(wxPAPER_A4); page = dlg_data->GetPaperSize(); } page.x = (int)(page.x * ppiScr.x / factor); page.y = (int)(page.y * ppiScr.y / factor); m_PageRect = wxRect(0, 0, page.x, page.y); int left = (int)(dlg_data->GetMarginTopLeft().x * ppiScr.x / factor); int top = (int)(dlg_data->GetMarginTopLeft().y * ppiScr.y / factor); int right = (int)(dlg_data->GetMarginBottomRight().x * ppiScr.x / factor); int bottom = (int)(dlg_data->GetMarginBottomRight().y * ppiScr.y / factor); m_PrintRect = wxRect( left, top, page.x - (left + right), page.y - (top + bottom)); CountPages(); } bool wxExPrintout::OnPrintPage(int pageNum) { wxASSERT(GetDC() != NULL); if (pageNum > (int)m_PageBreaks.size()) { wxFAIL; return false; } SetScale(GetDC()); m_Owner->FormatRange( true, m_PageBreaks[pageNum - 1], m_Owner->GetTextLength(), GetDC(), GetDC(), m_PrintRect, m_PageRect); wxFont font = *wxNORMAL_FONT; font.SetWeight(wxBOLD); GetDC()->SetFont(font); GetDC()->SetTextForeground(*wxBLACK); GetDC()->SetTextBackground(*wxWHITE); GetDC()->SetPen(*wxBLACK_PEN); // Print a header. const wxString header = wxExPrintHeader(m_Owner->GetName()); if (!header.empty()) { const int text_from_top = 27; const int line_from_top = 12; GetDC()->DrawText( wxExTranslate(header, pageNum, m_PageBreaks.size() - 1), m_PrintRect.GetTopLeft().x, m_PrintRect.GetTopLeft().y - text_from_top); GetDC()->DrawLine( m_PrintRect.GetTopLeft().x, m_PrintRect.GetTopLeft().y - line_from_top, m_PrintRect.GetBottomRight().x, m_PrintRect.GetTopLeft().y - line_from_top); } // Print a footer const wxString footer = wxExPrintFooter(); if (!footer.empty()) { GetDC()->DrawText( wxExTranslate(footer, pageNum, m_PageBreaks.size() - 1), m_PrintRect.GetBottomRight().x / 2, m_PrintRect.GetBottomRight().y); GetDC()->DrawLine( m_PrintRect.GetTopLeft().x, m_PrintRect.GetBottomRight().y, m_PrintRect.GetBottomRight().x, m_PrintRect.GetBottomRight().y); } return true; } void wxExPrintout::SetScale(wxDC *dc) { wxSize ppiScr, ppiPrt; GetPPIScreen(&ppiScr.x, &ppiScr.y); if (ppiScr.x == 0) { // Most possible gues 96 dpi. ppiScr.x = 96; ppiScr.y = 96; } GetPPIPrinter(&ppiPrt.x, &ppiPrt.y); if (ppiPrt.x == 0) { // Scaling factor to 1. ppiPrt.x = ppiScr.x; ppiPrt.y = ppiScr.y; } const wxSize dcSize = dc->GetSize(); wxSize pageSize; GetPageSizePixels(&pageSize.x, &pageSize.y); const double factor = 0.8; const float scale_x = (float)(factor * ppiPrt.x * dcSize.x) / (float)(ppiScr.x * pageSize.x); const float scale_y = (float)(factor * ppiPrt.y * dcSize.y) / (float)(ppiScr.y * pageSize.y); dc->SetUserScale(scale_x, scale_y); } #endif // wxUSE_PRINTING_ARCHITECTURE
/******************************************************************************\ * File: app.cpp * Purpose: Implementation of wxExPrinting class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/stc/stc.h> #include <wx/extension/printing.h> #include <wx/extension/util.h> wxExPrinting* wxExPrinting::m_Self = NULL; wxExPrinting::wxExPrinting() { #if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE m_HtmlPrinter = new wxHtmlEasyPrinting(); m_HtmlPrinter->SetFonts(wxEmptyString, wxEmptyString); // use defaults m_HtmlPrinter->GetPageSetupData()->SetMarginBottomRight(wxPoint(15, 5)); m_HtmlPrinter->GetPageSetupData()->SetMarginTopLeft(wxPoint(15, 5)); m_HtmlPrinter->SetHeader(wxExPrintHeader(wxFileName())); m_HtmlPrinter->SetFooter(wxExPrintFooter()); #endif #if wxUSE_PRINTING_ARCHITECTURE m_Printer = new wxPrinter; #endif } wxExPrinting::~wxExPrinting() { #if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE delete m_HtmlPrinter; #endif #if wxUSE_PRINTING_ARCHITECTURE delete m_Printer; #endif } wxExPrinting* wxExPrinting::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExPrinting(); } return m_Self; } wxExPrinting* wxExPrinting::Set(wxExPrinting* printing) { wxExPrinting* old = m_Self; m_Self = printing; return old; } #if wxUSE_PRINTING_ARCHITECTURE wxExPrintout::wxExPrintout(wxStyledTextCtrl* owner) : wxPrintout(wxExPrintCaption(owner->GetName())) , m_PageRect() , m_PrintRect() , m_PageBreaks() , m_Owner(owner) { } void wxExPrintout::CountPages() { wxASSERT(GetDC() != NULL); wxBusyCursor wait; m_PageBreaks.clear(); m_PageBreaks.push_back(0); // a page break at pos 0 int pos = 0; while (pos < m_Owner->GetLength()) { SetScale(GetDC()); pos = m_Owner->FormatRange( false, pos, m_Owner->GetLength(), GetDC(), GetDC(), m_PrintRect, m_PageRect); m_PageBreaks.push_back(pos); } } void wxExPrintout::GetPageInfo( int* minPage, int* maxPage, int* pageFrom, int* pageTo) { *minPage = 1; *maxPage = m_PageBreaks.size() - 1; *pageFrom = 1; *pageTo = m_PageBreaks.size() - 1; } void wxExPrintout::OnPreparePrinting() { const double factor = 22.4; wxSize ppiScr; GetPPIScreen(&ppiScr.x, &ppiScr.y); auto* dlg_data = wxExPrinting::Get()->GetHtmlPrinter()->GetPageSetupData(); wxSize page = dlg_data->GetPaperSize(); if (page.x == 0 || page.y == 0) { dlg_data->SetPaperSize(wxPAPER_A4); page = dlg_data->GetPaperSize(); } page.x = (int)(page.x * ppiScr.x / factor); page.y = (int)(page.y * ppiScr.y / factor); m_PageRect = wxRect(0, 0, page.x, page.y); int left = (int)(dlg_data->GetMarginTopLeft().x * ppiScr.x / factor); int top = (int)(dlg_data->GetMarginTopLeft().y * ppiScr.y / factor); int right = (int)(dlg_data->GetMarginBottomRight().x * ppiScr.x / factor); int bottom = (int)(dlg_data->GetMarginBottomRight().y * ppiScr.y / factor); m_PrintRect = wxRect( left, top, page.x - (left + right), page.y - (top + bottom)); CountPages(); } bool wxExPrintout::OnPrintPage(int pageNum) { wxASSERT(GetDC() != NULL); if (pageNum > (int)m_PageBreaks.size()) { wxFAIL; return false; } SetScale(GetDC()); m_Owner->FormatRange( true, m_PageBreaks[pageNum - 1], m_Owner->GetTextLength(), GetDC(), GetDC(), m_PrintRect, m_PageRect); wxFont font = *wxNORMAL_FONT; font.SetWeight(wxBOLD); GetDC()->SetFont(font); GetDC()->SetTextForeground(*wxBLACK); GetDC()->SetTextBackground(*wxWHITE); GetDC()->SetPen(*wxBLACK_PEN); // Print a header. const wxString header = wxExPrintHeader(m_Owner->GetName()); if (!header.empty()) { const int text_from_top = 23; const int line_from_top = 8; GetDC()->DrawText( wxExTranslate(header, pageNum, m_PageBreaks.size() - 1), m_PrintRect.GetTopLeft().x, m_PrintRect.GetTopLeft().y - text_from_top); GetDC()->DrawLine( m_PrintRect.GetTopLeft().x, m_PrintRect.GetTopLeft().y - line_from_top, m_PrintRect.GetBottomRight().x, m_PrintRect.GetTopLeft().y - line_from_top); } // Print a footer const wxString footer = wxExPrintFooter(); if (!footer.empty()) { GetDC()->DrawText( wxExTranslate(footer, pageNum, m_PageBreaks.size() - 1), m_PrintRect.GetBottomRight().x / 2, m_PrintRect.GetBottomRight().y); GetDC()->DrawLine( m_PrintRect.GetTopLeft().x, m_PrintRect.GetBottomRight().y, m_PrintRect.GetBottomRight().x, m_PrintRect.GetBottomRight().y); } return true; } void wxExPrintout::SetScale(wxDC *dc) { wxSize ppiScr, ppiPrt; GetPPIScreen(&ppiScr.x, &ppiScr.y); if (ppiScr.x == 0) { // Most possible gues 96 dpi. ppiScr.x = 96; ppiScr.y = 96; } GetPPIPrinter(&ppiPrt.x, &ppiPrt.y); if (ppiPrt.x == 0) { // Scaling factor to 1. ppiPrt.x = ppiScr.x; ppiPrt.y = ppiScr.y; } const wxSize dcSize = dc->GetSize(); wxSize pageSize; GetPageSizePixels(&pageSize.x, &pageSize.y); const double factor = 0.8; const float scale_x = (float)(factor * ppiPrt.x * dcSize.x) / (float)(ppiScr.x * pageSize.x); const float scale_y = (float)(factor * ppiPrt.y * dcSize.y) / (float)(ppiScr.y * pageSize.y); dc->SetUserScale(scale_x, scale_y); } #endif // wxUSE_PRINTING_ARCHITECTURE
change was wrong way
change was wrong way git-svn-id: e171abefef93db0a74257c7d87d5b6400fe00c1f@3753 f22100f3-aa73-48fe-a4fb-fd497bb32605
C++
mit
antonvw/wxExtension,antonvw/wxExtension,antonvw/wxExtension
31526bc15e409fb3260b465d928ddcb855266278
ucb/source/ucp/odma/odma_lib.cxx
ucb/source/ucp/odma/odma_lib.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucb.hxx" #ifdef WNT #include <windows.h> #endif #include <osl/module.h> #include <rtl/ustring.hxx> #include "odma_lib.hxx" namespace odma { TODMRegisterApp pODMRegisterApp; TODMUnRegisterApp pODMUnRegisterApp; TODMSelectDoc pODMSelectDoc; TODMOpenDoc pODMOpenDoc; TODMSaveDoc pODMSaveDoc; TODMCloseDoc pODMCloseDoc; TODMNewDoc pODMNewDoc; TODMSaveAs pODMSaveAs; TODMActivate pODMActivate; TODMGetDocInfo pODMGetDocInfo; TODMSetDocInfo pODMSetDocInfo; TODMGetDMSInfo pODMGetDMSInfo; TODMGetDMSCount pODMGetDMSCount; TODMGetDMSList pODMGetDMSList; TODMGetDMS pODMGetDMS; TODMSetDMS pODMSetDMS; TODMQueryExecute pODMQueryExecute; TODMQueryGetResults pODMQueryGetResults; TODMQueryClose pODMQueryClose; TODMCloseDocEx pODMCloseDocEx; TODMSaveAsEx pODMSaveAsEx; TODMSaveDocEx pODMSaveDocEx; TODMSelectDocEx pODMSelectDocEx; TODMQueryCapability pODMQueryCapability; TODMSetDocEvent pODMSetDocEvent; TODMGetAlternateContent pODMGetAlternateContent; TODMSetAlternateContent pODMSetAlternateContent; TODMGetDocRelation pODMGetDocRelation; TODMSetDocRelation pODMSetDocRelation; sal_Bool LoadFunctions(oslModule _pODMA); sal_Bool DMSsAvailable() { static sal_Bool bLoaded = sal_False; static sal_Bool bBeenHere = sal_False; oslModule pODMA = NULL; if (bBeenHere) return bLoaded; ::rtl::OUString sPath; #ifdef WNT sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMA32.DLL")); #endif #ifdef UNX sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("libodma.so")); #endif bBeenHere = sal_True; pODMA = osl_loadModule( sPath.pData,SAL_LOADMODULE_NOW ); if( !pODMA) return sal_False; if (!LoadFunctions(pODMA)) return sal_False; bLoaded = (NODMGetDMSCount() > 0); if (getenv ("NO_ODMA")) bLoaded = sal_False; return bLoaded; } // ------------------------------------------------------------------------- sal_Bool LoadFunctions(oslModule pODMA) { if ( ( pODMRegisterApp = (TODMRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMRegisterApp")).pData)) == NULL ) return sal_False; if ( ( pODMUnRegisterApp = (TODMUnRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMUnRegisterApp")).pData)) == NULL ) return sal_False; if ( ( pODMSelectDoc = (TODMSelectDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDoc")).pData)) == NULL ) return sal_False; if ( ( pODMOpenDoc = (TODMOpenDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMOpenDoc")).pData)) == NULL ) return sal_False; if ( ( pODMSaveDoc = (TODMSaveDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDoc")).pData)) == NULL ) return sal_False; if ( ( pODMCloseDoc = (TODMCloseDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDoc")).pData)) == NULL ) return sal_False; if ( ( pODMNewDoc = (TODMNewDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMNewDoc")).pData)) == NULL ) return sal_False; if ( ( pODMSaveAs = (TODMSaveAs)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAs")).pData)) == NULL ) return sal_False; if ( ( pODMActivate = (TODMActivate)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMActivate")).pData)) == NULL ) return sal_False; if ( ( pODMGetDocInfo = (TODMGetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocInfo")).pData)) == NULL ) return sal_False; if ( ( pODMSetDocInfo = (TODMSetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocInfo")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMSInfo = (TODMGetDMSInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSInfo")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMSCount = (TODMGetDMSCount)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSCount")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMSList = (TODMGetDMSList)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSList")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMS = (TODMGetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMS")).pData)) == NULL ) return sal_False; if ( ( pODMSetDMS = (TODMSetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDMS")).pData)) == NULL ) return sal_False; if ( ( pODMQueryExecute = (TODMQueryExecute)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryExecute")).pData)) == NULL ) return sal_False; if ( ( pODMQueryGetResults = (TODMQueryGetResults)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryGetResults")).pData)) == NULL ) return sal_False; if ( ( pODMQueryClose = (TODMQueryClose)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryClose")).pData)) == NULL ) return sal_False; if ( ( pODMCloseDocEx = (TODMCloseDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDocEx")).pData)) == NULL ) return sal_False; if ( ( pODMSaveAsEx = (TODMSaveAsEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAsEx")).pData)) == NULL ) return sal_False; if ( ( pODMSaveDocEx = (TODMSaveDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDocEx")).pData)) == NULL ) return sal_False; if ( ( pODMSelectDocEx = (TODMSelectDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDocEx")).pData)) == NULL ) return sal_False; if ( ( pODMQueryCapability = (TODMQueryCapability)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryCapability")).pData)) == NULL ) return sal_False; if ( ( pODMSetDocEvent = (TODMSetDocEvent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocEvent")).pData)) == NULL ) return sal_False; if ( ( pODMGetAlternateContent = (TODMGetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetAlternateContent")).pData)) == NULL ) return sal_False; if ( ( pODMSetAlternateContent = (TODMSetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetAlternateContent")).pData)) == NULL ) return sal_False; if ( ( pODMGetDocRelation = (TODMGetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocRelation")).pData)) == NULL ) return sal_False; if ( ( pODMSetDocRelation = (TODMSetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocRelation")).pData)) == NULL ) return sal_False; return sal_True; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucb.hxx" #ifdef WNT #include <windows.h> #endif #include <osl/module.h> #include <rtl/ustring.hxx> #include "odma_lib.hxx" namespace odma { TODMRegisterApp pODMRegisterApp; TODMUnRegisterApp pODMUnRegisterApp; TODMSelectDoc pODMSelectDoc; TODMOpenDoc pODMOpenDoc; TODMSaveDoc pODMSaveDoc; TODMCloseDoc pODMCloseDoc; TODMNewDoc pODMNewDoc; TODMSaveAs pODMSaveAs; TODMActivate pODMActivate; TODMGetDocInfo pODMGetDocInfo; TODMSetDocInfo pODMSetDocInfo; TODMGetDMSInfo pODMGetDMSInfo; TODMGetDMSCount pODMGetDMSCount; TODMGetDMSList pODMGetDMSList; TODMGetDMS pODMGetDMS; TODMSetDMS pODMSetDMS; TODMQueryExecute pODMQueryExecute; TODMQueryGetResults pODMQueryGetResults; TODMQueryClose pODMQueryClose; TODMCloseDocEx pODMCloseDocEx; TODMSaveAsEx pODMSaveAsEx; TODMSaveDocEx pODMSaveDocEx; TODMSelectDocEx pODMSelectDocEx; TODMQueryCapability pODMQueryCapability; TODMSetDocEvent pODMSetDocEvent; TODMGetAlternateContent pODMGetAlternateContent; TODMSetAlternateContent pODMSetAlternateContent; TODMGetDocRelation pODMGetDocRelation; TODMSetDocRelation pODMSetDocRelation; sal_Bool LoadFunctions(oslModule _pODMA); sal_Bool DMSsAvailable() { static sal_Bool bLoaded = sal_False; static sal_Bool bBeenHere = sal_False; oslModule pODMA = NULL; if (bBeenHere) return bLoaded; bBeenHere = sal_True; ::rtl::OUString sPath; #ifdef WNT wchar_t system32[MAX_PATH]; UINT n = GetSystemDirectoryW( system32, MAX_PATH ); if (n == 0) return sal_False; sPath = ::rtl::OUString( system32, n ) + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMA32.DLL")); #endif #ifdef UNX sPath = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("libodma.so")); #endif pODMA = osl_loadModule( sPath.pData,SAL_LOADMODULE_NOW ); if( !pODMA) return sal_False; if (!LoadFunctions(pODMA)) return sal_False; bLoaded = (NODMGetDMSCount() > 0); if (getenv ("NO_ODMA")) bLoaded = sal_False; return bLoaded; } // ------------------------------------------------------------------------- sal_Bool LoadFunctions(oslModule pODMA) { if ( ( pODMRegisterApp = (TODMRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMRegisterApp")).pData)) == NULL ) return sal_False; if ( ( pODMUnRegisterApp = (TODMUnRegisterApp)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMUnRegisterApp")).pData)) == NULL ) return sal_False; if ( ( pODMSelectDoc = (TODMSelectDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDoc")).pData)) == NULL ) return sal_False; if ( ( pODMOpenDoc = (TODMOpenDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMOpenDoc")).pData)) == NULL ) return sal_False; if ( ( pODMSaveDoc = (TODMSaveDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDoc")).pData)) == NULL ) return sal_False; if ( ( pODMCloseDoc = (TODMCloseDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDoc")).pData)) == NULL ) return sal_False; if ( ( pODMNewDoc = (TODMNewDoc)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMNewDoc")).pData)) == NULL ) return sal_False; if ( ( pODMSaveAs = (TODMSaveAs)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAs")).pData)) == NULL ) return sal_False; if ( ( pODMActivate = (TODMActivate)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMActivate")).pData)) == NULL ) return sal_False; if ( ( pODMGetDocInfo = (TODMGetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocInfo")).pData)) == NULL ) return sal_False; if ( ( pODMSetDocInfo = (TODMSetDocInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocInfo")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMSInfo = (TODMGetDMSInfo)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSInfo")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMSCount = (TODMGetDMSCount)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSCount")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMSList = (TODMGetDMSList)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMSList")).pData)) == NULL ) return sal_False; if ( ( pODMGetDMS = (TODMGetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDMS")).pData)) == NULL ) return sal_False; if ( ( pODMSetDMS = (TODMSetDMS)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDMS")).pData)) == NULL ) return sal_False; if ( ( pODMQueryExecute = (TODMQueryExecute)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryExecute")).pData)) == NULL ) return sal_False; if ( ( pODMQueryGetResults = (TODMQueryGetResults)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryGetResults")).pData)) == NULL ) return sal_False; if ( ( pODMQueryClose = (TODMQueryClose)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryClose")).pData)) == NULL ) return sal_False; if ( ( pODMCloseDocEx = (TODMCloseDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMCloseDocEx")).pData)) == NULL ) return sal_False; if ( ( pODMSaveAsEx = (TODMSaveAsEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveAsEx")).pData)) == NULL ) return sal_False; if ( ( pODMSaveDocEx = (TODMSaveDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSaveDocEx")).pData)) == NULL ) return sal_False; if ( ( pODMSelectDocEx = (TODMSelectDocEx)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSelectDocEx")).pData)) == NULL ) return sal_False; if ( ( pODMQueryCapability = (TODMQueryCapability)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMQueryCapability")).pData)) == NULL ) return sal_False; if ( ( pODMSetDocEvent = (TODMSetDocEvent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocEvent")).pData)) == NULL ) return sal_False; if ( ( pODMGetAlternateContent = (TODMGetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetAlternateContent")).pData)) == NULL ) return sal_False; if ( ( pODMSetAlternateContent = (TODMSetAlternateContent)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetAlternateContent")).pData)) == NULL ) return sal_False; if ( ( pODMGetDocRelation = (TODMGetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMGetDocRelation")).pData)) == NULL ) return sal_False; if ( ( pODMSetDocRelation = (TODMSetDocRelation)osl_getSymbol(pODMA,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ODMSetDocRelation")).pData)) == NULL ) return sal_False; return sal_True; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Improve the Windows code a bit
Improve the Windows code a bit
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
074ce33290016ced9a98083f26fc97362fb55689
unittests/Support/LocaleTest.cpp
unittests/Support/LocaleTest.cpp
//===- unittests/Support/LocaleTest.cpp - Locale.h tests ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Locale.h" #include "gtest/gtest.h" namespace llvm { namespace sys { namespace locale { namespace { // FIXME: WIN32 implementation is incorrect. We should consider using the one // from LocaleGeneric.inc for WIN32. #ifndef _WIN32 TEST(Locale, columnWidth) { EXPECT_EQ(0, columnWidth("")); EXPECT_EQ(1, columnWidth(" ")); EXPECT_EQ(1, columnWidth("a")); EXPECT_EQ(1, columnWidth("~")); EXPECT_EQ(6, columnWidth("abcdef")); EXPECT_EQ(-1, columnWidth("\x01")); EXPECT_EQ(-1, columnWidth("aaaaaaaaaa\x01")); EXPECT_EQ(-1, columnWidth("\342\200\213")); // 200B ZERO WIDTH SPACE EXPECT_EQ(0, columnWidth("\314\200")); // 0300 COMBINING GRAVE ACCENT EXPECT_EQ(1, columnWidth("\340\270\201")); // 0E01 THAI CHARACTER KO KAI EXPECT_EQ(2, columnWidth("\344\270\200")); // CJK UNIFIED IDEOGRAPH-4E00 EXPECT_EQ(4, columnWidth("\344\270\200\344\270\200")); EXPECT_EQ(3, columnWidth("q\344\270\200")); EXPECT_EQ(3, columnWidth("\314\200\340\270\201\344\270\200")); // FIXME: MacOS implementation of columnWidth seems to not handle incorrect // UTF-8 sequences. #ifndef __MACOSX__ // Invalid UTF-8 strings, columnWidth should error out. EXPECT_EQ(-2, columnWidth("\344")); EXPECT_EQ(-2, columnWidth("\344\270")); EXPECT_EQ(-2, columnWidth("\344\270\033")); EXPECT_EQ(-2, columnWidth("\344\270\300")); EXPECT_EQ(-2, columnWidth("\377\366\355")); EXPECT_EQ(-2, columnWidth("qwer\344")); EXPECT_EQ(-2, columnWidth("qwer\344\270")); EXPECT_EQ(-2, columnWidth("qwer\344\270\033")); EXPECT_EQ(-2, columnWidth("qwer\344\270\300")); EXPECT_EQ(-2, columnWidth("qwer\377\366\355")); // UTF-8 sequences longer than 4 bytes correspond to unallocated Unicode // characters. EXPECT_EQ(-2, columnWidth("\370\200\200\200\200")); // U+200000 EXPECT_EQ(-2, columnWidth("\374\200\200\200\200\200")); // U+4000000 #endif // __MACOSX__ } TEST(Locale, isPrint) { EXPECT_EQ(false, isPrint(0)); // <control-0000>-<control-001F> EXPECT_EQ(false, isPrint(0x01)); EXPECT_EQ(false, isPrint(0x1F)); EXPECT_EQ(true, isPrint(' ')); EXPECT_EQ(true, isPrint('A')); EXPECT_EQ(true, isPrint('~')); EXPECT_EQ(false, isPrint(0x7F)); // <control-007F>..<control-009F> EXPECT_EQ(false, isPrint(0x90)); EXPECT_EQ(false, isPrint(0x9F)); EXPECT_EQ(true, isPrint(0xAC)); // FIXME: Figure out if we want to treat SOFT HYPHEN as printable character. #ifndef __MACOSX__ EXPECT_EQ(false, isPrint(0xAD)); // SOFT HYPHEN #endif // __MACOSX__ EXPECT_EQ(true, isPrint(0xAE)); // MacOS implementation doesn't think it's printable. #ifndef __MACOSX__ EXPECT_EQ(true, isPrint(0x0377)); // GREEK SMALL LETTER PAMPHYLIAN DIGAMMA #endif // __MACOSX__ EXPECT_EQ(false, isPrint(0x0378)); // <reserved-0378>..<reserved-0379> EXPECT_EQ(false, isPrint(0x0600)); // ARABIC NUMBER SIGN EXPECT_EQ(false, isPrint(0x1FFFF)); // <reserved-1F774>..<noncharacter-1FFFF> EXPECT_EQ(true, isPrint(0x20000)); // CJK UNIFIED IDEOGRAPH-20000 EXPECT_EQ(false, isPrint(0x10FFFF)); // noncharacter } #endif // _WIN32 } // namespace } // namespace locale } // namespace sys } // namespace llvm
//===- unittests/Support/LocaleTest.cpp - Locale.h tests ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Locale.h" #include "gtest/gtest.h" namespace llvm { namespace sys { namespace locale { namespace { // FIXME: WIN32 implementation is incorrect. We should consider using the one // from LocaleGeneric.inc for WIN32. #ifndef _WIN32 TEST(Locale, columnWidth) { EXPECT_EQ(0, columnWidth("")); EXPECT_EQ(1, columnWidth(" ")); EXPECT_EQ(1, columnWidth("a")); EXPECT_EQ(1, columnWidth("~")); EXPECT_EQ(6, columnWidth("abcdef")); EXPECT_EQ(-1, columnWidth("\x01")); EXPECT_EQ(-1, columnWidth("aaaaaaaaaa\x01")); EXPECT_EQ(-1, columnWidth("\342\200\213")); // 200B ZERO WIDTH SPACE EXPECT_EQ(0, columnWidth("\314\200")); // 0300 COMBINING GRAVE ACCENT EXPECT_EQ(1, columnWidth("\340\270\201")); // 0E01 THAI CHARACTER KO KAI EXPECT_EQ(2, columnWidth("\344\270\200")); // CJK UNIFIED IDEOGRAPH-4E00 EXPECT_EQ(4, columnWidth("\344\270\200\344\270\200")); EXPECT_EQ(3, columnWidth("q\344\270\200")); EXPECT_EQ(3, columnWidth("\314\200\340\270\201\344\270\200")); // FIXME: MacOS implementation of columnWidth seems to not handle incorrect // UTF-8 sequences. #ifndef __APPLE__ // Invalid UTF-8 strings, columnWidth should error out. EXPECT_EQ(-2, columnWidth("\344")); EXPECT_EQ(-2, columnWidth("\344\270")); EXPECT_EQ(-2, columnWidth("\344\270\033")); EXPECT_EQ(-2, columnWidth("\344\270\300")); EXPECT_EQ(-2, columnWidth("\377\366\355")); EXPECT_EQ(-2, columnWidth("qwer\344")); EXPECT_EQ(-2, columnWidth("qwer\344\270")); EXPECT_EQ(-2, columnWidth("qwer\344\270\033")); EXPECT_EQ(-2, columnWidth("qwer\344\270\300")); EXPECT_EQ(-2, columnWidth("qwer\377\366\355")); // UTF-8 sequences longer than 4 bytes correspond to unallocated Unicode // characters. EXPECT_EQ(-2, columnWidth("\370\200\200\200\200")); // U+200000 EXPECT_EQ(-2, columnWidth("\374\200\200\200\200\200")); // U+4000000 #endif // __APPLE__ } TEST(Locale, isPrint) { EXPECT_EQ(false, isPrint(0)); // <control-0000>-<control-001F> EXPECT_EQ(false, isPrint(0x01)); EXPECT_EQ(false, isPrint(0x1F)); EXPECT_EQ(true, isPrint(' ')); EXPECT_EQ(true, isPrint('A')); EXPECT_EQ(true, isPrint('~')); EXPECT_EQ(false, isPrint(0x7F)); // <control-007F>..<control-009F> EXPECT_EQ(false, isPrint(0x90)); EXPECT_EQ(false, isPrint(0x9F)); EXPECT_EQ(true, isPrint(0xAC)); // FIXME: Figure out if we want to treat SOFT HYPHEN as printable character. #ifndef __APPLE__ EXPECT_EQ(false, isPrint(0xAD)); // SOFT HYPHEN #endif // __APPLE__ EXPECT_EQ(true, isPrint(0xAE)); // MacOS implementation doesn't think it's printable. #ifndef __APPLE__ EXPECT_EQ(true, isPrint(0x0377)); // GREEK SMALL LETTER PAMPHYLIAN DIGAMMA #endif // __APPLE__ EXPECT_EQ(false, isPrint(0x0378)); // <reserved-0378>..<reserved-0379> EXPECT_EQ(false, isPrint(0x0600)); // ARABIC NUMBER SIGN EXPECT_EQ(false, isPrint(0x1FFFF)); // <reserved-1F774>..<noncharacter-1FFFF> EXPECT_EQ(true, isPrint(0x20000)); // CJK UNIFIED IDEOGRAPH-20000 EXPECT_EQ(false, isPrint(0x10FFFF)); // noncharacter } #endif // _WIN32 } // namespace } // namespace locale } // namespace sys } // namespace llvm
Use correct platform detection macro: __MACOSX__ -> __APPLE__
Use correct platform detection macro: __MACOSX__ -> __APPLE__ git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@187847 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm
7b9fee4bc9640c9d18d7cfa4240608fd93eb5a83
urbackupserver/server_status.cpp
urbackupserver/server_status.cpp
/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #ifndef CLIENT_ONLY #include "server_status.h" #include "../Interface/Server.h" #include "action_header.h" #include <time.h> IMutex *ServerStatus::mutex=NULL; std::map<std::wstring, SStatus> ServerStatus::status; unsigned int ServerStatus::last_status_update; const unsigned int inactive_time_const=30*60*1000; void ServerStatus::init_mutex(void) { mutex=Server->createMutex(); last_status_update=Server->getTimeMS(); } void ServerStatus::destroy_mutex(void) { Server->destroy(mutex); } void ServerStatus::setServerStatus(const SStatus &pStatus, bool setactive) { IScopedLock lock(mutex); SStatus *s=&status[pStatus.client]; s->hashqueuesize=pStatus.hashqueuesize; s->prepare_hashqueuesize=pStatus.prepare_hashqueuesize; s->starttime=pStatus.starttime; s->pcdone=pStatus.pcdone; s->has_status=true; s->statusaction=pStatus.statusaction; s->clientid=pStatus.clientid; if(setactive) { last_status_update=Server->getTimeMS(); } } void ServerStatus::updateActive(void) { IScopedLock lock(mutex); last_status_update=Server->getTimeMS(); } void ServerStatus::setOnline(const std::wstring &clientname, bool bonline) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; if(bonline) { *s=SStatus(); } s->online=bonline; s->client=clientname; s->done=false; s->has_status=true; s->r_online=bonline; if(bonline) { last_status_update=Server->getTimeMS(); } } void ServerStatus::setROnline(const std::wstring &clientname, bool bonline) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->r_online=bonline; if(bonline) { last_status_update=Server->getTimeMS(); } } void ServerStatus::setDone(const std::wstring &clientname, bool bdone) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->done=bdone; } void ServerStatus::setIP(const std::wstring &clientname, unsigned int ip) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->ip_addr=ip; } void ServerStatus::setWrongIdent(const std::wstring &clientname, bool b) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->wrong_ident=b; } void ServerStatus::setTooManyClients(const std::wstring &clientname, bool b) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->too_many_clients=b; } void ServerStatus::setCommPipe(const std::wstring &clientname, IPipe *p) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->comm_pipe=p; } void ServerStatus::stopBackup(const std::wstring &clientname, bool b) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->stop_backup=b; } bool ServerStatus::isBackupStopped(const std::wstring &clientname) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; return s->stop_backup; } std::vector<SStatus> ServerStatus::getStatus(void) { IScopedLock lock(mutex); std::vector<SStatus> ret; for(std::map<std::wstring, SStatus>::iterator it=status.begin();it!=status.end();++it) { ret.push_back(it->second); } return ret; } SStatus ServerStatus::getStatus(const std::wstring &clientname) { IScopedLock lock(mutex); std::map<std::wstring, SStatus>::iterator iter=status.find(clientname); if(iter!=status.end()) return iter->second; else return SStatus(); } bool ServerStatus::isActive(void) { IScopedLock lock(mutex); if( Server->getTimeMS()-last_status_update>inactive_time_const) { return false; } else { return true; } } ACTION_IMPL(server_status) { ITemplate *tmpl=Server->createTemplate("urbackup/status.htm"); std::vector<SStatus> status=ServerStatus::getStatus(); tmpl->getTable(L"CLIENTS"); for(size_t i=0;i<status.size();++i) { if(status[i].done==false) { ITable *tab=tmpl->getTable(L"CLIENTS."+convert(i)); tab->addString(L"NAME", status[i].client ); if(status[i].has_status) { tab->addString(L"PCDONE", convert(status[i].pcdone) ); tab->addString(L"HASHQUEUESIZE", convert(status[i].hashqueuesize) ); tab->addString(L"HASHQUEUE_PREPARE", convert(status[i].prepare_hashqueuesize) ); tab->addString(L"ONLINE", convert(status[i].online) ); time_t tt=(time_t)(time(0)-((Server->getTimeMS()-status[i].starttime)/1000)); #ifdef _WIN32 struct tm ttm; localtime_s(&ttm, &tt); char buf[1000]; strftime(buf, 1000, "%d.%m.%Y %H:%M", &ttm); #else struct tm *ttm=localtime(&tt); char buf[1000]; strftime(buf, 1000, "%d.%m.%Y %H:%M", ttm); #endif tab->addString(L"STARTTIME", widen((std::string)buf) ); tab->addString(L"DONE", convert(status[i].done) ); std::wstring action; switch(status[i].statusaction) { case sa_none: action=L"none"; break; case sa_incr_file: action=L"incr_file"; break; case sa_full_file: action=L"full_file"; break; case sa_incr_image: action=L"incr_image"; break; case sa_full_image: action=L"full_image"; break; } tab->addString(L"ACTION", action); } else { tab->addString(L"PCDONE", L"&nbsp;"); tab->addString(L"HASHQUEUESIZE", L"&nbsp;"); tab->addString(L"HASHQUEUE_PREPARE", L"&nbsp;"); tab->addString(L"ONLINE", convert(status[i].online)); tab->addString(L"STARTTIME", L"&nbsp;"); tab->addString(L"DONE", L"&nbsp;"); tab->addString(L"ACTION", L"&nbsp;"); } } } Server->Write(tid, tmpl->getData()); Server->destroy(tmpl); } #endif //CLIENT_ONLY
/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #ifndef CLIENT_ONLY #include "server_status.h" #include "../Interface/Server.h" #include "action_header.h" #include <time.h> IMutex *ServerStatus::mutex=NULL; std::map<std::wstring, SStatus> ServerStatus::status; unsigned int ServerStatus::last_status_update; const unsigned int inactive_time_const=30*60*1000; void ServerStatus::init_mutex(void) { mutex=Server->createMutex(); last_status_update=Server->getTimeMS(); } void ServerStatus::destroy_mutex(void) { Server->destroy(mutex); } void ServerStatus::setServerStatus(const SStatus &pStatus, bool setactive) { IScopedLock lock(mutex); SStatus *s=&status[pStatus.client]; s->hashqueuesize=pStatus.hashqueuesize; s->prepare_hashqueuesize=pStatus.prepare_hashqueuesize; s->starttime=pStatus.starttime; s->pcdone=pStatus.pcdone; s->has_status=true; s->statusaction=pStatus.statusaction; s->clientid=pStatus.clientid; if(setactive) { last_status_update=Server->getTimeMS(); } } void ServerStatus::updateActive(void) { IScopedLock lock(mutex); last_status_update=Server->getTimeMS(); } void ServerStatus::setOnline(const std::wstring &clientname, bool bonline) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; if(bonline) { *s=SStatus(); } s->online=bonline; s->client=clientname; s->done=false; s->has_status=true; s->r_online=bonline; if(bonline) { last_status_update=Server->getTimeMS(); } } void ServerStatus::setROnline(const std::wstring &clientname, bool bonline) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->r_online=bonline; if(bonline) { last_status_update=Server->getTimeMS(); } } void ServerStatus::setDone(const std::wstring &clientname, bool bdone) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->done=bdone; } void ServerStatus::setIP(const std::wstring &clientname, unsigned int ip) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->ip_addr=ip; } void ServerStatus::setWrongIdent(const std::wstring &clientname, bool b) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->wrong_ident=b; } void ServerStatus::setTooManyClients(const std::wstring &clientname, bool b) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->too_many_clients=b; } void ServerStatus::setCommPipe(const std::wstring &clientname, IPipe *p) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->comm_pipe=p; } void ServerStatus::stopBackup(const std::wstring &clientname, bool b) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; s->stop_backup=b; } bool ServerStatus::isBackupStopped(const std::wstring &clientname) { IScopedLock lock(mutex); SStatus *s=&status[clientname]; return s->stop_backup; } std::vector<SStatus> ServerStatus::getStatus(void) { IScopedLock lock(mutex); std::vector<SStatus> ret; for(std::map<std::wstring, SStatus>::iterator it=status.begin();it!=status.end();++it) { ret.push_back(it->second); } return ret; } SStatus ServerStatus::getStatus(const std::wstring &clientname) { IScopedLock lock(mutex); std::map<std::wstring, SStatus>::iterator iter=status.find(clientname); if(iter!=status.end()) return iter->second; else return SStatus(); } bool ServerStatus::isActive(void) { IScopedLock lock(mutex); if( Server->getTimeMS()-last_status_update>inactive_time_const) { return false; } else { return true; } } ACTION_IMPL(server_status) { #ifndef _DEBUG Server->Write(tid, "Forbidden"); #else ITemplate *tmpl=Server->createTemplate("urbackup/status.htm"); std::vector<SStatus> status=ServerStatus::getStatus(); tmpl->getTable(L"CLIENTS"); for(size_t i=0;i<status.size();++i) { if(status[i].done==false) { ITable *tab=tmpl->getTable(L"CLIENTS."+convert(i)); tab->addString(L"NAME", status[i].client ); if(status[i].has_status) { tab->addString(L"PCDONE", convert(status[i].pcdone) ); tab->addString(L"HASHQUEUESIZE", convert(status[i].hashqueuesize) ); tab->addString(L"HASHQUEUE_PREPARE", convert(status[i].prepare_hashqueuesize) ); tab->addString(L"ONLINE", convert(status[i].online) ); time_t tt=(time_t)(time(0)-((Server->getTimeMS()-status[i].starttime)/1000)); #ifdef _WIN32 struct tm ttm; localtime_s(&ttm, &tt); char buf[1000]; strftime(buf, 1000, "%d.%m.%Y %H:%M", &ttm); #else struct tm *ttm=localtime(&tt); char buf[1000]; strftime(buf, 1000, "%d.%m.%Y %H:%M", ttm); #endif tab->addString(L"STARTTIME", widen((std::string)buf) ); tab->addString(L"DONE", convert(status[i].done) ); std::wstring action; switch(status[i].statusaction) { case sa_none: action=L"none"; break; case sa_incr_file: action=L"incr_file"; break; case sa_full_file: action=L"full_file"; break; case sa_incr_image: action=L"incr_image"; break; case sa_full_image: action=L"full_image"; break; } tab->addString(L"ACTION", action); } else { tab->addString(L"PCDONE", L"&nbsp;"); tab->addString(L"HASHQUEUESIZE", L"&nbsp;"); tab->addString(L"HASHQUEUE_PREPARE", L"&nbsp;"); tab->addString(L"ONLINE", convert(status[i].online)); tab->addString(L"STARTTIME", L"&nbsp;"); tab->addString(L"DONE", L"&nbsp;"); tab->addString(L"ACTION", L"&nbsp;"); } } } Server->Write(tid, tmpl->getData()); Server->destroy(tmpl); #endif } #endif //CLIENT_ONLY
Remove server_status for non-debug builds
Remove server_status for non-debug builds
C++
agpl-3.0
uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend
da07dfadaf9b8535f8e288cb8005fec84e658ff3
src/core/kext/RemapFunc/common/DependingPressingPeriodKeyToKey.cpp
src/core/kext/RemapFunc/common/DependingPressingPeriodKeyToKey.cpp
#include <IOKit/IOLib.h> #include "Config.hpp" #include "DependingPressingPeriodKeyToKey.hpp" #include "IOLogWrapper.hpp" #include "KeyboardRepeat.hpp" #include "RemapClass.hpp" namespace org_pqrs_Karabiner { namespace RemapFunc { TimerWrapper DependingPressingPeriodKeyToKey::fire_timer_; DependingPressingPeriodKeyToKey* DependingPressingPeriodKeyToKey::target_ = nullptr; DependingPressingPeriodKeyToKey::PeriodMS::PeriodMS(void) : mode_(Mode::NONE) { for (size_t m = 0; m < Mode::__END__; ++m) { for (size_t t = 0; t < Type::__END__; ++t) { overwritten_value_[m][t] = -1; } } } void DependingPressingPeriodKeyToKey::PeriodMS::set(PeriodMS::Mode::Value newval) { mode_ = newval; } unsigned int DependingPressingPeriodKeyToKey::PeriodMS::get(PeriodMS::Type::Value type) { if (overwritten_value_[mode_][type] >= 0) { return overwritten_value_[mode_][type]; } switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return Config::get_holdingkeytokey_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return 0; case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return Config::get_keyoverlaidmodifier_initial_wait(); case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::get\n"); return 0; } return 0; } bool DependingPressingPeriodKeyToKey::PeriodMS::enabled(PeriodMS::Type::Value type) { switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return false; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return true; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::enabled\n"); return false; } return false; } // ====================================================================== void DependingPressingPeriodKeyToKey::static_initialize(IOWorkLoop& workloop) { fire_timer_.initialize(&workloop, nullptr, DependingPressingPeriodKeyToKey::fire_timer_callback); } void DependingPressingPeriodKeyToKey::static_terminate(void) { fire_timer_.terminate(); } DependingPressingPeriodKeyToKey::DependingPressingPeriodKeyToKey(RemapFunc::RemapFuncBase* owner, AutogenId autogenId) : owner_(owner), active_(false), periodtype_(PeriodType::NONE), keytokey_{{autogenId}, {autogenId}, {autogenId}, {autogenId}}, beforeAfterKeys_(autogenId), keyboardRepeatID_(0), lastPhysicalEventType_(PhysicalEventType::DOWN), interruptibleByScrollWheel_(true) { for (size_t i = 0; i < KeyToKeyType::END_; ++i) { keytokey_[i].add(KeyCode::VK_PSEUDO_KEY); } beforeAfterKeys_.add(KeyCode::VK_PSEUDO_KEY); } DependingPressingPeriodKeyToKey::~DependingPressingPeriodKeyToKey(void) { if (target_ == this) { fire_timer_.cancelTimeout(); target_ = nullptr; } } void DependingPressingPeriodKeyToKey::add(KeyToKeyType::Value type, AddDataType datatype, AddValue newval) { if (type == KeyToKeyType::END_) return; if (datatype == BRIDGE_DATATYPE_OPTION && Option::UNINTERRUPTIBLE_BY_SCROLL_WHEEL == Option(newval)) { interruptibleByScrollWheel_ = false; } else { keytokey_[type].add(datatype, newval); } } void DependingPressingPeriodKeyToKey::prepare(RemapParams& remapParams) { // Params_ScrollWheelEventCallback { auto params = remapParams.paramsBase.get_Params_ScrollWheelEventCallback(); if (params) { if (interruptibleByScrollWheel_) { dokeydown(remapParams); } } } // Params_KeyboardEventCallBack, Params_KeyboardSpecialEventCallback, Params_RelativePointerEventCallback { bool iskeydown = false; if (remapParams.paramsBase.iskeydown(iskeydown)) { if (iskeydown) { // another key is pressed. dokeydown(remapParams); } } } } bool DependingPressingPeriodKeyToKey::remap(RemapParams& remapParams) { // Params_KeyboardEventCallBack, Params_KeyboardSpecialEventCallback, Params_RelativePointerEventCallback { bool iskeydown = false; if (remapParams.paramsBase.iskeydown(iskeydown)) { if (remapParams.isremapped || !fromEvent_.changePressingState(remapParams.paramsBase, FlagStatus::globalFlagStatus(), fromModifierFlags_)) { return false; } remapParams.isremapped = true; lastPhysicalEventType_ = remapParams.physicalEventType; if (iskeydown) { target_ = this; active_ = true; periodtype_ = PeriodType::NONE; FlagStatus::globalFlagStatus().decrease(fromEvent_.getModifierFlag()); FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, remapParams.physicalEventType); // We need save FlagStatus at keydown. // For example, "Change Space to Shift_L" is enabled, // // (1) Control_L down // (2) Space down // (3) Control_L up // (4) Space up -> We should send Control_L+Space here. // // At (4), Control_L is not presssed. // We should send Control_L+Space at (4) because user pressed Space with Control_L at (2). // // Therefore, we need to save FlagStatus at (2). // And restore it at (4). // flagStatusWhenKeyPressed_ = FlagStatus::globalFlagStatus(); unsigned int ms = periodMS_.get(PeriodMS::Type::SHORT_PERIOD); if (ms == 0) { fire_timer_callback(nullptr, nullptr); } else { fire_timer_.setTimeoutMS(ms); } RemapClassManager::registerPrepareTargetItem(owner_); // Stop modifier flag events until normal key event is happen or physical key down event is happen // in order to reduce unnecessary modifier events. // // For example, we consider the following autogens: // // <autogen> // __KeyOverlaidModifier__ // KeyCode::COMMAND_L, // KeyCode::CONTROL_L, // KeyCode::ESCAPE, // </autogen> // <autogen> // __KeyOverlaidModifier__ // KeyCode::SPACE, // KeyCode::SHIFT_L, // KeyCode::SPACE, // </autogen> // // * Change the left command key to control key. // * Change the space key to shift key. // * Send an escape key event when the left command key is pressed alone, // * Send a space key event when the space key is pressed alone. // // When we press keys by this order. // #1 Press COMMAND_L. // #2 Press SPACE. // #3 Release COMMAND_L. // #4 Release SPACE. // // The result is control-space at #4. // // If we does not stop modifier events, CONTROL_L events are sent at #3 and #4. // // #1 -> CONTROL_L down. // #2 -> SHIFT_L down. // #3 -> CONTROL_L up. // #4 -> CONTROL_L down, SHIFT_L up, SPACE down, SPACE up. // // To reduce these events, we ignore modifier events at physical key up. // // #1 -> CONTROL_L down // #2 -> SHIFT_L down. // #3 -> Do nothing. // #4 -> SHIFT_L up, SPACE down, SPACE up. // EventOutputQueue::FireModifiers::setIgnorePhysicalUpEvent(true); } else { FlagStatus::globalFlagStatus().increase(fromEvent_.getModifierFlag()); dokeydown(remapParams); dokeyup(); FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::UP, remapParams.physicalEventType); RemapClassManager::unregisterPrepareTargetItem(owner_); } return true; } } return false; } void DependingPressingPeriodKeyToKey::dokeydown(RemapParams& remapParams) { if (!active_) return; active_ = false; if (target_ == this) { fire_timer_.cancelTimeout(); } switch (periodtype_) { case PeriodType::NONE: { periodtype_ = PeriodType::SHORT_PERIOD; { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), flagStatusWhenKeyPressed_); keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, remapParams.physicalEventType); // Call prepare in order to cancel delayed action. // // For example: // 1. Enable remap.samples_keytokey_delayed_action_3 in samples.xml. // 2. Type return. // 3. Type space. // 4. It should be changed to 1,space. // // If we don't call prepare, the delayed action will be registered when we type the space key // and it will not be canceled. // The result becomes `space,1`. (`1` is entered by delayed action after space key.) // // Therefore we need to call prepare to preserve events order. keytokey_[KeyToKeyType::SHORT_PERIOD].prepare(remapParams); } break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } void DependingPressingPeriodKeyToKey::dokeyup(void) { switch (periodtype_) { case PeriodType::SHORT_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); break; } case PeriodType::LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); // ---------------------------------------- // handle PRESSING_TARGET_KEY_ONLY if (periodMS_.enabled(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { if (!eventWatcherTarget_.isAnyEventHappen() && ic_.getmillisec() < periodMS_.get(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), flagStatusWhenKeyPressed_); keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, lastPhysicalEventType_); keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); } } break; } case PeriodType::LONG_LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); break; } case PeriodType::NONE: // do nothing break; } eventWatcherTarget_.unobserve(); } void DependingPressingPeriodKeyToKey::fire_timer_callback(OSObject* /* owner */, IOTimerEventSource* /* sender */) { if (!target_) return; switch (target_->periodtype_) { case PeriodType::NONE: { target_->periodtype_ = PeriodType::LONG_PERIOD; { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), target_->flagStatusWhenKeyPressed_); (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, target_->lastPhysicalEventType_); } (target_->eventWatcherTarget_).observe(); (target_->ic_).begin(); if (target_->periodMS_.enabled(PeriodMS::Type::LONG_LONG_PERIOD)) { KeyboardRepeat::cancel(); target_->keyboardRepeatID_ = KeyboardRepeat::getID(); fire_timer_.setTimeoutMS(target_->periodMS_.get(PeriodMS::Type::LONG_LONG_PERIOD)); } break; } case PeriodType::LONG_PERIOD: { // If keyboard repeat cancellation occured while pressing LONG_PERIOD key, // we cancel LONG_LONG_PERIOD event. bool isKeyboardRepeatCanceled = (target_->keyboardRepeatID_ != KeyboardRepeat::getID()); (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::UP, target_->lastPhysicalEventType_); if (isKeyboardRepeatCanceled) { target_->periodtype_ = PeriodType::NONE; } else { target_->periodtype_ = PeriodType::LONG_LONG_PERIOD; { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), target_->flagStatusWhenKeyPressed_); (target_->keytokey_[KeyToKeyType::LONG_LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, target_->lastPhysicalEventType_); } } break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } } }
#include <IOKit/IOLib.h> #include "Config.hpp" #include "DependingPressingPeriodKeyToKey.hpp" #include "IOLogWrapper.hpp" #include "KeyboardRepeat.hpp" #include "RemapClass.hpp" namespace org_pqrs_Karabiner { namespace RemapFunc { TimerWrapper DependingPressingPeriodKeyToKey::fire_timer_; DependingPressingPeriodKeyToKey* DependingPressingPeriodKeyToKey::target_ = nullptr; DependingPressingPeriodKeyToKey::PeriodMS::PeriodMS(void) : mode_(Mode::NONE) { for (size_t m = 0; m < Mode::__END__; ++m) { for (size_t t = 0; t < Type::__END__; ++t) { overwritten_value_[m][t] = -1; } } } void DependingPressingPeriodKeyToKey::PeriodMS::set(PeriodMS::Mode::Value newval) { mode_ = newval; } unsigned int DependingPressingPeriodKeyToKey::PeriodMS::get(PeriodMS::Type::Value type) { if (overwritten_value_[mode_][type] >= 0) { return overwritten_value_[mode_][type]; } switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return Config::get_holdingkeytokey_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return 0; case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return 0; case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return Config::get_keyoverlaidmodifier_initial_modifier_wait(); case Type::LONG_LONG_PERIOD: return Config::get_keyoverlaidmodifier_initial_wait(); case Type::PRESSING_TARGET_KEY_ONLY: return Config::get_keyoverlaidmodifier_timeout(); case Type::__END__: return 0; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::get\n"); return 0; } return 0; } bool DependingPressingPeriodKeyToKey::PeriodMS::enabled(PeriodMS::Type::Value type) { switch (mode_) { case Mode::HOLDING_KEY_TO_KEY: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return false; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return false; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::KEY_OVERLAID_MODIFIER_WITH_REPEAT: switch (type) { case Type::SHORT_PERIOD: return true; case Type::LONG_LONG_PERIOD: return true; case Type::PRESSING_TARGET_KEY_ONLY: return true; case Type::__END__: return false; } case Mode::NONE: case Mode::__END__: IOLOG_ERROR("Invalid DependingPressingPeriodKeyToKey::PeriodMS::enabled\n"); return false; } return false; } // ====================================================================== void DependingPressingPeriodKeyToKey::static_initialize(IOWorkLoop& workloop) { fire_timer_.initialize(&workloop, nullptr, DependingPressingPeriodKeyToKey::fire_timer_callback); } void DependingPressingPeriodKeyToKey::static_terminate(void) { fire_timer_.terminate(); } DependingPressingPeriodKeyToKey::DependingPressingPeriodKeyToKey(RemapFunc::RemapFuncBase* owner, AutogenId autogenId) : owner_(owner), active_(false), periodtype_(PeriodType::NONE), keytokey_{{autogenId}, {autogenId}, {autogenId}, {autogenId}}, beforeAfterKeys_(autogenId), keyboardRepeatID_(0), lastPhysicalEventType_(PhysicalEventType::DOWN), interruptibleByScrollWheel_(true) { for (size_t i = 0; i < KeyToKeyType::END_; ++i) { keytokey_[i].add(KeyCode::VK_PSEUDO_KEY); } beforeAfterKeys_.add(KeyCode::VK_PSEUDO_KEY); } DependingPressingPeriodKeyToKey::~DependingPressingPeriodKeyToKey(void) { if (target_ == this) { fire_timer_.cancelTimeout(); target_ = nullptr; } } void DependingPressingPeriodKeyToKey::add(KeyToKeyType::Value type, AddDataType datatype, AddValue newval) { if (type == KeyToKeyType::END_) return; if (datatype == BRIDGE_DATATYPE_OPTION && Option::UNINTERRUPTIBLE_BY_SCROLL_WHEEL == Option(newval)) { interruptibleByScrollWheel_ = false; } else { keytokey_[type].add(datatype, newval); } } void DependingPressingPeriodKeyToKey::prepare(RemapParams& remapParams) { // Params_ScrollWheelEventCallback { auto params = remapParams.paramsBase.get_Params_ScrollWheelEventCallback(); if (params) { if (interruptibleByScrollWheel_) { dokeydown(remapParams); } } } // Params_KeyboardEventCallBack, Params_KeyboardSpecialEventCallback, Params_RelativePointerEventCallback { bool iskeydown = false; if (remapParams.paramsBase.iskeydown(iskeydown)) { if (iskeydown) { // another key is pressed. dokeydown(remapParams); } } } } bool DependingPressingPeriodKeyToKey::remap(RemapParams& remapParams) { // Params_KeyboardEventCallBack, Params_KeyboardSpecialEventCallback, Params_RelativePointerEventCallback { bool iskeydown = false; if (remapParams.paramsBase.iskeydown(iskeydown)) { if (remapParams.isremapped || !fromEvent_.changePressingState(remapParams.paramsBase, FlagStatus::globalFlagStatus(), fromModifierFlags_)) { return false; } remapParams.isremapped = true; lastPhysicalEventType_ = remapParams.physicalEventType; if (iskeydown) { target_ = this; active_ = true; periodtype_ = PeriodType::NONE; FlagStatus::globalFlagStatus().decrease(fromEvent_.getModifierFlag()); FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, remapParams.physicalEventType); // We need save FlagStatus at keydown. // For example, "Change Space to Shift_L" is enabled, // // (1) Control_L down // (2) Space down // (3) Control_L up // (4) Space up -> We should send Control_L+Space here. // // At (4), Control_L is not presssed. // We should send Control_L+Space at (4) because user pressed Space with Control_L at (2). // // Therefore, we need to save FlagStatus at (2). // And restore it at (4). // flagStatusWhenKeyPressed_ = FlagStatus::globalFlagStatus(); unsigned int ms = periodMS_.get(PeriodMS::Type::SHORT_PERIOD); if (ms == 0) { fire_timer_callback(nullptr, nullptr); } else { fire_timer_.setTimeoutMS(ms); } RemapClassManager::registerPrepareTargetItem(owner_); // Stop modifier flag events until normal key event is happen or physical key down event is happen // in order to reduce unnecessary modifier events. // // For example, we consider the following autogens: // // <autogen> // __KeyOverlaidModifier__ // KeyCode::COMMAND_L, // KeyCode::CONTROL_L, // KeyCode::ESCAPE, // </autogen> // <autogen> // __KeyOverlaidModifier__ // KeyCode::SPACE, // KeyCode::SHIFT_L, // KeyCode::SPACE, // </autogen> // // * Change the left command key to control key. // * Change the space key to shift key. // * Send an escape key event when the left command key is pressed alone, // * Send a space key event when the space key is pressed alone. // // When we press keys by this order. // #1 Press COMMAND_L. // #2 Press SPACE. // #3 Release COMMAND_L. // #4 Release SPACE. // // The result is control-space at #4. // // If we does not stop modifier events, CONTROL_L events are sent at #3 and #4. // // #1 -> CONTROL_L down. // #2 -> SHIFT_L down. // #3 -> CONTROL_L up. // #4 -> CONTROL_L down, SHIFT_L up, SPACE down, SPACE up, CONTROL_L up. // // To reduce these events, we ignore modifier events at physical key up. // // #1 -> CONTROL_L down // #2 -> SHIFT_L down. // #3 -> Do nothing. // #4 -> SHIFT_L up, SPACE down, SPACE up, CONTROL_L up. // EventOutputQueue::FireModifiers::setIgnorePhysicalUpEvent(true); } else { FlagStatus::globalFlagStatus().increase(fromEvent_.getModifierFlag()); dokeydown(remapParams); dokeyup(); FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_); beforeAfterKeys_.call_remap_with_VK_PSEUDO_KEY(EventType::UP, remapParams.physicalEventType); RemapClassManager::unregisterPrepareTargetItem(owner_); } return true; } } return false; } void DependingPressingPeriodKeyToKey::dokeydown(RemapParams& remapParams) { if (!active_) return; active_ = false; if (target_ == this) { fire_timer_.cancelTimeout(); } switch (periodtype_) { case PeriodType::NONE: { periodtype_ = PeriodType::SHORT_PERIOD; { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), flagStatusWhenKeyPressed_); keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, remapParams.physicalEventType); // Call prepare in order to cancel delayed action. // // For example: // 1. Enable remap.samples_keytokey_delayed_action_3 in samples.xml. // 2. Type return. // 3. Type space. // 4. It should be changed to 1,space. // // If we don't call prepare, the delayed action will be registered when we type the space key // and it will not be canceled. // The result becomes `space,1`. (`1` is entered by delayed action after space key.) // // Therefore we need to call prepare to preserve events order. keytokey_[KeyToKeyType::SHORT_PERIOD].prepare(remapParams); } break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } void DependingPressingPeriodKeyToKey::dokeyup(void) { switch (periodtype_) { case PeriodType::SHORT_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::SHORT_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); break; } case PeriodType::LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); // ---------------------------------------- // handle PRESSING_TARGET_KEY_ONLY if (periodMS_.enabled(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { if (!eventWatcherTarget_.isAnyEventHappen() && ic_.getmillisec() < periodMS_.get(PeriodMS::Type::PRESSING_TARGET_KEY_ONLY)) { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), flagStatusWhenKeyPressed_); keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, lastPhysicalEventType_); keytokey_[KeyToKeyType::PRESSING_TARGET_KEY_ONLY].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); } } break; } case PeriodType::LONG_LONG_PERIOD: { periodtype_ = PeriodType::NONE; keytokey_[KeyToKeyType::LONG_LONG_PERIOD].call_remap_with_VK_PSEUDO_KEY(EventType::UP, lastPhysicalEventType_); break; } case PeriodType::NONE: // do nothing break; } eventWatcherTarget_.unobserve(); } void DependingPressingPeriodKeyToKey::fire_timer_callback(OSObject* /* owner */, IOTimerEventSource* /* sender */) { if (!target_) return; switch (target_->periodtype_) { case PeriodType::NONE: { target_->periodtype_ = PeriodType::LONG_PERIOD; { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), target_->flagStatusWhenKeyPressed_); (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, target_->lastPhysicalEventType_); } (target_->eventWatcherTarget_).observe(); (target_->ic_).begin(); if (target_->periodMS_.enabled(PeriodMS::Type::LONG_LONG_PERIOD)) { KeyboardRepeat::cancel(); target_->keyboardRepeatID_ = KeyboardRepeat::getID(); fire_timer_.setTimeoutMS(target_->periodMS_.get(PeriodMS::Type::LONG_LONG_PERIOD)); } break; } case PeriodType::LONG_PERIOD: { // If keyboard repeat cancellation occured while pressing LONG_PERIOD key, // we cancel LONG_LONG_PERIOD event. bool isKeyboardRepeatCanceled = (target_->keyboardRepeatID_ != KeyboardRepeat::getID()); (target_->keytokey_[KeyToKeyType::LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::UP, target_->lastPhysicalEventType_); if (isKeyboardRepeatCanceled) { target_->periodtype_ = PeriodType::NONE; } else { target_->periodtype_ = PeriodType::LONG_LONG_PERIOD; { FlagStatus::ScopedSetter scopedSetter(FlagStatus::globalFlagStatus(), target_->flagStatusWhenKeyPressed_); (target_->keytokey_[KeyToKeyType::LONG_LONG_PERIOD]).call_remap_with_VK_PSEUDO_KEY(EventType::DOWN, target_->lastPhysicalEventType_); } } break; } case PeriodType::SHORT_PERIOD: case PeriodType::LONG_LONG_PERIOD: // do nothing break; } } } }
update comments
update comments
C++
unlicense
e-gaulue/Karabiner,astachurski/Karabiner,wataash/Karabiner,astachurski/Karabiner,wataash/Karabiner,chzyer-dev/Karabiner,e-gaulue/Karabiner,muramasa64/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,wataash/Karabiner,runarbu/Karabiner,chzyer-dev/Karabiner,miaotaizi/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,runarbu/Karabiner,tekezo/Karabiner,astachurski/Karabiner,e-gaulue/Karabiner,chzyer-dev/Karabiner,runarbu/Karabiner,tekezo/Karabiner,tekezo/Karabiner,chzyer-dev/Karabiner,astachurski/Karabiner,e-gaulue/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,runarbu/Karabiner,tekezo/Karabiner,wataash/Karabiner
faf1dd9b7e1a3687b46d37ac0f1aa50416295934
modules/crypt.cpp
modules/crypt.cpp
/* * Copyright (C) 2004-2013 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ //! @author [email protected] // // The encryption here was designed to be compatible with mircryption's CBC mode. // // TODO: // // 1) Encrypt key storage file // 2) Secure key exchange using pub/priv keys and the DH algorithm // 3) Some way of notifying the user that the current channel is in "encryption mode" verses plain text // 4) Temporarily disable a target (nick/chan) // // NOTE: This module is currently NOT intended to secure you from your shell admin. // The keys are currently stored in plain text, so anyone with access to your account (or root) can obtain them. // It is strongly suggested that you enable SSL between znc and your client otherwise the encryption stops at znc and gets sent to your client in plain text. // #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #define REQUIRESSL 1 class CCryptMod : public CModule { public: MODCONSTRUCTOR(CCryptMod) {} virtual ~CCryptMod() {} virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) { sTarget.TrimLeft("\244"); if (sMessage.Left(2) == "``") { sMessage.LeftChomp(2); return CONTINUE; } MCString::iterator it = FindNV(sTarget.AsLower()); if (it != EndNV()) { CChan* pChan = m_pNetwork->FindChan(sTarget); if (pChan) { if (!pChan->AutoClearChanBuffer()) pChan->AddBuffer(":\244" + _NAMEDFMT(m_pNetwork->GetIRCNick().GetNickMask()) + " PRIVMSG " + _NAMEDFMT(sTarget) + " :" + _NAMEDFMT(sMessage)); m_pUser->PutUser(":\244" + m_pNetwork->GetIRCNick().GetNickMask() + " PRIVMSG " + sTarget + " :" + sMessage, NULL, m_pClient); } CString sMsg = MakeIvec() + sMessage; sMsg.Encrypt(it->second); sMsg.Base64Encode(); sMsg = "+OK *" + sMsg; PutIRC("PRIVMSG " + sTarget + " :" + sMsg); return HALTCORE; } return CONTINUE; } virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) { FilterIncoming(Nick.GetNick(), Nick, sMessage); return CONTINUE; } virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { FilterIncoming(Channel.GetName(), Nick, sMessage); return CONTINUE; } void FilterIncoming(const CString& sTarget, CNick& Nick, CString& sMessage) { if (sMessage.Left(5) == "+OK *") { MCString::iterator it = FindNV(sTarget.AsLower()); if (it != EndNV()) { sMessage.LeftChomp(5); sMessage.Base64Decode(); sMessage.Decrypt(it->second); sMessage.LeftChomp(8); sMessage = sMessage.c_str(); Nick.SetNick("\244" + Nick.GetNick()); } } } virtual void OnModCommand(const CString& sCommand) { CString sCmd = sCommand.Token(0); if (sCmd.Equals("DELKEY")) { CString sTarget = sCommand.Token(1); if (!sTarget.empty()) { if (DelNV(sTarget.AsLower())) { PutModule("Target [" + sTarget + "] deleted"); } else { PutModule("Target [" + sTarget + "] not found"); } } else { PutModule("Usage DelKey <#chan|Nick>"); } } else if (sCmd.Equals("SETKEY")) { CString sTarget = sCommand.Token(1); CString sKey = sCommand.Token(2, true); // Strip "cbc:" from beginning of string incase someone pastes directly from mircryption sKey.TrimPrefix("cbc:"); if (!sKey.empty()) { SetNV(sTarget.AsLower(), sKey); PutModule("Set encryption key for [" + sTarget + "] to [" + sKey + "]"); } else { PutModule("Usage: SetKey <#chan|Nick> <Key>"); } } else if (sCmd.Equals("LISTKEYS")) { if (BeginNV() == EndNV()) { PutModule("You have no encryption keys set."); } else { CTable Table; Table.AddColumn("Target"); Table.AddColumn("Key"); for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { Table.AddRow(); Table.SetCell("Target", it->first); Table.SetCell("Key", it->second); } PutModule(Table); } } else if (sCmd.Equals("HELP")) { PutModule("Try: SetKey, DelKey, ListKeys"); } else { PutModule("Unknown command, try 'Help'"); } } CString MakeIvec() { CString sRet; time_t t; time(&t); int r = rand(); sRet.append((char*) &t, 4); sRet.append((char*) &r, 4); return sRet; } }; template<> void TModInfo<CCryptMod>(CModInfo& Info) { Info.SetWikiPage("crypt"); } NETWORKMODULEDEFS(CCryptMod, "Encryption for channel/private messages")
/* * Copyright (C) 2004-2013 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ //! @author [email protected] // // The encryption here was designed to be compatible with mircryption's CBC mode. // // TODO: // // 1) Encrypt key storage file // 2) Secure key exchange using pub/priv keys and the DH algorithm // 3) Some way of notifying the user that the current channel is in "encryption mode" verses plain text // 4) Temporarily disable a target (nick/chan) // // NOTE: This module is currently NOT intended to secure you from your shell admin. // The keys are currently stored in plain text, so anyone with access to your account (or root) can obtain them. // It is strongly suggested that you enable SSL between znc and your client otherwise the encryption stops at znc and gets sent to your client in plain text. // #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #define REQUIRESSL 1 class CCryptMod : public CModule { public: MODCONSTRUCTOR(CCryptMod) {} virtual ~CCryptMod() {} virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) { sTarget.TrimLeft("\244"); if (sMessage.Left(2) == "``") { sMessage.LeftChomp(2); return CONTINUE; } MCString::iterator it = FindNV(sTarget.AsLower()); if (it != EndNV()) { CChan* pChan = m_pNetwork->FindChan(sTarget); if (pChan) { if (!pChan->AutoClearChanBuffer()) pChan->AddBuffer(":\244" + _NAMEDFMT(m_pNetwork->GetIRCNick().GetNickMask()) + " PRIVMSG " + _NAMEDFMT(sTarget) + " :{text}", sMessage); m_pUser->PutUser(":\244" + m_pNetwork->GetIRCNick().GetNickMask() + " PRIVMSG " + sTarget + " :" + sMessage, NULL, m_pClient); } CString sMsg = MakeIvec() + sMessage; sMsg.Encrypt(it->second); sMsg.Base64Encode(); sMsg = "+OK *" + sMsg; PutIRC("PRIVMSG " + sTarget + " :" + sMsg); return HALTCORE; } return CONTINUE; } virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) { FilterIncoming(Nick.GetNick(), Nick, sMessage); return CONTINUE; } virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { FilterIncoming(Channel.GetName(), Nick, sMessage); return CONTINUE; } void FilterIncoming(const CString& sTarget, CNick& Nick, CString& sMessage) { if (sMessage.Left(5) == "+OK *") { MCString::iterator it = FindNV(sTarget.AsLower()); if (it != EndNV()) { sMessage.LeftChomp(5); sMessage.Base64Decode(); sMessage.Decrypt(it->second); sMessage.LeftChomp(8); sMessage = sMessage.c_str(); Nick.SetNick("\244" + Nick.GetNick()); } } } virtual void OnModCommand(const CString& sCommand) { CString sCmd = sCommand.Token(0); if (sCmd.Equals("DELKEY")) { CString sTarget = sCommand.Token(1); if (!sTarget.empty()) { if (DelNV(sTarget.AsLower())) { PutModule("Target [" + sTarget + "] deleted"); } else { PutModule("Target [" + sTarget + "] not found"); } } else { PutModule("Usage DelKey <#chan|Nick>"); } } else if (sCmd.Equals("SETKEY")) { CString sTarget = sCommand.Token(1); CString sKey = sCommand.Token(2, true); // Strip "cbc:" from beginning of string incase someone pastes directly from mircryption sKey.TrimPrefix("cbc:"); if (!sKey.empty()) { SetNV(sTarget.AsLower(), sKey); PutModule("Set encryption key for [" + sTarget + "] to [" + sKey + "]"); } else { PutModule("Usage: SetKey <#chan|Nick> <Key>"); } } else if (sCmd.Equals("LISTKEYS")) { if (BeginNV() == EndNV()) { PutModule("You have no encryption keys set."); } else { CTable Table; Table.AddColumn("Target"); Table.AddColumn("Key"); for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { Table.AddRow(); Table.SetCell("Target", it->first); Table.SetCell("Key", it->second); } PutModule(Table); } } else if (sCmd.Equals("HELP")) { PutModule("Try: SetKey, DelKey, ListKeys"); } else { PutModule("Unknown command, try 'Help'"); } } CString MakeIvec() { CString sRet; time_t t; time(&t); int r = rand(); sRet.append((char*) &t, 4); sRet.append((char*) &r, 4); return sRet; } }; template<> void TModInfo<CCryptMod>(CModInfo& Info) { Info.SetWikiPage("crypt"); } NETWORKMODULEDEFS(CCryptMod, "Encryption for channel/private messages")
Add time stamp to buffered messages
crypt: Add time stamp to buffered messages This is relevant when replaying the buffer on connect and brings the crypt module in sync with the normal logging functionality (which it bypasses).
C++
apache-2.0
reedloden/znc,evilnet/znc,ollie27/znc,jpnurmi/znc,jantman/znc,BtbN/znc,withinsoft/znc,Kriechi/znc,wolfy1339/znc,KielBNC/znc,znc/znc,elyscape/znc,dgw/znc,wolfy1339/znc,TuffLuck/znc,jantman/znc,ollie27/znc,TingPing/znc,reedloden/znc,znc/znc,ollie27/znc,psychon/znc,dgw/znc,DarthGandalf/znc,dgw/znc,TuffLuck/znc,GLolol/znc,DarthGandalf/znc,znc/znc,dgw/znc,jreese/znc,badloop/znc,anthonyryan1/znc,Hasimir/znc,psychon/znc,YourBNC/znc,markusj/znc,evilnet/znc,markusj/znc,DarthGandalf/znc,jpnurmi/znc,jpnurmi/znc,Adam-/znc,Mkaysi/znc,badloop/znc,Kriechi/znc,Kriechi/znc,jreese/znc,jpnurmi/znc,BtbN/znc,Zarthus/znc,jantman/znc,elyscape/znc,wolfy1339/znc,kashike/znc,anthonyryan1/znc,jreese/znc,BtbN/znc,wolfy1339/znc,jantman/znc,evilnet/znc,TingPing/znc,kashike/znc,Mkaysi/znc,jpnurmi/znc,Mikaela/znc,Phansa/znc,aarondunlap/znc,kashike/znc,Mkaysi/znc,dgw/znc,trisk/znc,YourBNC/znc,KielBNC/znc,aarondunlap/znc,jantman/znc,KiNgMaR/znc,withinsoft/znc,trisk/znc,trisk/znc,elyscape/znc,Zarthus/znc,TuffLuck/znc,KielBNC/znc,KielBNC/znc,reedloden/znc,znc/znc,trisk/znc,aarondunlap/znc,Hasimir/znc,YourBNC/znc,reedloden/znc,GLolol/znc,KiNgMaR/znc,jpnurmi/znc,KiNgMaR/znc,Adam-/znc,Phansa/znc,Kriechi/nobnc,GLolol/znc,anthonyryan1/znc,Zarthus/znc,Kriechi/znc,TingPing/znc,Mikaela/znc,Phansa/znc,TuffLuck/znc,Phansa/znc,wolfy1339/znc,Mkaysi/znc,wolfy1339/znc,Hasimir/znc,znc/znc,BtbN/znc,Mkaysi/znc,KielBNC/znc,KiNgMaR/znc,elyscape/znc,anthonyryan1/znc,Phansa/znc,badloop/znc,trisk/znc,KiNgMaR/znc,kashike/znc,Kriechi/nobnc,jreese/znc,kashike/znc,Mikaela/znc,GLolol/znc,Adam-/znc,ollie27/znc,TingPing/znc,badloop/znc,markusj/znc,anthonyryan1/znc,TuffLuck/znc,KielBNC/znc,reedloden/znc,Adam-/znc,Hasimir/znc,elyscape/znc,KiNgMaR/znc,Mikaela/znc,Mikaela/znc,Adam-/znc,Phansa/znc,jpnurmi/znc,TingPing/znc,TuffLuck/znc,aarondunlap/znc,jantman/znc,aarondunlap/znc,elyscape/znc,psychon/znc,Adam-/znc,BtbN/znc,psychon/znc,badloop/znc,Hasimir/znc,withinsoft/znc,Mikaela/znc,psychon/znc,Mikaela/znc,badloop/znc,jreese/znc,evilnet/znc,Adam-/znc,withinsoft/znc,anthonyryan1/znc,TingPing/znc,GLolol/znc,jreese/znc,markusj/znc,BtbN/znc,Zarthus/znc,markusj/znc,ollie27/znc,aarondunlap/znc,aarondunlap/znc,Mkaysi/znc,Zarthus/znc,DarthGandalf/znc,Kriechi/nobnc,TuffLuck/znc,evilnet/znc,Zarthus/znc,kashike/znc,psychon/znc,GLolol/znc,ollie27/znc,YourBNC/znc,markusj/znc,DarthGandalf/znc,withinsoft/znc,reedloden/znc,Hasimir/znc,Kriechi/znc,Hasimir/znc,badloop/znc,dgw/znc,anthonyryan1/znc,YourBNC/znc,DarthGandalf/znc,evilnet/znc,Mkaysi/znc,YourBNC/znc,trisk/znc,withinsoft/znc,Kriechi/znc,znc/znc
c110b4cb961c4d469afd8d4ec102fd5c90937afc
gui/browsable/src/RNTupleBrowseProvider.cxx
gui/browsable/src/RNTupleBrowseProvider.cxx
/************************************************************************* * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <ROOT/Browsable/RElement.hxx> #include <ROOT/Browsable/RProvider.hxx> #include <ROOT/Browsable/RLevelIter.hxx> #include <ROOT/Browsable/RItem.hxx> #include <ROOT/RNTuple.hxx> #include <ROOT/RNTupleDescriptor.hxx> #include <ROOT/RMiniFile.hxx> #include "TClass.h" #include "RFieldHolder.hxx" using namespace std::string_literals; using namespace ROOT::Experimental::Browsable; // ============================================================================================== /** \class RFieldElement \ingroup rbrowser \brief Browsing element representing of RField \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RFieldElement : public RElement { protected: std::shared_ptr<ROOT::Experimental::RNTupleReader> fNTuple; std::string fParentName; ROOT::Experimental::DescriptorId_t fFieldId; public: RFieldElement(std::shared_ptr<ROOT::Experimental::RNTupleReader> tuple, const std::string &parent_name, const ROOT::Experimental::DescriptorId_t id) : RElement(), fNTuple(tuple), fParentName(parent_name), fFieldId(id) {} virtual ~RFieldElement() = default; /** Name of RField */ std::string GetName() const override { return fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId).GetFieldName(); } /** Title of RField */ std::string GetTitle() const override { auto &fld = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId); return "RField name "s + fld.GetFieldName() + " type "s + fld.GetTypeName(); } std::unique_ptr<RLevelIter> GetChildsIter() override; /** Return class of field - for a moment using RNTuple class as dummy */ const TClass *GetClass() const { return TClass::GetClass<ROOT::Experimental::RNTuple>(); } std::unique_ptr<RHolder> GetObject() { return std::make_unique<RFieldHolder>(fNTuple, fParentName, fFieldId); } EActionKind GetDefaultAction() const override { auto range = fNTuple->GetDescriptor().GetFieldRange(fFieldId); if (range.begin() != range.end()) return kActNone; auto &field = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId); bool supported = (field.GetTypeName() == "double"s) || (field.GetTypeName() == "float"s) || (field.GetTypeName() == "int"s) || (field.GetTypeName() == "std::int32_t"s) || (field.GetTypeName() == "std::uint32_t"s) || (field.GetTypeName() == "std::string"s); if (!supported) printf("Field %s type %s not yet supported for drawing\n", field.GetFieldName().c_str(), field.GetTypeName().c_str()); return supported ? kActDraw6 : kActNone; } //bool IsCapable(EActionKind) const override; }; // ============================================================================================== /** \class RNTupleElement \ingroup rbrowser \brief Browsing element representing of RNTuple \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RNTupleElement : public RElement { protected: std::shared_ptr<ROOT::Experimental::RNTupleReader> fNTuple; public: RNTupleElement(const std::string &tuple_name, const std::string &filename) { fNTuple = ROOT::Experimental::RNTupleReader::Open(tuple_name, filename); } virtual ~RNTupleElement() = default; /** Returns true if no ntuple found */ bool IsNull() const { return !fNTuple; } /** Name of NTuple */ std::string GetName() const override { return fNTuple->GetDescriptor().GetName(); } /** Title of NTuple */ std::string GetTitle() const override { return "RNTuple title"s; } /** Create iterator for childs elements if any */ std::unique_ptr<RLevelIter> GetChildsIter() override; const TClass *GetClass() const { return TClass::GetClass<ROOT::Experimental::RNTuple>(); } //EActionKind GetDefaultAction() const override; //bool IsCapable(EActionKind) const override; }; // ============================================================================================== /** \class RFieldsIterator \ingroup rbrowser \brief Iterator over RNTuple fields \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RFieldsIterator : public RLevelIter { std::shared_ptr<ROOT::Experimental::RNTupleReader> fNTuple; std::vector<ROOT::Experimental::DescriptorId_t> fFieldIds; std::string fParentName; int fCounter{-1}; public: RFieldsIterator(std::shared_ptr<ROOT::Experimental::RNTupleReader> tuple, std::vector<ROOT::Experimental::DescriptorId_t> &&ids, const std::string &parent_name = ""s) : fNTuple(tuple), fFieldIds(ids), fParentName(parent_name) { } virtual ~RFieldsIterator() = default; bool Next() override { return ++fCounter < (int) fFieldIds.size(); } std::string GetItemName() const override { return fNTuple->GetDescriptor().GetFieldDescriptor(fFieldIds[fCounter]).GetFieldName(); } bool CanItemHaveChilds() const override { auto subrange = fNTuple->GetDescriptor().GetFieldRange(fFieldIds[fCounter]); return subrange.begin() != subrange.end(); } /** Create element for the browser */ std::unique_ptr<RItem> CreateItem() override { int nchilds = 0; for (auto &sub: fNTuple->GetDescriptor().GetFieldRange(fFieldIds[fCounter])) { (void) sub; nchilds++; } auto &field = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldIds[fCounter]); auto item = std::make_unique<RItem>(field.GetFieldName(), nchilds, nchilds > 0 ? "sap-icon://split" : "sap-icon://e-care"); item->SetTitle("RField name "s + field.GetFieldName() + " type "s + field.GetTypeName()); return item; } std::shared_ptr<RElement> GetElement() override { return std::make_shared<RFieldElement>(fNTuple, fParentName, fFieldIds[fCounter]); } }; std::unique_ptr<RLevelIter> RFieldElement::GetChildsIter() { std::vector<ROOT::Experimental::DescriptorId_t> ids; for (auto &f : fNTuple->GetDescriptor().GetFieldRange(fFieldId)) ids.emplace_back(f.GetId()); if (ids.size() == 0) return nullptr; std::string prefix = fParentName; auto &fld = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId); prefix.append(fld.GetFieldName()); prefix.append("."); return std::make_unique<RFieldsIterator>(fNTuple, std::move(ids), prefix); } std::unique_ptr<RLevelIter> RNTupleElement::GetChildsIter() { std::vector<ROOT::Experimental::DescriptorId_t> ids; for (auto &f : fNTuple->GetDescriptor().GetTopLevelFields()) ids.emplace_back(f.GetId()); if (ids.size() == 0) return nullptr; return std::make_unique<RFieldsIterator>(fNTuple, std::move(ids)); } // ============================================================================================== /** \class RNTupleBrowseProvider \ingroup rbrowser \brief Provider for browsing RNTuple classes \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RNTupleBrowseProvider : public RProvider { public: RNTupleBrowseProvider() { RegisterNTupleFunc([](const std::string &tuple_name, const std::string &filename) -> std::shared_ptr<RElement> { auto elem = std::make_shared<RNTupleElement>(tuple_name, filename); return elem->IsNull() ? nullptr : elem; }); } virtual ~RNTupleBrowseProvider() { RegisterNTupleFunc(nullptr); } } newRNTupleBrowseProvider;
/************************************************************************* * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <ROOT/Browsable/RElement.hxx> #include <ROOT/Browsable/RProvider.hxx> #include <ROOT/Browsable/RLevelIter.hxx> #include <ROOT/Browsable/RItem.hxx> #include <ROOT/RNTuple.hxx> #include <ROOT/RNTupleDescriptor.hxx> #include <ROOT/RMiniFile.hxx> #include "TClass.h" #include "RFieldHolder.hxx" using namespace std::string_literals; using namespace ROOT::Experimental::Browsable; // ============================================================================================== /** \class RFieldElement \ingroup rbrowser \brief Browsing element representing of RField \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RFieldElement : public RElement { protected: std::shared_ptr<ROOT::Experimental::RNTupleReader> fNTuple; std::string fParentName; ROOT::Experimental::DescriptorId_t fFieldId; public: RFieldElement(std::shared_ptr<ROOT::Experimental::RNTupleReader> tuple, const std::string &parent_name, const ROOT::Experimental::DescriptorId_t id) : RElement(), fNTuple(tuple), fParentName(parent_name), fFieldId(id) {} virtual ~RFieldElement() = default; /** Name of RField */ std::string GetName() const override { return fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId).GetFieldName(); } /** Title of RField */ std::string GetTitle() const override { auto &fld = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId); return "RField name "s + fld.GetFieldName() + " type "s + fld.GetTypeName(); } std::unique_ptr<RLevelIter> GetChildsIter() override; /** Return class of field - for a moment using RNTuple class as dummy */ const TClass *GetClass() const { return TClass::GetClass<ROOT::Experimental::RNTuple>(); } std::unique_ptr<RHolder> GetObject() override { return std::make_unique<RFieldHolder>(fNTuple, fParentName, fFieldId); } EActionKind GetDefaultAction() const override { auto range = fNTuple->GetDescriptor().GetFieldRange(fFieldId); if (range.begin() != range.end()) return kActNone; auto &field = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId); bool supported = (field.GetTypeName() == "double"s) || (field.GetTypeName() == "float"s) || (field.GetTypeName() == "int"s) || (field.GetTypeName() == "std::int32_t"s) || (field.GetTypeName() == "std::uint32_t"s) || (field.GetTypeName() == "std::string"s); if (!supported) printf("Field %s type %s not yet supported for drawing\n", field.GetFieldName().c_str(), field.GetTypeName().c_str()); return supported ? kActDraw6 : kActNone; } //bool IsCapable(EActionKind) const override; }; // ============================================================================================== /** \class RNTupleElement \ingroup rbrowser \brief Browsing element representing of RNTuple \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RNTupleElement : public RElement { protected: std::shared_ptr<ROOT::Experimental::RNTupleReader> fNTuple; public: RNTupleElement(const std::string &tuple_name, const std::string &filename) { fNTuple = ROOT::Experimental::RNTupleReader::Open(tuple_name, filename); } virtual ~RNTupleElement() = default; /** Returns true if no ntuple found */ bool IsNull() const { return !fNTuple; } /** Name of NTuple */ std::string GetName() const override { return fNTuple->GetDescriptor().GetName(); } /** Title of NTuple */ std::string GetTitle() const override { return "RNTuple title"s; } /** Create iterator for childs elements if any */ std::unique_ptr<RLevelIter> GetChildsIter() override; const TClass *GetClass() const { return TClass::GetClass<ROOT::Experimental::RNTuple>(); } //EActionKind GetDefaultAction() const override; //bool IsCapable(EActionKind) const override; }; // ============================================================================================== /** \class RFieldsIterator \ingroup rbrowser \brief Iterator over RNTuple fields \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RFieldsIterator : public RLevelIter { std::shared_ptr<ROOT::Experimental::RNTupleReader> fNTuple; std::vector<ROOT::Experimental::DescriptorId_t> fFieldIds; std::string fParentName; int fCounter{-1}; public: RFieldsIterator(std::shared_ptr<ROOT::Experimental::RNTupleReader> tuple, std::vector<ROOT::Experimental::DescriptorId_t> &&ids, const std::string &parent_name = ""s) : fNTuple(tuple), fFieldIds(ids), fParentName(parent_name) { } virtual ~RFieldsIterator() = default; bool Next() override { return ++fCounter < (int) fFieldIds.size(); } std::string GetItemName() const override { return fNTuple->GetDescriptor().GetFieldDescriptor(fFieldIds[fCounter]).GetFieldName(); } bool CanItemHaveChilds() const override { auto subrange = fNTuple->GetDescriptor().GetFieldRange(fFieldIds[fCounter]); return subrange.begin() != subrange.end(); } /** Create element for the browser */ std::unique_ptr<RItem> CreateItem() override { int nchilds = 0; for (auto &sub: fNTuple->GetDescriptor().GetFieldRange(fFieldIds[fCounter])) { (void) sub; nchilds++; } auto &field = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldIds[fCounter]); auto item = std::make_unique<RItem>(field.GetFieldName(), nchilds, nchilds > 0 ? "sap-icon://split" : "sap-icon://e-care"); item->SetTitle("RField name "s + field.GetFieldName() + " type "s + field.GetTypeName()); return item; } std::shared_ptr<RElement> GetElement() override { return std::make_shared<RFieldElement>(fNTuple, fParentName, fFieldIds[fCounter]); } }; std::unique_ptr<RLevelIter> RFieldElement::GetChildsIter() { std::vector<ROOT::Experimental::DescriptorId_t> ids; for (auto &f : fNTuple->GetDescriptor().GetFieldRange(fFieldId)) ids.emplace_back(f.GetId()); if (ids.size() == 0) return nullptr; std::string prefix = fParentName; auto &fld = fNTuple->GetDescriptor().GetFieldDescriptor(fFieldId); prefix.append(fld.GetFieldName()); prefix.append("."); return std::make_unique<RFieldsIterator>(fNTuple, std::move(ids), prefix); } std::unique_ptr<RLevelIter> RNTupleElement::GetChildsIter() { std::vector<ROOT::Experimental::DescriptorId_t> ids; for (auto &f : fNTuple->GetDescriptor().GetTopLevelFields()) ids.emplace_back(f.GetId()); if (ids.size() == 0) return nullptr; return std::make_unique<RFieldsIterator>(fNTuple, std::move(ids)); } // ============================================================================================== /** \class RNTupleBrowseProvider \ingroup rbrowser \brief Provider for browsing RNTuple classes \author Sergey Linev <[email protected]> \date 2021-03-08 \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome! */ class RNTupleBrowseProvider : public RProvider { public: RNTupleBrowseProvider() { RegisterNTupleFunc([](const std::string &tuple_name, const std::string &filename) -> std::shared_ptr<RElement> { auto elem = std::make_shared<RNTupleElement>(tuple_name, filename); return elem->IsNull() ? nullptr : elem; }); } virtual ~RNTupleBrowseProvider() { RegisterNTupleFunc(nullptr); } } newRNTupleBrowseProvider;
add override specifier
[browsable] add override specifier Fix compiler warnings
C++
lgpl-2.1
olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,olifre/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root
f37274269615fccb6f5d0b5f5f029c728c996896
eval/src/tests/eval/fast_sparse_map/fast_sparse_map_test.cpp
eval/src/tests/eval/fast_sparse_map/fast_sparse_map_test.cpp
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/eval/eval/fast_sparse_map.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <vespa/vespalib/gtest/gtest.h> using namespace vespalib; using namespace vespalib::eval; class StringList { private: std::vector<vespalib::string> _str_list; std::vector<vespalib::stringref> _ref_list; std::vector<const vespalib::stringref *> _ref_ptr_list; public: StringList(const std::vector<vespalib::string> &list) : _str_list(list), _ref_list(), _ref_ptr_list() { for (const auto &str: _str_list) { _ref_list.push_back(str); } for (const auto &ref: _ref_list) { _ref_ptr_list.push_back(&ref); } } ~StringList(); ConstArrayRef<vespalib::string> direct_str() const { return _str_list; } ConstArrayRef<vespalib::stringref> direct_ref() const { return _ref_list; } ConstArrayRef<const vespalib::stringref *> indirect_ref() const { return _ref_ptr_list; } }; StringList::~StringList() = default; using SL = StringList; TEST(FastSparseMapTest, fast_sparse_map_basic_usage_works) { SL a1({"a","a","a"}); SL a2({"a","a","b"}); SL a3({"a","b","a"}); SL a4({"b","a","a"}); FastSparseMap map(3, 128); EXPECT_EQ(map.size(), 0); map.add_mapping(a1.direct_str()); map.add_mapping(a2.direct_ref()); map.add_mapping(a3.indirect_ref()); EXPECT_EQ(map.size(), 3); EXPECT_EQ(map.lookup(a1.direct_str()), 0); EXPECT_EQ(map.lookup(a1.direct_ref()), 0); EXPECT_EQ(map.lookup(a1.indirect_ref()), 0); EXPECT_EQ(map.lookup(a2.direct_str()), 1); EXPECT_EQ(map.lookup(a2.direct_ref()), 1); EXPECT_EQ(map.lookup(a2.indirect_ref()), 1); EXPECT_EQ(map.lookup(a3.direct_str()), 2); EXPECT_EQ(map.lookup(a3.direct_ref()), 2); EXPECT_EQ(map.lookup(a3.indirect_ref()), 2); EXPECT_EQ(map.lookup(a4.direct_str()), map.npos()); EXPECT_EQ(map.lookup(a4.direct_ref()), map.npos()); EXPECT_EQ(map.lookup(a4.indirect_ref()), map.npos()); EXPECT_EQ(FastSparseMap::npos(), map.npos()); EXPECT_EQ(map.labels().size(), 9); auto dump = [&](auto addr_tag, auto subspace, auto hash) { auto addr = map.make_addr(addr_tag); fprintf(stderr, " [%s,%s,%s]: %u (%zu)\n", addr[0].label.c_str(), addr[1].label.c_str(), addr[2].label.c_str(), subspace, hash); }; map.each_map_entry(dump); } TEST(FastSparseMapTest, fast_sparse_map_works_with_no_labels) { SL empty({}); FastSparseMap map1(0, 1); FastSparseMap map2(0, 1); FastSparseMap map3(0, 1); EXPECT_EQ(map1.size(), 0); EXPECT_EQ(map2.size(), 0); EXPECT_EQ(map3.size(), 0); map1.add_mapping(empty.direct_str()); map2.add_mapping(empty.direct_ref()); map3.add_mapping(empty.indirect_ref()); EXPECT_EQ(map1.size(), 1); EXPECT_EQ(map2.size(), 1); EXPECT_EQ(map3.size(), 1); EXPECT_EQ(map1.lookup(empty.direct_str()), 0); EXPECT_EQ(map1.lookup(empty.direct_ref()), 0); EXPECT_EQ(map1.lookup(empty.indirect_ref()), 0); EXPECT_EQ(map2.lookup(empty.direct_str()), 0); EXPECT_EQ(map2.lookup(empty.direct_ref()), 0); EXPECT_EQ(map2.lookup(empty.indirect_ref()), 0); EXPECT_EQ(map3.lookup(empty.direct_str()), 0); EXPECT_EQ(map3.lookup(empty.direct_ref()), 0); EXPECT_EQ(map3.lookup(empty.indirect_ref()), 0); EXPECT_EQ(map1.labels().size(), 0); EXPECT_EQ(map2.labels().size(), 0); EXPECT_EQ(map3.labels().size(), 0); } TEST(FastSparseMapTest, size_of_internal_types) { fprintf(stderr, "fast sparse map hash node size: %zu\n", sizeof(hash_node<FastSparseMap::MapType::value_type>)); } GTEST_MAIN_RUN_ALL_TESTS()
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/eval/eval/fast_sparse_map.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <vespa/vespalib/gtest/gtest.h> using namespace vespalib; using namespace vespalib::eval; class StringList { private: std::vector<vespalib::string> _str_list; std::vector<vespalib::stringref> _ref_list; std::vector<const vespalib::stringref *> _ref_ptr_list; public: StringList(const std::vector<vespalib::string> &list) : _str_list(list), _ref_list(), _ref_ptr_list() { for (const auto &str: _str_list) { _ref_list.push_back(str); } for (const auto &ref: _ref_list) { _ref_ptr_list.push_back(&ref); } } ~StringList(); ConstArrayRef<vespalib::string> direct_str() const { return _str_list; } ConstArrayRef<vespalib::stringref> direct_ref() const { return _ref_list; } ConstArrayRef<const vespalib::stringref *> indirect_ref() const { return _ref_ptr_list; } bool is_eq(ConstArrayRef<FastSparseMap::HashedLabel> addr) const { if (addr.size() != _str_list.size()) { return false; } for (size_t i = 0; i < addr.size(); ++i) { if (addr[i].label != _str_list[i]) { return false; } } return true; } }; StringList::~StringList() = default; using SL = StringList; TEST(FastSparseMapTest, fast_sparse_map_basic_usage_works) { SL a1({"a","a","a"}); SL a2({"a","a","b"}); SL a3({"a","b","a"}); SL a4({"b","a","a"}); FastSparseMap map(3, 128); EXPECT_EQ(map.size(), 0); map.add_mapping(a1.direct_str()); map.add_mapping(a2.direct_ref()); map.add_mapping(a3.indirect_ref()); EXPECT_EQ(map.size(), 3); EXPECT_EQ(map.lookup(a1.direct_str()), 0); EXPECT_EQ(map.lookup(a1.direct_ref()), 0); EXPECT_EQ(map.lookup(a1.indirect_ref()), 0); EXPECT_EQ(map.lookup(a2.direct_str()), 1); EXPECT_EQ(map.lookup(a2.direct_ref()), 1); EXPECT_EQ(map.lookup(a2.indirect_ref()), 1); EXPECT_EQ(map.lookup(a3.direct_str()), 2); EXPECT_EQ(map.lookup(a3.direct_ref()), 2); EXPECT_EQ(map.lookup(a3.indirect_ref()), 2); EXPECT_EQ(map.lookup(a4.direct_str()), map.npos()); EXPECT_EQ(map.lookup(a4.direct_ref()), map.npos()); EXPECT_EQ(map.lookup(a4.indirect_ref()), map.npos()); EXPECT_EQ(FastSparseMap::npos(), map.npos()); EXPECT_EQ(map.labels().size(), 9); using hash_t = FastSparseMap::hash_t; std::set<hash_t> seen_hashes; std::map<uint32_t, uint32_t> addr_map; auto my_fun = [&](uint32_t addr_tag, uint32_t subspace, hash_t hash) { addr_map[addr_tag] = subspace; seen_hashes.insert(hash); }; map.each_map_entry(my_fun); EXPECT_EQ(seen_hashes.size(), 3); EXPECT_EQ(addr_map.size(), 3); EXPECT_NE(addr_map.find(0), addr_map.end()); EXPECT_EQ(addr_map[0], 0); EXPECT_EQ(addr_map[3], 1); EXPECT_EQ(addr_map[6], 2); EXPECT_EQ(addr_map.size(), 3); EXPECT_TRUE(a1.is_eq(map.make_addr(0))); EXPECT_FALSE(a2.is_eq(map.make_addr(0))); EXPECT_TRUE(a2.is_eq(map.make_addr(3))); EXPECT_TRUE(a3.is_eq(map.make_addr(6))); } TEST(FastSparseMapTest, fast_sparse_map_works_with_no_labels) { SL empty({}); FastSparseMap map1(0, 1); FastSparseMap map2(0, 1); FastSparseMap map3(0, 1); EXPECT_EQ(map1.size(), 0); EXPECT_EQ(map2.size(), 0); EXPECT_EQ(map3.size(), 0); map1.add_mapping(empty.direct_str()); map2.add_mapping(empty.direct_ref()); map3.add_mapping(empty.indirect_ref()); EXPECT_EQ(map1.size(), 1); EXPECT_EQ(map2.size(), 1); EXPECT_EQ(map3.size(), 1); EXPECT_EQ(map1.lookup(empty.direct_str()), 0); EXPECT_EQ(map1.lookup(empty.direct_ref()), 0); EXPECT_EQ(map1.lookup(empty.indirect_ref()), 0); EXPECT_EQ(map2.lookup(empty.direct_str()), 0); EXPECT_EQ(map2.lookup(empty.direct_ref()), 0); EXPECT_EQ(map2.lookup(empty.indirect_ref()), 0); EXPECT_EQ(map3.lookup(empty.direct_str()), 0); EXPECT_EQ(map3.lookup(empty.direct_ref()), 0); EXPECT_EQ(map3.lookup(empty.indirect_ref()), 0); EXPECT_EQ(map1.labels().size(), 0); EXPECT_EQ(map2.labels().size(), 0); EXPECT_EQ(map3.labels().size(), 0); } TEST(FastSparseMapTest, size_of_internal_types) { fprintf(stderr, "fast sparse map hash node size: %zu\n", sizeof(hash_node<FastSparseMap::MapType::value_type>)); } GTEST_MAIN_RUN_ALL_TESTS()
improve testing of each_map_entry
improve testing of each_map_entry
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
ed90ed692ffd86025dd970ac889c3372791e4936
interpreter/cling/lib/Interpreter/ASTNullDerefProtection.cpp
interpreter/cling/lib/Interpreter/ASTNullDerefProtection.cpp
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Baozeng Ding <[email protected]> // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "ASTNullDerefProtection.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Mangle.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Lookup.h" using namespace clang; namespace cling { ASTNullDerefProtection::ASTNullDerefProtection(clang::Sema* S) : TransactionTransformer(S) { } ASTNullDerefProtection::~ASTNullDerefProtection() { } bool ASTNullDerefProtection::isDeclCandidate(FunctionDecl * FDecl) { if(m_NonNullArgIndexs.count(FDecl)) return true; std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; for (NonNullAttr::args_iterator i = NonNull->args_begin(), e = NonNull->args_end(); i != e; ++i) { ArgIndexs.set(*i); } } if (ArgIndexs.any()) { m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs)); return true; } return false; } Stmt* ASTNullDerefProtection::SynthesizeCheck(SourceLocation Loc, Expr* Arg ){ ASTContext& Context = m_Sema->getASTContext(); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); //copied from DynamicLookup.cpp NamespaceDecl* NSD = utils::Lookup::Namespace(m_Sema, "cling"); NamespaceDecl* clingRuntimeNSD = utils::Lookup::Namespace(m_Sema, "runtime", NSD); // Find and set up "NullDerefException" DeclarationName Name = &Context.Idents.get("NullDerefException"); LookupResult R(*m_Sema, Name, SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, clingRuntimeNSD); CXXRecordDecl* NullDerefDecl = R.getAsSingle<CXXRecordDecl>(); // Lookup Sema type CXXRecordDecl* SemaRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Sema", utils::Lookup::Namespace(m_Sema, "clang"))); QualType SemaRDTy = Context.getTypeDeclType(SemaRD); Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, SemaRDTy, (uint64_t)m_Sema); // Lookup Expr type CXXRecordDecl* ExprRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr", utils::Lookup::Namespace(m_Sema, "clang"))); QualType ExprRDTy = Context.getTypeDeclType(ExprRD); Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)Arg); Expr *args[] = {VoidSemaArg, VoidExprArg}; QualType NullDerefDeclTy = Context.getTypeDeclType(NullDerefDecl); TypeSourceInfo* TSI = Context.getTrivialTypeSourceInfo(NullDerefDeclTy, SourceLocation()); ExprResult ConstructorCall = m_Sema->BuildCXXTypeConstructExpr(TSI,Loc, MultiExprArg(args, 2),Loc); Expr* Throw = m_Sema->ActOnCXXThrow(S, Loc, ConstructorCall.take()).take(); // Check whether we can get the argument'value. If the argument is // null, throw an exception direclty. If the argument is not null // then ignore this argument and continue to deal with the next // argument with the nonnull attribute. bool Result = false; if (Arg->EvaluateAsBooleanCondition(Result, Context)) { if(!Result) { return Throw; } return Arg; } // The argument's value cannot be decided, so we add a UnaryOp // operation to check its value at runtime. DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreImpCasts()); assert(DRE && "No declref expr?"); ExprResult ER = m_Sema->ActOnUnaryOp(S, Loc, tok::exclaim, DRE); Decl* varDecl = 0; Stmt* varStmt = 0; Sema::FullExprArg FullCond(m_Sema->MakeFullExpr(ER.take())); StmtResult IfStmt = m_Sema->ActOnIfStmt(Loc, FullCond, varDecl, Throw, Loc, varStmt); return IfStmt.take(); } void ASTNullDerefProtection::Transform() { FunctionDecl* FD = getTransaction()->getWrapperFD(); if (!FD) return; CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody()); assert(CS && "Function body not a CompundStmt?"); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); ASTContext* Context = &m_Sema->getASTContext(); DeclContext* DC = FD->getTranslationUnitDecl(); llvm::SmallVector<Stmt*, 4> Stmts; SourceLocation Loc = FD->getBody()->getLocStart(); for (CompoundStmt::body_iterator I = CS->body_begin(), EI = CS->body_end(); I != EI; ++I) { CallExpr* CE = dyn_cast<CallExpr>(*I); if (CE) { if (FunctionDecl* FDecl = CE->getDirectCallee()) { if(FDecl && isDeclCandidate(FDecl)) { SourceLocation CallLoc = CE->getLocStart(); decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl); const std::bitset<32>& ArgIndexs = it->second; Sema::ContextRAII pushedDC(*m_Sema, FDecl); for (int index = 0; index < 32; ++index) { if (!ArgIndexs.test(index)) continue; // Get the argument with the nonnull attribute. Expr* Arg = CE->getArg(index); Stmts.push_back(SynthesizeCheck(CallLoc, Arg)); } } } //Stmts.push_back(CE); } else { if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(*I)) { SourceLocation SL = BinOp->getLocStart(); Expr* LHS = BinOp->getLHS()->IgnoreImpCasts(); Expr* RHS = BinOp->getRHS()->IgnoreImpCasts(); UnaryOperator* LUO = dyn_cast<UnaryOperator>(LHS); UnaryOperator* RUO = dyn_cast<UnaryOperator>(RHS); if (LUO && LUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(LUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Expr* Throw = InsertThrow(&SL, Op); Stmts.push_back(Throw); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } if (RUO && RUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(RUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Expr* Throw = InsertThrow(&SL, Op); Stmts.push_back(Throw); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } } } Stmts.push_back(*I); } llvm::ArrayRef<Stmt*> StmtsRef(Stmts.data(), Stmts.size()); CompoundStmt* CSBody = new (*Context)CompoundStmt(*Context, StmtsRef, Loc, Loc); FD->setBody(CSBody); DC->removeDecl(FD); DC->addDecl(FD); } } // end namespace cling
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Baozeng Ding <[email protected]> // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "ASTNullDerefProtection.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Mangle.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Lookup.h" using namespace clang; namespace cling { ASTNullDerefProtection::ASTNullDerefProtection(clang::Sema* S) : TransactionTransformer(S) { } ASTNullDerefProtection::~ASTNullDerefProtection() { } bool ASTNullDerefProtection::isDeclCandidate(FunctionDecl * FDecl) { if(m_NonNullArgIndexs.count(FDecl)) return true; std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; for (NonNullAttr::args_iterator i = NonNull->args_begin(), e = NonNull->args_end(); i != e; ++i) { ArgIndexs.set(*i); } } if (ArgIndexs.any()) { m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs)); return true; } return false; } Stmt* ASTNullDerefProtection::SynthesizeCheck(SourceLocation Loc, Expr* Arg ){ ASTContext& Context = m_Sema->getASTContext(); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); //copied from DynamicLookup.cpp NamespaceDecl* NSD = utils::Lookup::Namespace(m_Sema, "cling"); NamespaceDecl* clingRuntimeNSD = utils::Lookup::Namespace(m_Sema, "runtime", NSD); // Find and set up "NullDerefException" DeclarationName Name = &Context.Idents.get("NullDerefException"); LookupResult R(*m_Sema, Name, SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, clingRuntimeNSD); CXXRecordDecl* NullDerefDecl = R.getAsSingle<CXXRecordDecl>(); // Lookup Sema type CXXRecordDecl* SemaRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Sema", utils::Lookup::Namespace(m_Sema, "clang"))); QualType SemaRDTy = Context.getTypeDeclType(SemaRD); Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, SemaRDTy, (uint64_t)m_Sema); // Lookup Expr type CXXRecordDecl* ExprRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr", utils::Lookup::Namespace(m_Sema, "clang"))); QualType ExprRDTy = Context.getTypeDeclType(ExprRD); Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)Arg); Expr *args[] = {VoidSemaArg, VoidExprArg}; QualType NullDerefDeclTy = Context.getTypeDeclType(NullDerefDecl); TypeSourceInfo* TSI = Context.getTrivialTypeSourceInfo(NullDerefDeclTy, SourceLocation()); ExprResult ConstructorCall = m_Sema->BuildCXXTypeConstructExpr(TSI,Loc, MultiExprArg(args, 2),Loc); Expr* Throw = m_Sema->ActOnCXXThrow(S, Loc, ConstructorCall.take()).take(); // Check whether we can get the argument'value. If the argument is // null, throw an exception direclty. If the argument is not null // then ignore this argument and continue to deal with the next // argument with the nonnull attribute. bool Result = false; if (Arg->EvaluateAsBooleanCondition(Result, Context)) { if(!Result) { return Throw; } return Arg; } // The argument's value cannot be decided, so we add a UnaryOp // operation to check its value at runtime. DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreImpCasts()); assert(DRE && "No declref expr?"); ExprResult ER = m_Sema->ActOnUnaryOp(S, Loc, tok::exclaim, DRE); Decl* varDecl = 0; Stmt* varStmt = 0; Sema::FullExprArg FullCond(m_Sema->MakeFullExpr(ER.take())); StmtResult IfStmt = m_Sema->ActOnIfStmt(Loc, FullCond, varDecl, Throw, Loc, varStmt); return IfStmt.take(); } void ASTNullDerefProtection::Transform() { FunctionDecl* FD = getTransaction()->getWrapperFD(); if (!FD) return; CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody()); assert(CS && "Function body not a CompundStmt?"); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); ASTContext* Context = &m_Sema->getASTContext(); DeclContext* DC = FD->getTranslationUnitDecl(); llvm::SmallVector<Stmt*, 4> Stmts; SourceLocation Loc = FD->getBody()->getLocStart(); for (CompoundStmt::body_iterator I = CS->body_begin(), EI = CS->body_end(); I != EI; ++I) { CallExpr* CE = dyn_cast<CallExpr>(*I); if (CE) { if (FunctionDecl* FDecl = CE->getDirectCallee()) { if(FDecl && isDeclCandidate(FDecl)) { SourceLocation CallLoc = CE->getLocStart(); decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl); const std::bitset<32>& ArgIndexs = it->second; Sema::ContextRAII pushedDC(*m_Sema, FDecl); for (int index = 0; index < 32; ++index) { if (!ArgIndexs.test(index)) continue; // Get the argument with the nonnull attribute. Expr* Arg = CE->getArg(index); Stmts.push_back(SynthesizeCheck(CallLoc, Arg)); } } } //Stmts.push_back(CE); } else { if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(*I)) { SourceLocation SL = BinOp->getLocStart(); Expr* LHS = BinOp->getLHS()->IgnoreImpCasts(); Expr* RHS = BinOp->getRHS()->IgnoreImpCasts(); UnaryOperator* LUO = dyn_cast<UnaryOperator>(LHS); UnaryOperator* RUO = dyn_cast<UnaryOperator>(RHS); if (LUO && LUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(LUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Stmts.push_back(SynthesizeCheck(SL, Op)); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } if (RUO && RUO->getOpcode() == UO_Deref) { Expr* Op = dyn_cast<DeclRefExpr>(RUO->getSubExpr()->IgnoreImpCasts()); if (Op) { bool Result = false; if (Op->EvaluateAsBooleanCondition(Result, *Context)) { if(!Result) { Stmts.push_back(SynthesizeCheck(SL, Op)); } } else { Stmts.push_back(SynthesizeCheck(SL, Op)); } } } } } Stmts.push_back(*I); } llvm::ArrayRef<Stmt*> StmtsRef(Stmts.data(), Stmts.size()); CompoundStmt* CSBody = new (*Context)CompoundStmt(*Context, StmtsRef, Loc, Loc); FD->setBody(CSBody); DC->removeDecl(FD); DC->addDecl(FD); } } // end namespace cling
Use the correct routine.
Use the correct routine.
C++
lgpl-2.1
beniz/root,veprbl/root,zzxuanyuan/root-compressor-dummy,omazapa/root,vukasinmilosevic/root,thomaskeck/root,perovic/root,sbinet/cxx-root,georgtroska/root,Duraznos/root,lgiommi/root,gbitzes/root,Y--/root,georgtroska/root,nilqed/root,dfunke/root,georgtroska/root,olifre/root,arch1tect0r/root,BerserkerTroll/root,mhuwiler/rootauto,omazapa/root,dfunke/root,sawenzel/root,veprbl/root,smarinac/root,pspe/root,gbitzes/root,root-mirror/root,smarinac/root,abhinavmoudgil95/root,mkret2/root,krafczyk/root,esakellari/root,simonpf/root,evgeny-boger/root,mattkretz/root,beniz/root,gbitzes/root,georgtroska/root,pspe/root,simonpf/root,sirinath/root,karies/root,jrtomps/root,beniz/root,0x0all/ROOT,perovic/root,karies/root,cxx-hep/root-cern,dfunke/root,arch1tect0r/root,sawenzel/root,zzxuanyuan/root,lgiommi/root,evgeny-boger/root,olifre/root,lgiommi/root,agarciamontoro/root,omazapa/root-old,dfunke/root,davidlt/root,omazapa/root-old,satyarth934/root,mhuwiler/rootauto,Y--/root,sawenzel/root,Y--/root,smarinac/root,arch1tect0r/root,esakellari/root,satyarth934/root,nilqed/root,georgtroska/root,BerserkerTroll/root,sbinet/cxx-root,davidlt/root,gganis/root,vukasinmilosevic/root,nilqed/root,sawenzel/root,mkret2/root,agarciamontoro/root,abhinavmoudgil95/root,cxx-hep/root-cern,lgiommi/root,vukasinmilosevic/root,mhuwiler/rootauto,simonpf/root,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,perovic/root,0x0all/ROOT,Y--/root,perovic/root,pspe/root,olifre/root,CristinaCristescu/root,agarciamontoro/root,esakellari/my_root_for_test,krafczyk/root,agarciamontoro/root,cxx-hep/root-cern,sirinath/root,abhinavmoudgil95/root,zzxuanyuan/root,nilqed/root,omazapa/root-old,CristinaCristescu/root,gbitzes/root,olifre/root,evgeny-boger/root,davidlt/root,davidlt/root,gganis/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,omazapa/root-old,thomaskeck/root,sawenzel/root,davidlt/root,BerserkerTroll/root,omazapa/root,beniz/root,BerserkerTroll/root,BerserkerTroll/root,evgeny-boger/root,buuck/root,esakellari/root,veprbl/root,Duraznos/root,mattkretz/root,mhuwiler/rootauto,evgeny-boger/root,mattkretz/root,thomaskeck/root,mattkretz/root,bbockelm/root,root-mirror/root,omazapa/root,satyarth934/root,evgeny-boger/root,perovic/root,0x0all/ROOT,lgiommi/root,omazapa/root-old,Y--/root,karies/root,root-mirror/root,bbockelm/root,nilqed/root,vukasinmilosevic/root,mhuwiler/rootauto,esakellari/my_root_for_test,smarinac/root,pspe/root,karies/root,veprbl/root,pspe/root,gganis/root,CristinaCristescu/root,buuck/root,smarinac/root,sawenzel/root,buuck/root,satyarth934/root,satyarth934/root,jrtomps/root,zzxuanyuan/root,buuck/root,karies/root,jrtomps/root,omazapa/root,sirinath/root,alexschlueter/cern-root,dfunke/root,evgeny-boger/root,veprbl/root,root-mirror/root,BerserkerTroll/root,perovic/root,vukasinmilosevic/root,mkret2/root,vukasinmilosevic/root,Duraznos/root,smarinac/root,0x0all/ROOT,simonpf/root,smarinac/root,buuck/root,simonpf/root,dfunke/root,gganis/root,karies/root,veprbl/root,mhuwiler/rootauto,sbinet/cxx-root,sirinath/root,zzxuanyuan/root,veprbl/root,BerserkerTroll/root,gganis/root,gganis/root,evgeny-boger/root,vukasinmilosevic/root,esakellari/root,alexschlueter/cern-root,zzxuanyuan/root,pspe/root,davidlt/root,buuck/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,Duraznos/root,mhuwiler/rootauto,jrtomps/root,pspe/root,dfunke/root,agarciamontoro/root,sawenzel/root,smarinac/root,Duraznos/root,cxx-hep/root-cern,smarinac/root,perovic/root,zzxuanyuan/root-compressor-dummy,karies/root,mkret2/root,gganis/root,alexschlueter/cern-root,gbitzes/root,thomaskeck/root,root-mirror/root,mattkretz/root,abhinavmoudgil95/root,mkret2/root,zzxuanyuan/root-compressor-dummy,abhinavmoudgil95/root,gganis/root,buuck/root,krafczyk/root,olifre/root,sbinet/cxx-root,CristinaCristescu/root,mkret2/root,bbockelm/root,gganis/root,bbockelm/root,sbinet/cxx-root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,omazapa/root,CristinaCristescu/root,buuck/root,sirinath/root,sirinath/root,zzxuanyuan/root-compressor-dummy,esakellari/my_root_for_test,abhinavmoudgil95/root,davidlt/root,mhuwiler/rootauto,esakellari/root,sirinath/root,jrtomps/root,omazapa/root-old,abhinavmoudgil95/root,alexschlueter/cern-root,BerserkerTroll/root,veprbl/root,Y--/root,krafczyk/root,pspe/root,evgeny-boger/root,omazapa/root,arch1tect0r/root,georgtroska/root,jrtomps/root,sawenzel/root,mattkretz/root,buuck/root,alexschlueter/cern-root,agarciamontoro/root,mattkretz/root,satyarth934/root,nilqed/root,beniz/root,root-mirror/root,gganis/root,root-mirror/root,olifre/root,mattkretz/root,krafczyk/root,omazapa/root-old,zzxuanyuan/root,perovic/root,nilqed/root,esakellari/root,sirinath/root,davidlt/root,Duraznos/root,agarciamontoro/root,mkret2/root,sawenzel/root,Duraznos/root,vukasinmilosevic/root,evgeny-boger/root,lgiommi/root,georgtroska/root,Y--/root,thomaskeck/root,simonpf/root,mkret2/root,0x0all/ROOT,gbitzes/root,omazapa/root,thomaskeck/root,mkret2/root,mkret2/root,zzxuanyuan/root-compressor-dummy,omazapa/root,Y--/root,BerserkerTroll/root,CristinaCristescu/root,buuck/root,sbinet/cxx-root,buuck/root,satyarth934/root,bbockelm/root,karies/root,omazapa/root,simonpf/root,krafczyk/root,mkret2/root,BerserkerTroll/root,BerserkerTroll/root,olifre/root,omazapa/root,bbockelm/root,davidlt/root,abhinavmoudgil95/root,abhinavmoudgil95/root,arch1tect0r/root,lgiommi/root,gganis/root,esakellari/my_root_for_test,gbitzes/root,thomaskeck/root,olifre/root,jrtomps/root,omazapa/root-old,mhuwiler/rootauto,dfunke/root,zzxuanyuan/root,sbinet/cxx-root,omazapa/root-old,nilqed/root,zzxuanyuan/root-compressor-dummy,olifre/root,satyarth934/root,Duraznos/root,esakellari/root,root-mirror/root,0x0all/ROOT,krafczyk/root,agarciamontoro/root,dfunke/root,esakellari/root,Duraznos/root,gbitzes/root,perovic/root,esakellari/root,omazapa/root-old,bbockelm/root,beniz/root,cxx-hep/root-cern,arch1tect0r/root,veprbl/root,thomaskeck/root,zzxuanyuan/root,sbinet/cxx-root,davidlt/root,veprbl/root,esakellari/my_root_for_test,esakellari/my_root_for_test,sbinet/cxx-root,esakellari/my_root_for_test,root-mirror/root,mhuwiler/rootauto,nilqed/root,vukasinmilosevic/root,veprbl/root,karies/root,thomaskeck/root,agarciamontoro/root,lgiommi/root,vukasinmilosevic/root,nilqed/root,vukasinmilosevic/root,evgeny-boger/root,karies/root,georgtroska/root,olifre/root,zzxuanyuan/root,satyarth934/root,Y--/root,simonpf/root,arch1tect0r/root,cxx-hep/root-cern,sbinet/cxx-root,mattkretz/root,perovic/root,georgtroska/root,krafczyk/root,zzxuanyuan/root,sbinet/cxx-root,thomaskeck/root,jrtomps/root,arch1tect0r/root,karies/root,simonpf/root,esakellari/my_root_for_test,mattkretz/root,olifre/root,beniz/root,esakellari/my_root_for_test,Duraznos/root,alexschlueter/cern-root,sirinath/root,gbitzes/root,smarinac/root,jrtomps/root,agarciamontoro/root,pspe/root,zzxuanyuan/root,omazapa/root-old,zzxuanyuan/root,esakellari/root,sirinath/root,simonpf/root,dfunke/root,mhuwiler/rootauto,Y--/root,krafczyk/root,sirinath/root,abhinavmoudgil95/root,cxx-hep/root-cern,jrtomps/root,beniz/root,sawenzel/root,CristinaCristescu/root,beniz/root,perovic/root,arch1tect0r/root,bbockelm/root,satyarth934/root,lgiommi/root,cxx-hep/root-cern,sawenzel/root,pspe/root,dfunke/root,gbitzes/root,0x0all/ROOT,root-mirror/root,nilqed/root,simonpf/root,pspe/root,beniz/root,CristinaCristescu/root,davidlt/root,CristinaCristescu/root,Duraznos/root,krafczyk/root,bbockelm/root,georgtroska/root,0x0all/ROOT,alexschlueter/cern-root,agarciamontoro/root,CristinaCristescu/root,Y--/root,satyarth934/root,abhinavmoudgil95/root,root-mirror/root,esakellari/root,esakellari/my_root_for_test,gbitzes/root,jrtomps/root,bbockelm/root,mattkretz/root,CristinaCristescu/root,georgtroska/root,bbockelm/root,0x0all/ROOT,beniz/root,lgiommi/root,lgiommi/root
fd7f801852371e6451fc9cfd10991cef9235eb8c
src/antenna_checker/include/antennachecker/AntennaChecker.hh
src/antenna_checker/include/antennachecker/AntennaChecker.hh
// BSD 3-Clause License // // Copyright (c) 2020, MICL, DD-Lab, University of Michigan // 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 holder 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. #pragma once #include <tcl.h> #include <map> #include "opendb/db.h" #include "opendb/dbWireGraph.h" #include "utl/Logger.h" namespace ant { using odb::dbInst; using odb::dbITerm; using odb::dbNet; using odb::dbSWire; using odb::dbTechLayer; using odb::dbWire; using odb::dbWireGraph; using utl::Logger; typedef std::pair<dbWireGraph::Node*, std::vector<dbWireGraph::Node*>> wireroots_info_vec; struct PARinfo { // std::pair<odb::dbWireGraph::Node*, std::vector<odb::dbWireGraph::Node*>> // WirerootNode; odb::dbWireGraph::Node* WirerootNode; std::set<odb::dbITerm*> iterms; double wire_area; double side_wire_area; double iterm_areas[2]; double PAR_value; double PSR_value; double diff_PAR_value; double diff_PSR_value; }; struct ARinfo { odb::dbWireGraph::Node* WirerootNode; odb::dbWireGraph::Node* GateNode; bool violated_net; double PAR_value; double PSR_value; double diff_PAR_value; double diff_PSR_value; double CAR_value; double CSR_value; double diff_CAR_value; double diff_CSR_value; double diff_area; }; struct ANTENNAmodel { odb::dbTechLayer* layer; double metal_factor; double diff_metal_factor; double cut_factor; double diff_cut_factor; double side_metal_factor; double diff_side_metal_factor; double minus_diff_factor; double plus_diff_factor; double diff_metal_reduce_factor; ANTENNAmodel& operator=(const ANTENNAmodel& am) { metal_factor = am.metal_factor; diff_metal_factor = am.diff_metal_factor; cut_factor = am.cut_factor; diff_cut_factor = am.diff_cut_factor; side_metal_factor = am.side_metal_factor; diff_side_metal_factor = am.diff_side_metal_factor; minus_diff_factor = am.minus_diff_factor; plus_diff_factor = am.plus_diff_factor; diff_metal_reduce_factor = am.diff_metal_reduce_factor; return *this; } }; struct VINFO { int routing_level; std::vector<odb::dbITerm*> iterms; int antenna_cell_nums; }; class AntennaChecker { public: AntennaChecker(); ~AntennaChecker(); void init(odb::dbDatabase* db, utl::Logger *logger); dbNet* get_net(std::string net_name); template <class valueType> double defdist(valueType value); // wireroots_info_vec find_segment_root(std::pair<dbWireGraph::Node*, // std::vector<dbWireGraph::Node*>> node_info, int wire_level ); dbWireGraph::Node* find_segment_root(dbWireGraph::Node* node_info, int wire_level); dbWireGraph::Node* find_segment_start(dbWireGraph::Node* node); bool if_segment_root(dbWireGraph::Node* node, int wire_level); void find_wire_below_iterms(dbWireGraph::Node* node, double iterm_areas[2], int wire_level, std::set<dbITerm*>& iv, std::set<dbWireGraph::Node*>& nv); std::pair<double, double> calculate_wire_area( dbWireGraph::Node* node, int wire_level, std::set<dbWireGraph::Node*>& nv, std::set<dbWireGraph::Node*>& level_nodes); double get_via_area(dbWireGraph::Edge* edge); dbTechLayer* get_via_layer(dbWireGraph::Edge* edge); std::string get_via_name(dbWireGraph::Edge* edge); double calculate_via_area(dbWireGraph::Node* node, int wire_level); dbWireGraph::Edge* find_via(dbWireGraph::Node* node, int wire_level); void find_car_path(dbWireGraph::Node* node, int wire_level, dbWireGraph::Node* goal, std::vector<dbWireGraph::Node*>& current_path, std::vector<dbWireGraph::Node*>& path_found); void print_graph_info(dbWireGraph graph); void calculate_PAR_info(PARinfo& PARtable); bool check_iterm(dbWireGraph::Node* node, double iterm_areas[2]); double get_pwl_factor(odb::dbTechLayerAntennaRule::pwl_pair pwl_info, double ref_val, double def); void build_wire_PAR_table(std::vector<PARinfo>& PARtable, std::vector<dbWireGraph::Node*> wireroots_info); void build_wire_CAR_table(std::vector<ARinfo>& CARtable, std::vector<PARinfo> PARtable, std::vector<PARinfo> VIA_PARtable, std::vector<dbWireGraph::Node*> gate_iterms); void build_VIA_PAR_table(std::vector<PARinfo>& VIA_PARtable, std::vector<dbWireGraph::Node*> wireroots_info); void build_VIA_CAR_table(std::vector<ARinfo>& VIA_CARtable, std::vector<PARinfo> PARtable, std::vector<PARinfo> VIA_PARtable, std::vector<dbWireGraph::Node*> gate_iterms); // std::vector<wireroots_info_vec> get_wireroots(dbWireGraph graph); std::vector<dbWireGraph::Node*> get_wireroots(dbWireGraph graph); std::pair<bool, bool> check_wire_PAR(ARinfo AntennaRatio); std::pair<bool, bool> check_wire_CAR(ARinfo AntennaRatio, bool par_checked); bool check_VIA_PAR(ARinfo AntennaRatio); bool check_VIA_CAR(ARinfo AntennaRatio); std::vector<int> GetAntennaRatio(std::string path); void load_antenna_rules(); void check_antenna_cell(); void check_antennas(std::string report_filename); bool check_violation(PARinfo par_info, dbTechLayer* layer); void find_wireroot_iterms(dbWireGraph::Node* node, int wire_level, std::vector<dbITerm*>& gates); std::vector<std::pair<double, std::vector<dbITerm*>>> PAR_max_wire_length( dbNet* net, int layer); void check_max_length(const char *net_name, int layer); std::vector<VINFO> get_net_antenna_violations(dbNet* net, std::string antenna_cell_name = "", std::string cell_pin = ""); std::vector<std::pair<double, std::vector<dbITerm*>>> get_violated_wire_length(dbNet* net, int routing_level); void find_max_wire_length(); private: odb::dbDatabase* db_; utl::Logger *logger_; FILE* _out; std::map<odb::dbTechLayer*, ANTENNAmodel> layer_info; }; } // namespace ant
// BSD 3-Clause License // // Copyright (c) 2020, MICL, DD-Lab, University of Michigan // 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 holder 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. #pragma once #include <tcl.h> #include <map> #include "opendb/db.h" #include "opendb/dbWireGraph.h" #include "utl/Logger.h" namespace ant { using odb::dbInst; using odb::dbITerm; using odb::dbNet; using odb::dbSWire; using odb::dbTechLayer; using odb::dbWire; using odb::dbWireGraph; using utl::Logger; typedef std::pair<dbWireGraph::Node*, std::vector<dbWireGraph::Node*>> wireroots_info_vec; struct PARinfo { // std::pair<odb::dbWireGraph::Node*, std::vector<odb::dbWireGraph::Node*>> // WirerootNode; odb::dbWireGraph::Node* WirerootNode; std::set<odb::dbITerm*> iterms; double wire_area; double side_wire_area; double iterm_areas[2]; double PAR_value; double PSR_value; double diff_PAR_value; double diff_PSR_value; }; struct ARinfo { odb::dbWireGraph::Node* WirerootNode; odb::dbWireGraph::Node* GateNode; bool violated_net; double PAR_value; double PSR_value; double diff_PAR_value; double diff_PSR_value; double CAR_value; double CSR_value; double diff_CAR_value; double diff_CSR_value; double diff_area; }; struct ANTENNAmodel { odb::dbTechLayer* layer; double metal_factor; double diff_metal_factor; double cut_factor; double diff_cut_factor; double side_metal_factor; double diff_side_metal_factor; double minus_diff_factor; double plus_diff_factor; double diff_metal_reduce_factor; ANTENNAmodel& operator=(const ANTENNAmodel& am) { metal_factor = am.metal_factor; diff_metal_factor = am.diff_metal_factor; cut_factor = am.cut_factor; diff_cut_factor = am.diff_cut_factor; side_metal_factor = am.side_metal_factor; diff_side_metal_factor = am.diff_side_metal_factor; minus_diff_factor = am.minus_diff_factor; plus_diff_factor = am.plus_diff_factor; diff_metal_reduce_factor = am.diff_metal_reduce_factor; return *this; } }; struct VINFO { int routing_level; std::vector<odb::dbITerm*> iterms; int antenna_cell_nums; }; class AntennaChecker { public: AntennaChecker(); ~AntennaChecker(); void init(odb::dbDatabase* db, utl::Logger *logger); dbNet* get_net(std::string net_name); template <class valueType> double defdist(valueType value); // wireroots_info_vec find_segment_root(std::pair<dbWireGraph::Node*, // std::vector<dbWireGraph::Node*>> node_info, int wire_level ); dbWireGraph::Node* find_segment_root(dbWireGraph::Node* node_info, int wire_level); dbWireGraph::Node* find_segment_start(dbWireGraph::Node* node); bool if_segment_root(dbWireGraph::Node* node, int wire_level); void find_wire_below_iterms(dbWireGraph::Node* node, double iterm_areas[2], int wire_level, std::set<dbITerm*>& iv, std::set<dbWireGraph::Node*>& nv); std::pair<double, double> calculate_wire_area( dbWireGraph::Node* node, int wire_level, std::set<dbWireGraph::Node*>& nv, std::set<dbWireGraph::Node*>& level_nodes); double get_via_area(dbWireGraph::Edge* edge); dbTechLayer* get_via_layer(dbWireGraph::Edge* edge); std::string get_via_name(dbWireGraph::Edge* edge); double calculate_via_area(dbWireGraph::Node* node, int wire_level); dbWireGraph::Edge* find_via(dbWireGraph::Node* node, int wire_level); void find_car_path(dbWireGraph::Node* node, int wire_level, dbWireGraph::Node* goal, std::vector<dbWireGraph::Node*>& current_path, std::vector<dbWireGraph::Node*>& path_found); void print_graph_info(dbWireGraph graph); void calculate_PAR_info(PARinfo& PARtable); bool check_iterm(dbWireGraph::Node* node, double iterm_areas[2]); double get_pwl_factor(odb::dbTechLayerAntennaRule::pwl_pair pwl_info, double ref_val, double def); void build_wire_PAR_table(std::vector<PARinfo>& PARtable, std::vector<dbWireGraph::Node*> wireroots_info); void build_wire_CAR_table(std::vector<ARinfo>& CARtable, std::vector<PARinfo> PARtable, std::vector<PARinfo> VIA_PARtable, std::vector<dbWireGraph::Node*> gate_iterms); void build_VIA_PAR_table(std::vector<PARinfo>& VIA_PARtable, std::vector<dbWireGraph::Node*> wireroots_info); void build_VIA_CAR_table(std::vector<ARinfo>& VIA_CARtable, std::vector<PARinfo> PARtable, std::vector<PARinfo> VIA_PARtable, std::vector<dbWireGraph::Node*> gate_iterms); // std::vector<wireroots_info_vec> get_wireroots(dbWireGraph graph); std::vector<dbWireGraph::Node*> get_wireroots(dbWireGraph graph); std::pair<bool, bool> check_wire_PAR(ARinfo AntennaRatio, bool simple_report, bool print); std::pair<bool, bool> check_wire_CAR(ARinfo AntennaRatio, bool par_checked, bool simple_report, bool print); bool check_VIA_PAR(ARinfo AntennaRatio, bool simple_report, bool print); bool check_VIA_CAR(ARinfo AntennaRatio, bool simple_report, bool print); std::vector<int> GetAntennaRatio(std::string path, bool simple_report); void load_antenna_rules(); void check_antenna_cell(); void check_antennas(std::string report_filename, bool simple_report); bool check_violation(PARinfo par_info, dbTechLayer* layer); void find_wireroot_iterms(dbWireGraph::Node* node, int wire_level, std::vector<dbITerm*>& gates); std::vector<std::pair<double, std::vector<dbITerm*>>> PAR_max_wire_length( dbNet* net, int layer); void check_max_length(const char *net_name, int layer); std::vector<VINFO> get_net_antenna_violations(dbNet* net, std::string antenna_cell_name = "", std::string cell_pin = ""); std::vector<std::pair<double, std::vector<dbITerm*>>> get_violated_wire_length(dbNet* net, int routing_level); void find_max_wire_length(); private: odb::dbDatabase* db_; utl::Logger *logger_; FILE* _out; std::map<odb::dbTechLayer*, ANTENNAmodel> layer_info; }; } // namespace ant
update AntennaChecker.hh
update AntennaChecker.hh
C++
bsd-3-clause
The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD
6380b2087aa1bcf72a64fc64d7f78b7f725009ff
src/connection.cc
src/connection.cc
#include <errno.h> #include "connection.h" #include "btio.h" #include "btleException.h" // Struct for write callbacks struct writeData { writeData() : connection(NULL), data(NULL), callback(NULL) {} Connection* connection; void* data; Connection::writeCallback callback; }; // Constructor Connection::Connection() : sock(0), tcp(NULL), poll_handle(NULL), imtu(0), cid(0), readCb(NULL), readData(NULL), errorCb(NULL), errorData(NULL) { } // Destructor Connection::~Connection() { delete this->tcp; delete this->poll_handle; } // Struct for connection callbacks struct connectData { connectData() : conn(NULL), callback(NULL), data(NULL) {} Connection* conn; Connection::connectCallback callback; void* data; }; // // Connect to the Bluetooth device // Arguments: // opts - Connection options // connect - Connect callback // data - Optional callback data // void Connection::connect(struct set_opts& opts, connectCallback connect, void* data) { this->sock = bt_io_connect(&opts); if (this->sock == -1) { // Throw exception throw BTLEException("Error connecting", errno); } struct connectData* cd = new struct connectData(); cd->callback = connect; cd->data = data; cd->conn = this; this->poll_handle = new uv_poll_t; this->poll_handle->data = cd; uv_poll_init_socket(uv_default_loop(), this->poll_handle, this->sock); uv_poll_start(this->poll_handle, UV_WRITABLE, onConnect); } // Register a read callback void Connection::registerReadCallback(readCallback callback, void* cbData) { this->readCb = callback; this->readData = cbData; } // Register an error callback void Connection::registerErrorCallback(errorCallback callback, void* cbData) { this->errorCb = callback; this->errorData = cbData; } // Write to the device void Connection::write(uv_buf_t& buffer, writeCallback callback, void* cbData) { uv_write_t* req = new uv_write_t(); if (callback != NULL) { struct writeData* wd = new struct writeData(); wd->connection = this; wd->data = cbData; wd->callback = callback; req->data = wd; } uv_write(req, getStream(), &buffer, 1, callback == NULL ? NULL : onWrite); } // Struct for close callbacks struct closeData { closeData() : callback(NULL), data(NULL) {} Connection::closeCallback callback; void* data; }; // // Close the connection // Arguments: // cb - Close callback // data - Optional callback data // void Connection::close(closeCallback cb, void* data) { if (this->tcp) { struct closeData* cd = new struct closeData(); cd->callback = cb; cd->data = data; uv_close((uv_handle_t*) this->tcp, onClose); delete this->tcp; this->tcp = NULL; } } // // Internal Callbacks, mostly just call the passed-in callbacks // // // Write callback // void Connection::onWrite(uv_write_t* req, int status) { struct writeData* wd = (struct writeData*) req->data; if (status < 0) { Connection* conn = wd->connection; if (conn->errorCb) { // We call the callback and let it decide whether to close the // connection uv_err_t err = uv_last_error(uv_default_loop()); conn->errorCb(conn->errorData, uv_strerror(err)); } else { // If no error callback, close the connection on error conn->close(NULL, NULL); // TODO: Throw an exception? } } else { if (wd->callback) wd->callback(wd->data, status); } } // // Close callback // void Connection::onClose(uv_handle_t* handle) { struct closeData* cd = static_cast<struct closeData*>(handle->data); if (cd && cd->callback) cd->callback(cd->data); } // // Read callback // void Connection::onRead(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) { Connection* conn = static_cast<Connection*>(stream->data); // nread < 0 signals an error if (nread < 0) { if (conn->errorCb) { // We call the callback and let it decide whether to close the // connection uv_err_t err = uv_last_error(uv_default_loop()); conn->errorCb(conn->errorData, uv_strerror(err)); } else { // If no error callback, close the connection on error conn->close(NULL, NULL); // TODO: Throw an exception? } } else { if (conn->readCb != NULL) { conn->readCb(conn->readData, (uint8_t*) buf.base, nread); } } delete buf.base; } // // Connect callback // void Connection::onConnect(uv_poll_t* handle, int status, int events) { // Stop polling uv_poll_stop(handle); struct connectData* cd = static_cast<struct connectData*>(handle->data); // Need to do this, otherwise onClose will crash handle->data = NULL; uv_close((uv_handle_t*) handle, onClose); Connection* conn = cd->conn; if (status == 0) { // Get our socket int fd = handle->io_watcher.fd; // Get the CID and MTU information bt_io_get(fd, BT_IO_OPT_IMTU, &conn->imtu, BT_IO_OPT_CID, &conn->cid, BT_IO_OPT_INVALID); // Convert the socket to a TCP handle, and start reading conn->tcp = new uv_tcp_t(); uv_tcp_init(uv_default_loop(), conn->tcp); uv_tcp_open(conn->tcp, fd); conn->tcp->data = (void*) conn; uv_read_start((uv_stream_t*) conn->tcp, onAlloc, onRead); } cd->callback(cd->data, status, events); } // // Get a buffer of the right size to send to device // uv_buf_t Connection::getBuffer() { size_t bufSize = (this->cid == ATT_CID) ? ATT_DEFAULT_LE_MTU : this->imtu; return uv_buf_init(new char[bufSize], bufSize); } // // libuv allocation callback // uv_buf_t Connection::onAlloc(uv_handle_t* handle, size_t suggested) { return uv_buf_init(new char[suggested], suggested); }
#include <errno.h> #include "connection.h" #include "btio.h" #include "btleException.h" // Struct for write callbacks struct writeData { writeData() : connection(NULL), data(NULL), callback(NULL) {} Connection* connection; void* data; Connection::writeCallback callback; }; // Constructor Connection::Connection() : sock(0), tcp(NULL), poll_handle(NULL), imtu(0), cid(0), readCb(NULL), readData(NULL), errorCb(NULL), errorData(NULL) { } // Destructor Connection::~Connection() { delete this->tcp; delete this->poll_handle; } // Struct for connection callbacks struct connectData { connectData() : conn(NULL), callback(NULL), data(NULL) {} Connection* conn; Connection::connectCallback callback; void* data; }; // // Connect to the Bluetooth device // Arguments: // opts - Connection options // connect - Connect callback // data - Optional callback data // void Connection::connect(struct set_opts& opts, connectCallback connect, void* data) { this->sock = bt_io_connect(&opts); if (this->sock == -1) { // Throw exception throw BTLEException("Error connecting", errno); } struct connectData* cd = new struct connectData(); cd->callback = connect; cd->data = data; cd->conn = this; this->poll_handle = new uv_poll_t; this->poll_handle->data = cd; uv_poll_init_socket(uv_default_loop(), this->poll_handle, this->sock); uv_poll_start(this->poll_handle, UV_WRITABLE, onConnect); } // Register a read callback void Connection::registerReadCallback(readCallback callback, void* cbData) { this->readCb = callback; this->readData = cbData; } // Register an error callback void Connection::registerErrorCallback(errorCallback callback, void* cbData) { this->errorCb = callback; this->errorData = cbData; } // Write to the device void Connection::write(uv_buf_t& buffer, writeCallback callback, void* cbData) { uv_write_t* req = new uv_write_t(); if (callback != NULL) { struct writeData* wd = new struct writeData(); wd->connection = this; wd->data = cbData; wd->callback = callback; req->data = wd; } uv_write(req, getStream(), &buffer, 1, callback == NULL ? NULL : onWrite); } // Struct for close callbacks struct closeData { closeData() : callback(NULL), data(NULL) {} Connection::closeCallback callback; void* data; }; // // Close the connection // Arguments: // cb - Close callback // data - Optional callback data // void Connection::close(closeCallback cb, void* data) { if (this->tcp) { struct closeData* cd = new struct closeData(); cd->callback = cb; cd->data = data; this->tcp->data = cd; uv_close((uv_handle_t*) this->tcp, onClose); } } // // Internal Callbacks, mostly just call the passed-in callbacks // // // Write callback // void Connection::onWrite(uv_write_t* req, int status) { struct writeData* wd = (struct writeData*) req->data; if (status < 0) { Connection* conn = wd->connection; if (conn->errorCb) { // We call the callback and let it decide whether to close the // connection uv_err_t err = uv_last_error(uv_default_loop()); conn->errorCb(conn->errorData, uv_strerror(err)); } else { // If no error callback, close the connection on error conn->close(NULL, NULL); // TODO: Throw an exception? } } else { if (wd->callback) wd->callback(wd->data, status); } } // // Close callback // void Connection::onClose(uv_handle_t* handle) { struct closeData* cd = static_cast<struct closeData*>(handle->data); if (cd && cd->callback) cd->callback(cd->data); } // // Read callback // void Connection::onRead(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) { Connection* conn = static_cast<Connection*>(stream->data); // nread < 0 signals an error if (nread < 0) { if (conn->errorCb) { // We call the callback and let it decide whether to close the // connection uv_err_t err = uv_last_error(uv_default_loop()); conn->errorCb(conn->errorData, uv_strerror(err)); } else { // If no error callback, close the connection on error conn->close(NULL, NULL); // TODO: Throw an exception? } } else { if (conn->readCb != NULL) { conn->readCb(conn->readData, (uint8_t*) buf.base, nread); } } delete buf.base; } // // Connect callback // void Connection::onConnect(uv_poll_t* handle, int status, int events) { // Stop polling uv_poll_stop(handle); struct connectData* cd = static_cast<struct connectData*>(handle->data); // Need to do this, otherwise onClose will crash handle->data = NULL; uv_close((uv_handle_t*) handle, onClose); Connection* conn = cd->conn; if (status == 0) { // Get our socket int fd = handle->io_watcher.fd; // Get the CID and MTU information bt_io_get(fd, BT_IO_OPT_IMTU, &conn->imtu, BT_IO_OPT_CID, &conn->cid, BT_IO_OPT_INVALID); // Convert the socket to a TCP handle, and start reading conn->tcp = new uv_tcp_t(); uv_tcp_init(uv_default_loop(), conn->tcp); uv_tcp_open(conn->tcp, fd); conn->tcp->data = (void*) conn; uv_read_start((uv_stream_t*) conn->tcp, onAlloc, onRead); } cd->callback(cd->data, status, events); } // // Get a buffer of the right size to send to device // uv_buf_t Connection::getBuffer() { size_t bufSize = (this->cid == ATT_CID) ? ATT_DEFAULT_LE_MTU : this->imtu; return uv_buf_init(new char[bufSize], bufSize); } // // libuv allocation callback // uv_buf_t Connection::onAlloc(uv_handle_t* handle, size_t suggested) { return uv_buf_init(new char[suggested], suggested); }
Fix for segfault when closing the connection
Fix for segfault when closing the connection
C++
mit
hybridgroup/btle.js,hybridgroup/btle.js,hybridgroup/btle.js,jacklund/btle.js,jacklund/btle.js,hybridgroup/btle.js,jacklund/btle.js,jacklund/btle.js
cd636d0a7f161df3c754b4836e064ae60ee21569
src/map/src/items/inventory.cpp
src/map/src/items/inventory.cpp
#include "items/inventory.h" #include "entity_system.h" #include "dataconsts.h" #include "random.h" #include "components/basic_info.h" #include "components/inventory.h" #include "components/item.h" #include "components/lua.h" #include "components/position.h" #include "components/owner.h" #include "itemdb.h" #include "srv_equip_item.h" #include "srv_set_item.h" #include "srv_set_money.h" #include <limits> using namespace RoseCommon; using namespace Items; namespace { // only for items, not cart/castle gear inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) { const auto& item = entitySystem.get_component<ItemDef>(entity); const EquippedPosition pos = static_cast<EquippedPosition>(spot); if (pos >= EquippedPosition::MAX_EQUIP_ITEMS) { return true; // we don't care of the spot if we are not equipping anything } switch (item.type) { case ItemType::ITEM_GOGGLES: return pos == EquippedPosition::GOGGLES; case ItemType::ITEM_HELMET: return pos == EquippedPosition::HELMET; case ItemType::ITEM_ARMOR: return pos == EquippedPosition::ARMOR; case ItemType::ITEM_GAUNTLET: return pos == EquippedPosition::GAUNTLET; case ItemType::ITEM_BOOTS: return pos == EquippedPosition::BOOTS; case ItemType::ITEM_BACKPACK: return pos == EquippedPosition::BACKPACK; case ItemType::ITEM_RING: return pos == EquippedPosition::RING; case ItemType::ITEM_WEAPON_R: return pos == EquippedPosition::WEAPON_R; case ItemType::ITEM_WEAPON_L: return pos == EquippedPosition::WEAPON_L; default: return false; } } inline bool is_spot_equipped(size_t spot) { return spot < EquippedPosition::MAX_EQUIP_ITEMS; } } size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); size_t res = decltype(inv.getInventory())::offset(); bool stackable = false; ItemType type = ItemType::NONE; uint16_t id = 0; if (item != entt::null) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); stackable = i.is_stackable; type = i.type; id = i.id; } for (const auto item : inv.getInventory()) { if (item == entt::null) { return res; } else if (stackable) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); const auto& it = entitySystem.get_component<Component::Item>(item); if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) { return res; } } ++res; } return 0; } ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const size_t pos = get_first_available_spot(entitySystem, entity, item); if (pos == 0) { return ReturnValue::NO_SPACE; } auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (inv.items[pos] == entt::null) { inv.items[pos] = item; } else { // add the stack auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]); auto& it = entitySystem.get_component<Component::Item>(item); if (i.count + it.count < RoseCommon::MAX_STACK) { // below max stack i.count += it.count; } else { // split the stack in two or more const uint32_t stack_tmp1 = i.count; const uint32_t stack_tmp2 = it.count; it.count -= RoseCommon::MAX_STACK - i.count; i.count = RoseCommon::MAX_STACK; if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) { it.count = stack_tmp2; i.count = stack_tmp1; return ReturnValue::NO_SPACE; } } } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); RoseCommon::Entity item = inv.items[pos]; auto& i = entitySystem.get_component<Component::Item>(item); const auto& it = entitySystem.get_component<ItemDef>(item); if (i.count < quantity) { return entt::null; } if (i.count > quantity) { const auto type = it.type; const auto id = it.id; i.count -= quantity; RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity); RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return newItem; } if (is_spot_equipped(pos)) { const auto& lua = entitySystem.get_component<Component::ItemLua>(item); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(item)) { return entt::null; } } } inv.items[pos] = entt::null; RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return item; } void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); std::swap(inv.items[pos1], inv.items[pos2]); } ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) { return ReturnValue::WRONG_INDEX; } if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[to]; const RoseCommon::Entity to_equip = inv.items[from]; if (!is_spot_correct(entitySystem, to_equip, to)) { return ReturnValue::REQUIREMENTS_NOT_MET; } if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } if (from != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_equip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to])); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) { const size_t to = get_first_available_spot(entitySystem, entity); if (to == 0) { return ReturnValue::NO_SPACE; } const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[from]; if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {}); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item({}); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) { Component::BasicInfo bi; bi.id = entitySystem.get_free_id(); if (owner != entt::null) { const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner); bi.teamId = basicInfo.teamId; auto& Cowner = entitySystem.add_component<Component::Owner>(item); Cowner.owner = owner; } else { bi.teamId = bi.id; } entitySystem.add_component(item, std::move(bi)); entitySystem.update_position(item, x, y); entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) { entitySystem.delete_entity(item); }); } void Items::pickup_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const float x = entitySystem.get_component<Component::Position>(item).x; const float y = entitySystem.get_component<Component::Position>(item).y; const auto* owner = entitySystem.try_get_component<Component::Owner>(item); entitySystem.remove_component<Component::Position>(item); if (Items::add_item(entitySystem, entity, item) != ReturnValue::OK) { const RoseCommon::Entity owner = owner ? owner->owner : entt::null; Items::drop_item(entitySystem, item, x, y, owner); } } bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (zuly < 0 && inv.zuly + zuly < 0) { return false; } else if (zuly < 0) { inv.zuly += zuly; } else { inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly), static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))); } entitySystem.send_to(entity, RoseCommon::Packet::SrvSetMoney::create(inv.zuly)); return true; } void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo()); const auto from = packet.get_slotFrom(); const auto to = packet.get_slotTo(); const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag unequip_item(entitySystem, entity, to): equip_item(entitySystem, entity, from, to); (void) res; } void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity()); const auto index = packet.get_index(); const auto quantity = packet.get_quantity(); const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (index > inv.items.size()) { logger->warn("wrong index {} for item drop, client {}", index, entity); return; } RoseCommon::Entity item = entt::null; if (index == 0) { // we drop zulies if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) { item = entitySystem.create_zuly(packet.get_quantity()); } else { return; // we don't have enough zuly to remove } } else { item = remove_item(entitySystem, entity, index, quantity); } const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE); drop_item(entitySystem, item, x, y, entity); }
#include "items/inventory.h" #include "entity_system.h" #include "dataconsts.h" #include "random.h" #include "components/basic_info.h" #include "components/inventory.h" #include "components/item.h" #include "components/lua.h" #include "components/position.h" #include "components/owner.h" #include "itemdb.h" #include "srv_equip_item.h" #include "srv_set_item.h" #include "srv_set_money.h" #include <limits> using namespace RoseCommon; using namespace Items; namespace { // only for items, not cart/castle gear inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) { const auto& item = entitySystem.get_component<ItemDef>(entity); const EquippedPosition pos = static_cast<EquippedPosition>(spot); if (pos >= EquippedPosition::MAX_EQUIP_ITEMS) { return true; // we don't care of the spot if we are not equipping anything } switch (item.type) { case ItemType::ITEM_GOGGLES: return pos == EquippedPosition::GOGGLES; case ItemType::ITEM_HELMET: return pos == EquippedPosition::HELMET; case ItemType::ITEM_ARMOR: return pos == EquippedPosition::ARMOR; case ItemType::ITEM_GAUNTLET: return pos == EquippedPosition::GAUNTLET; case ItemType::ITEM_BOOTS: return pos == EquippedPosition::BOOTS; case ItemType::ITEM_BACKPACK: return pos == EquippedPosition::BACKPACK; case ItemType::ITEM_RING: return pos == EquippedPosition::RING; case ItemType::ITEM_WEAPON_R: return pos == EquippedPosition::WEAPON_R; case ItemType::ITEM_WEAPON_L: return pos == EquippedPosition::WEAPON_L; default: return false; } } inline bool is_spot_equipped(size_t spot) { return spot < EquippedPosition::MAX_EQUIP_ITEMS; } } size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); size_t res = decltype(inv.getInventory())::offset(); bool stackable = false; ItemType type = ItemType::NONE; uint16_t id = 0; if (item != entt::null) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); stackable = i.is_stackable; type = i.type; id = i.id; } for (const auto item : inv.getInventory()) { if (item == entt::null) { return res; } else if (stackable) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); const auto& it = entitySystem.get_component<Component::Item>(item); if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) { return res; } } ++res; } return 0; } ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const size_t pos = get_first_available_spot(entitySystem, entity, item); if (pos == 0) { return ReturnValue::NO_SPACE; } auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (inv.items[pos] == entt::null) { inv.items[pos] = item; } else { // add the stack auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]); auto& it = entitySystem.get_component<Component::Item>(item); if (i.count + it.count < RoseCommon::MAX_STACK) { // below max stack i.count += it.count; } else { // split the stack in two or more const uint32_t stack_tmp1 = i.count; const uint32_t stack_tmp2 = it.count; it.count -= RoseCommon::MAX_STACK - i.count; i.count = RoseCommon::MAX_STACK; if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) { it.count = stack_tmp2; i.count = stack_tmp1; return ReturnValue::NO_SPACE; } } } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); RoseCommon::Entity item = inv.items[pos]; auto& i = entitySystem.get_component<Component::Item>(item); const auto& it = entitySystem.get_component<ItemDef>(item); if (i.count < quantity) { return entt::null; } if (i.count > quantity) { const auto type = it.type; const auto id = it.id; i.count -= quantity; RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity); RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return newItem; } if (is_spot_equipped(pos)) { const auto& lua = entitySystem.get_component<Component::ItemLua>(item); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(item)) { return entt::null; } } } inv.items[pos] = entt::null; RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return item; } void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); std::swap(inv.items[pos1], inv.items[pos2]); } ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) { return ReturnValue::WRONG_INDEX; } if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[to]; const RoseCommon::Entity to_equip = inv.items[from]; if (!is_spot_correct(entitySystem, to_equip, to)) { return ReturnValue::REQUIREMENTS_NOT_MET; } if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } if (from != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_equip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to])); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) { const size_t to = get_first_available_spot(entitySystem, entity); if (to == 0) { return ReturnValue::NO_SPACE; } const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[from]; if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {}); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item({}); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) { Component::BasicInfo bi; bi.id = entitySystem.get_free_id(); if (owner != entt::null) { const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner); bi.teamId = basicInfo.teamId; auto& Cowner = entitySystem.add_component<Component::Owner>(item); Cowner.owner = owner; } else { bi.teamId = bi.id; } entitySystem.add_component(item, std::move(bi)); entitySystem.update_position(item, x, y); entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) { entitySystem.delete_entity(item); }); } void Items::pickup_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const float x = entitySystem.get_component<Component::Position>(item).x; const float y = entitySystem.get_component<Component::Position>(item).y; const auto* owner = entitySystem.try_get_component<Component::Owner>(item); entitySystem.remove_component<Component::Position>(item); entitySystem.remove_component<Component::BasicInfo>(item); if (Items::add_item(entitySystem, entity, item) != ReturnValue::OK) { const RoseCommon::Entity owner = owner ? owner->owner : entt::null; Items::drop_item(entitySystem, item, x, y, owner); } } bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (zuly < 0 && inv.zuly + zuly < 0) { return false; } else if (zuly < 0) { inv.zuly += zuly; } else { inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly), static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))); } entitySystem.send_to(entity, RoseCommon::Packet::SrvSetMoney::create(inv.zuly)); return true; } void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo()); const auto from = packet.get_slotFrom(); const auto to = packet.get_slotTo(); const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag unequip_item(entitySystem, entity, to): equip_item(entitySystem, entity, from, to); (void) res; } void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity()); const auto index = packet.get_index(); const auto quantity = packet.get_quantity(); const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (index > inv.items.size()) { logger->warn("wrong index {} for item drop, client {}", index, entity); return; } RoseCommon::Entity item = entt::null; if (index == 0) { // we drop zulies if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) { item = entitySystem.create_zuly(packet.get_quantity()); } else { return; // we don't have enough zuly to remove } } else { item = remove_item(entitySystem, entity, index, quantity); } const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE); drop_item(entitySystem, item, x, y, entity); }
Update inventory.cpp
Update inventory.cpp
C++
apache-2.0
RavenX8/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new,dev-osrose/osIROSE-new,dev-osrose/osIROSE-new,RavenX8/osIROSE-new
5d10a264de17df801e893df2d1e2725c78162179
src/rt/rust.cpp
src/rt/rust.cpp
#include "rust_internal.h" #include "util/array_list.h" // #define TRACK_ALLOCATIONS // For debugging, keeps track of live allocations, so you can find out // exactly what leaked. #ifdef TRACK_ALLOCATIONS array_list<void *> allocation_list; #endif rust_srv::rust_srv() : live_allocs(0) { } rust_srv::~rust_srv() { if (live_allocs != 0) { char msg[128]; snprintf(msg, sizeof(msg), "leaked memory in rust main loop (%" PRIuPTR " objects)", live_allocs); #ifdef TRACK_ALLOCATIONS for (size_t i = 0; i < allocation_list.size(); i++) { if (allocation_list[i] != NULL) { printf("allocation 0x%" PRIxPTR " was not freed\n", (uintptr_t) allocation_list[i]); } } #endif fatal(msg, __FILE__, __LINE__); } } void rust_srv::log(char const *str) { printf("rt: %s\n", str); } void * rust_srv::malloc(size_t bytes) { ++live_allocs; void * val = ::malloc(bytes); #ifdef TRACK_ALLOCATIONS allocation_list.append(val); #endif return val; } void * rust_srv::realloc(void *p, size_t bytes) { if (!p) { live_allocs++; } void * val = ::realloc(p, bytes); #ifdef TRACK_ALLOCATIONS if (allocation_list.replace(p, val) == NULL) { fatal("not in allocation_list", __FILE__, __LINE__); } #endif return val; } void rust_srv::free(void *p) { if (live_allocs < 1) { fatal("live_allocs < 1", __FILE__, __LINE__); } live_allocs--; ::free(p); #ifdef TRACK_ALLOCATIONS if (allocation_list.replace(p, NULL) == NULL) { fatal("not in allocation_list", __FILE__, __LINE__); } #endif } void rust_srv::fatal(char const *expr, char const *file, size_t line) { char buf[1024]; snprintf(buf, sizeof(buf), "fatal, '%s' failed, %s:%d", expr, file, (int)line); log(buf); exit(1); } rust_srv * rust_srv::clone() { return new rust_srv(); } int rust_main_loop(rust_dom *dom) { // Make sure someone is watching, to pull us out of infinite loops. rust_timer timer(*dom); int rval; rust_task *task; dom->log(rust_log::DOM, "running main-loop on domain 0x%" PRIxPTR, dom); dom->logptr("exit-task glue", dom->root_crate->get_exit_task_glue()); while ((task = dom->sched()) != NULL) { I(dom, task->running()); dom->log(rust_log::TASK, "activating task 0x%" PRIxPTR ", sp=0x%" PRIxPTR, (uintptr_t)task, task->rust_sp); dom->interrupt_flag = 0; dom->activate(task); dom->log(rust_log::TASK, "returned from task 0x%" PRIxPTR " in state '%s', sp=0x%" PRIxPTR, (uintptr_t)task, dom->state_vec_name(task->state), task->rust_sp); I(dom, task->rust_sp >= (uintptr_t) &task->stk->data[0]); I(dom, task->rust_sp < task->stk->limit); dom->reap_dead_tasks(); } dom->log(rust_log::DOM, "finished main-loop (dom.rval = %d)", dom->rval); rval = dom->rval; return rval; } struct command_line_args { rust_dom &dom; int argc; char **argv; // vec[str] passed to rust_task::start. rust_vec *args; command_line_args(rust_dom &dom, int sys_argc, char **sys_argv) : dom(dom), argc(sys_argc), argv(sys_argv), args(NULL) { #if defined(__WIN32__) LPCWSTR cmdline = GetCommandLineW(); LPWSTR *wargv = CommandLineToArgvW(cmdline, &argc); dom.win32_require("CommandLineToArgvW", wargv != NULL); argv = (char **) dom.malloc(sizeof(char*) * argc); for (int i = 0; i < argc; ++i) { int n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL); dom.win32_require("WideCharToMultiByte(0)", n_chars != 0); argv[i] = (char *) dom.malloc(n_chars); n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], n_chars, NULL, NULL); dom.win32_require("WideCharToMultiByte(1)", n_chars != 0); } LocalFree(wargv); #endif size_t vec_fill = sizeof(rust_str *) * argc; size_t vec_alloc = next_power_of_two(sizeof(rust_vec) + vec_fill); void *mem = dom.malloc(vec_alloc); args = new (mem) rust_vec(&dom, vec_alloc, 0, NULL); rust_str **strs = (rust_str**) &args->data[0]; for (int i = 0; i < argc; ++i) { size_t str_fill = strlen(argv[i]) + 1; size_t str_alloc = next_power_of_two(sizeof(rust_str) + str_fill); mem = dom.malloc(str_alloc); strs[i] = new (mem) rust_str(&dom, str_alloc, str_fill, (uint8_t const *)argv[i]); } args->fill = vec_fill; // If the caller has a declared args array, they may drop; but // we don't know if they have such an array. So we pin the args // array here to ensure it survives to program-shutdown. args->ref(); } ~command_line_args() { if (args) { // Drop the args we've had pinned here. rust_str **strs = (rust_str**) &args->data[0]; for (int i = 0; i < argc; ++i) dom.free(strs[i]); dom.free(args); } #ifdef __WIN32__ for (int i = 0; i < argc; ++i) { dom.free(argv[i]); } dom.free(argv); #endif } }; extern "C" CDECL int rust_start(uintptr_t main_fn, rust_crate const *crate, int argc, char **argv) { int ret; { rust_srv srv; rust_dom dom(&srv, crate); command_line_args args(dom, argc, argv); dom.log(rust_log::DOM, "startup: %d args", args.argc); for (int i = 0; i < args.argc; ++i) dom.log(rust_log::DOM, "startup: arg[%d] = '%s'", i, args.argv[i]); if (dom._log.is_tracing(rust_log::DWARF)) { rust_crate_reader rdr(&dom, crate); } uintptr_t main_args[3] = { 0, 0, (uintptr_t)args.args }; dom.root_task->start(crate->get_exit_task_glue(), main_fn, (uintptr_t)&main_args, sizeof(main_args)); ret = rust_main_loop(&dom); } #if !defined(__WIN32__) // Don't take down the process if the main thread exits without an // error. if (!ret) pthread_exit(NULL); #endif return ret; } // // Local Variables: // mode: C++ // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End: //
#include "rust_internal.h" #include "util/array_list.h" // #define TRACK_ALLOCATIONS // For debugging, keeps track of live allocations, so you can find out // exactly what leaked. #ifdef TRACK_ALLOCATIONS array_list<void *> allocation_list; #endif rust_srv::rust_srv() : live_allocs(0) { } rust_srv::~rust_srv() { if (live_allocs != 0) { char msg[128]; snprintf(msg, sizeof(msg), "leaked memory in rust main loop (%" PRIuPTR " objects)", live_allocs); #ifdef TRACK_ALLOCATIONS for (size_t i = 0; i < allocation_list.size(); i++) { if (allocation_list[i] != NULL) { printf("allocation 0x%" PRIxPTR " was not freed\n", (uintptr_t) allocation_list[i]); } } #endif fatal(msg, __FILE__, __LINE__); } } void rust_srv::log(char const *str) { printf("rt: %s\n", str); } void * rust_srv::malloc(size_t bytes) { ++live_allocs; void * val = ::malloc(bytes); #ifdef TRACK_ALLOCATIONS allocation_list.append(val); #endif return val; } void * rust_srv::realloc(void *p, size_t bytes) { if (!p) { live_allocs++; } void * val = ::realloc(p, bytes); #ifdef TRACK_ALLOCATIONS if (allocation_list.replace(p, val) == NULL) { fatal("not in allocation_list", __FILE__, __LINE__); } #endif return val; } void rust_srv::free(void *p) { if (live_allocs < 1) { fatal("live_allocs < 1", __FILE__, __LINE__); } live_allocs--; ::free(p); #ifdef TRACK_ALLOCATIONS if (allocation_list.replace(p, NULL) == NULL) { fatal("not in allocation_list", __FILE__, __LINE__); } #endif } void rust_srv::fatal(char const *expr, char const *file, size_t line) { char buf[1024]; snprintf(buf, sizeof(buf), "fatal, '%s' failed, %s:%d", expr, file, (int)line); log(buf); exit(1); } rust_srv * rust_srv::clone() { return new rust_srv(); } int rust_main_loop(rust_dom *dom) { // Make sure someone is watching, to pull us out of infinite loops. rust_timer timer(*dom); int rval; rust_task *task; dom->log(rust_log::DOM, "running main-loop on domain 0x%" PRIxPTR, dom); dom->logptr("exit-task glue", dom->root_crate->get_exit_task_glue()); while ((task = dom->sched()) != NULL) { I(dom, task->running()); dom->log(rust_log::TASK, "activating task 0x%" PRIxPTR ", sp=0x%" PRIxPTR, (uintptr_t)task, task->rust_sp); dom->interrupt_flag = 0; dom->activate(task); dom->log(rust_log::TASK, "returned from task 0x%" PRIxPTR " in state '%s', sp=0x%" PRIxPTR, (uintptr_t)task, dom->state_vec_name(task->state), task->rust_sp); I(dom, task->rust_sp >= (uintptr_t) &task->stk->data[0]); I(dom, task->rust_sp < task->stk->limit); dom->reap_dead_tasks(); } dom->log(rust_log::DOM, "finished main-loop (dom.rval = %d)", dom->rval); rval = dom->rval; return rval; } struct command_line_args { rust_dom &dom; int argc; char **argv; // vec[str] passed to rust_task::start. rust_vec *args; command_line_args(rust_dom &dom, int sys_argc, char **sys_argv) : dom(dom), argc(sys_argc), argv(sys_argv), args(NULL) { #if defined(__WIN32__) LPCWSTR cmdline = GetCommandLineW(); LPWSTR *wargv = CommandLineToArgvW(cmdline, &argc); dom.win32_require("CommandLineToArgvW", wargv != NULL); argv = (char **) dom.malloc(sizeof(char*) * argc); for (int i = 0; i < argc; ++i) { int n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL); dom.win32_require("WideCharToMultiByte(0)", n_chars != 0); argv[i] = (char *) dom.malloc(n_chars); n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], n_chars, NULL, NULL); dom.win32_require("WideCharToMultiByte(1)", n_chars != 0); } LocalFree(wargv); #endif size_t vec_fill = sizeof(rust_str *) * argc; size_t vec_alloc = next_power_of_two(sizeof(rust_vec) + vec_fill); void *mem = dom.malloc(vec_alloc); args = new (mem) rust_vec(&dom, vec_alloc, 0, NULL); rust_str **strs = (rust_str**) &args->data[0]; for (int i = 0; i < argc; ++i) { size_t str_fill = strlen(argv[i]) + 1; size_t str_alloc = next_power_of_two(sizeof(rust_str) + str_fill); mem = dom.malloc(str_alloc); strs[i] = new (mem) rust_str(&dom, str_alloc, str_fill, (uint8_t const *)argv[i]); } args->fill = vec_fill; // If the caller has a declared args array, they may drop; but // we don't know if they have such an array. So we pin the args // array here to ensure it survives to program-shutdown. args->ref(); } ~command_line_args() { if (args) { // Drop the args we've had pinned here. rust_str **strs = (rust_str**) &args->data[0]; for (int i = 0; i < argc; ++i) dom.free(strs[i]); dom.free(args); } #ifdef __WIN32__ for (int i = 0; i < argc; ++i) { dom.free(argv[i]); } dom.free(argv); #endif } }; extern "C" CDECL int rust_start(uintptr_t main_fn, rust_crate const *crate, int argc, char **argv) { int ret; { rust_srv srv; rust_dom dom(&srv, crate); command_line_args args(dom, argc, argv); dom.log(rust_log::DOM, "startup: %d args", args.argc); for (int i = 0; i < args.argc; ++i) dom.log(rust_log::DOM, "startup: arg[%d] = '%s'", i, args.argv[i]); if (dom._log.is_tracing(rust_log::DWARF)) { rust_crate_reader rdr(&dom, crate); } uintptr_t main_args[4] = { 0, 0, 0, (uintptr_t)args.args }; dom.root_task->start(crate->get_exit_task_glue(), main_fn, (uintptr_t)&main_args, sizeof(main_args)); ret = rust_main_loop(&dom); } #if !defined(__WIN32__) // Don't take down the process if the main thread exits without an // error. if (!ret) pthread_exit(NULL); #endif return ret; } // // Local Variables: // mode: C++ // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End: //
Add another null byte preceding commandline args passed to the root task, in position of closure/obj pointer.
Add another null byte preceding commandline args passed to the root task, in position of closure/obj pointer.
C++
apache-2.0
mdinger/rust,mihneadb/rust,aneeshusa/rust,michaelballantyne/rust-gpu,mahkoh/rust,jroesch/rust,AerialX/rust,cllns/rust,nwin/rust,graydon/rust,SiegeLord/rust,seanrivera/rust,kimroen/rust,AerialX/rust-rt-minimal,nham/rust,cllns/rust,rprichard/rust,ejjeong/rust,0x73/rust,ebfull/rust,pythonesque/rust,arthurprs/rand,reem/rust,emk/rust,SiegeLord/rust,mihneadb/rust,AerialX/rust-rt-minimal,servo/rust,erickt/rust,sarojaba/rust-doc-korean,pczarn/rust,robertg/rust,ejjeong/rust,pshc/rust,l0kod/rust,defuz/rust,GBGamer/rust,andars/rust,aneeshusa/rust,retep998/rand,j16r/rust,KokaKiwi/rust,nham/rust,jashank/rust,jroesch/rust,ktossell/rust,richo/rust,avdi/rust,ebfull/rust,ktossell/rust,defuz/rust,LeoTestard/rust,andars/rust,KokaKiwi/rust,robertg/rust,mahkoh/rust,stepancheg/rust-ide-rust,emk/rust,aneeshusa/rust,ktossell/rust,emk/rust,zubron/rust,j16r/rust,pythonesque/rust,krzysz00/rust,aepsil0n/rust,aneeshusa/rust,reem/rust,untitaker/rust,barosl/rust,huonw/rand,kwantam/rust,quornian/rust,zachwick/rust,emk/rust,nwin/rust,avdi/rust,rohitjoshi/rust,Ryman/rust,jbclements/rust,TheNeikos/rust,erickt/rust,emk/rust,dwillmer/rust,erickt/rust,ruud-v-a/rust,nham/rust,ebfull/rust,kmcallister/rust,pshc/rust,mitsuhiko/rust,mvdnes/rust,XMPPwocky/rust,kwantam/rust,P1start/rust,achanda/rand,kwantam/rust,P1start/rust,seanrivera/rust,vhbit/rust,nham/rust,bombless/rust,cllns/rust,SiegeLord/rust,pczarn/rust,ktossell/rust,mdinger/rust,avdi/rust,victorvde/rust,mdinger/rust,kwantam/rust,pythonesque/rust,stepancheg/rust-ide-rust,pshc/rust,gifnksm/rust,P1start/rust,P1start/rust,TheNeikos/rust,mvdnes/rust,TheNeikos/rust,carols10cents/rust,pelmers/rust,andars/rust,jbclements/rust,quornian/rust,carols10cents/rust,pelmers/rust,zaeleus/rust,SiegeLord/rust,rohitjoshi/rust,shepmaster/rand,zachwick/rust,miniupnp/rust,mitsuhiko/rust,philyoon/rust,servo/rust,kimroen/rust,victorvde/rust,zubron/rust,waynenilsen/rand,stepancheg/rust-ide-rust,gifnksm/rust,SiegeLord/rust,fabricedesre/rust,jbclements/rust,l0kod/rust,gifnksm/rust,aidancully/rust,kmcallister/rust,omasanori/rust,rprichard/rust,sae-bom/rust,LeoTestard/rust,robertg/rust,nwin/rust,0x73/rust,miniupnp/rust,nham/rust,j16r/rust,gifnksm/rust,quornian/rust,aturon/rust,GBGamer/rust,robertg/rust,servo/rust,avdi/rust,graydon/rust,barosl/rust,sarojaba/rust-doc-korean,vhbit/rust,quornian/rust,pshc/rust,philyoon/rust,untitaker/rust,krzysz00/rust,rohitjoshi/rust,aturon/rust,aepsil0n/rust,michaelballantyne/rust-gpu,bombless/rust,rohitjoshi/rust,andars/rust,victorvde/rust,rprichard/rust,nwin/rust,Ryman/rust,defuz/rust,jbclements/rust,aneeshusa/rust,GBGamer/rust,XMPPwocky/rust,mitsuhiko/rust,aturon/rust,TheNeikos/rust,graydon/rust,GBGamer/rust,mihneadb/rust,Ryman/rust,bhickey/rand,0x73/rust,mahkoh/rust,mvdnes/rust,AerialX/rust,andars/rust,jbclements/rust,sae-bom/rust,sae-bom/rust,michaelballantyne/rust-gpu,bombless/rust-docs-chinese,GBGamer/rust,jashank/rust,l0kod/rust,mitsuhiko/rust,zaeleus/rust,jroesch/rust,carols10cents/rust,richo/rust,sarojaba/rust-doc-korean,dwillmer/rust,mihneadb/rust,omasanori/rust,dwillmer/rust,dwillmer/rust,zubron/rust,philyoon/rust,aepsil0n/rust,AerialX/rust-rt-minimal,dwillmer/rust,jroesch/rust,KokaKiwi/rust,pelmers/rust,SiegeLord/rust,aidancully/rust,ktossell/rust,kwantam/rust,servo/rust,seanrivera/rust,ktossell/rust,graydon/rust,zubron/rust,zaeleus/rust,emk/rust,pelmers/rust,mvdnes/rust,cllns/rust,j16r/rust,pelmers/rust,XMPPwocky/rust,mitsuhiko/rust,fabricedesre/rust,SiegeLord/rust,andars/rust,GBGamer/rust,defuz/rust,erickt/rust,rohitjoshi/rust,XMPPwocky/rust,bombless/rust,kmcallister/rust,gifnksm/rust,nham/rust,dwillmer/rust,mitsuhiko/rust,GBGamer/rust,mvdnes/rust,omasanori/rust,ejjeong/rust,untitaker/rust,nwin/rust,zaeleus/rust,j16r/rust,kimroen/rust,kwantam/rust,vhbit/rust,kmcallister/rust,sarojaba/rust-doc-korean,stepancheg/rust-ide-rust,quornian/rust,richo/rust,graydon/rust,ruud-v-a/rust,hauleth/rust,zubron/rust,sae-bom/rust,reem/rust,aneeshusa/rust,rprichard/rust,rprichard/rust,miniupnp/rust,zubron/rust,l0kod/rust,KokaKiwi/rust,hauleth/rust,defuz/rust,ruud-v-a/rust,miniupnp/rust,vhbit/rust,reem/rust,erickt/rust,jashank/rust,kmcallister/rust,kimroen/rust,fabricedesre/rust,graydon/rust,kimroen/rust,barosl/rust,zubron/rust,mahkoh/rust,barosl/rust,fabricedesre/rust,jashank/rust,michaelballantyne/rust-gpu,ruud-v-a/rust,AerialX/rust-rt-minimal,mdinger/rust,pshc/rust,hauleth/rust,kimroen/rust,pshc/rust,pczarn/rust,Ryman/rust,aepsil0n/rust,mvdnes/rust,vhbit/rust,robertg/rust,aturon/rust,pshc/rust,ebfull/rust,richo/rust,ktossell/rust,barosl/rust,avdi/rust,michaelballantyne/rust-gpu,vhbit/rust,pythonesque/rust,pythonesque/rust,jroesch/rust,bombless/rust,stepancheg/rust-ide-rust,richo/rust,mihneadb/rust,l0kod/rust,Ryman/rust,j16r/rust,nwin/rust,l0kod/rust,reem/rust,rohitjoshi/rust,pczarn/rust,philyoon/rust,victorvde/rust,zachwick/rust,pshc/rust,l0kod/rust,kimroen/rust,krzysz00/rust,seanrivera/rust,untitaker/rust,reem/rust,aidancully/rust,mahkoh/rust,nham/rust,servo/rust,quornian/rust,omasanori/rust,jashank/rust,pczarn/rust,jbclements/rust,seanrivera/rust,servo/rust,ebfull/rand,l0kod/rust,fabricedesre/rust,XMPPwocky/rust,mihneadb/rust,jashank/rust,dinfuehr/rust,cllns/rust,LeoTestard/rust,jroesch/rust,mdinger/rust,KokaKiwi/rust,sarojaba/rust-doc-korean,philyoon/rust,XMPPwocky/rust,ejjeong/rust,bombless/rust,hauleth/rust,defuz/rust,aturon/rust,carols10cents/rust,zaeleus/rust,michaelballantyne/rust-gpu,LeoTestard/rust,mdinger/rust,hauleth/rust,richo/rust,dinfuehr/rust,dwillmer/rust,pelmers/rust,ebfull/rust,vhbit/rust,miniupnp/rust,jbclements/rust,aidancully/rust,aepsil0n/rust,LeoTestard/rust,GBGamer/rust,P1start/rust,zachwick/rust,quornian/rust,ruud-v-a/rust,TheNeikos/rust,untitaker/rust,0x73/rust,zaeleus/rust,aturon/rust,barosl/rust,cllns/rust,dinfuehr/rust,krzysz00/rust,bombless/rust,jashank/rust,kmcallister/rust,sae-bom/rust,LeoTestard/rust,aturon/rust,mahkoh/rust,nwin/rust,victorvde/rust,fabricedesre/rust,AerialX/rust,dwillmer/rust,LeoTestard/rust,bluss/rand,robertg/rust,jbclements/rust,emk/rust,AerialX/rust-rt-minimal,miniupnp/rust,miniupnp/rust,sarojaba/rust-doc-korean,KokaKiwi/rust,nwin/rust,erickt/rust,rprichard/rust,pythonesque/rust,carols10cents/rust,servo/rust,AerialX/rust-rt-minimal,pythonesque/rust,miniupnp/rust,0x73/rust,AerialX/rust,untitaker/rust,0x73/rust,P1start/rust,kmcallister/rust,jbclements/rust,jroesch/rust,aidancully/rust,jroesch/rust,P1start/rust,zachwick/rust,krzysz00/rust,0x73/rust,GrahamDennis/rand,jashank/rust,aidancully/rust,ejjeong/rust,zubron/rust,vhbit/rust,gifnksm/rust,mitsuhiko/rust,pczarn/rust,carols10cents/rust,ejjeong/rust,barosl/rust,AerialX/rust,dinfuehr/rust,philyoon/rust,dinfuehr/rust,fabricedesre/rust,ruud-v-a/rust,sarojaba/rust-doc-korean,omasanori/rust,Ryman/rust,stepancheg/rust-ide-rust,AerialX/rust,aepsil0n/rust,omasanori/rust,Ryman/rust,erickt/rust,stepancheg/rust-ide-rust,TheNeikos/rust,sae-bom/rust,j16r/rust,hauleth/rust,pczarn/rust,dinfuehr/rust,victorvde/rust,michaelballantyne/rust-gpu,seanrivera/rust,krzysz00/rust,zachwick/rust,avdi/rust,ebfull/rust
d6b69d7c23326456592fba104a40d3678267d12f
copasi/tex/CStructureParser.cpp
copasi/tex/CStructureParser.cpp
// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/tex/CStructureParser.cpp,v $ // $Revision: 1.6 $ // $Name: $ // $Author: shoops $ // $Date: 2009/01/08 16:07:12 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Written by pwilly on 09.07.08 #include "CStructureParser.h" #include <qstring.h> #include <qregexp.h> //Added by qt3to4: #include <Q3ValueList> #include <iostream> #include "UI/qtUtilities.h" //#include <qvaluelist.h> CStructureParser::CStructureParser(int n) { sumColumns = n; } bool CStructureParser::startDocument() { indent = ""; tex = ""; indexColumns = -1; if (!sumColumns) needToWriteColumnAllignment = false; else needToWriteColumnAllignment = true; return TRUE; } bool CStructureParser::startElement(const QString& /* str1 */, const QString& /* str2 */, const QString& qName, const QXmlAttributes& attr) { tagName = qName; if (qName == "mtable") texHead = "\\begin{array}"; if (qName == "mtr") indexColumns = 0; if (qName == "mtd") { if (indexColumns > 0 && indexColumns < sumColumns - 1) tex += " \\; &"; if (indexColumns == 0 && needToWriteColumnAllignment) texHead += "{"; if (indexColumns < sumColumns && needToWriteColumnAllignment) { if (attr.count()) { if (attr.value("columnalign") == "left") texHead += "l"; else if (attr.value("columnalign") == "center") texHead += "c"; else if (attr.value("columnalign") == "right") texHead += "r"; } else texHead += "c"; } if (indexColumns == sumColumns - 1) { if (needToWriteColumnAllignment) texHead += "}"; needToWriteColumnAllignment = false; } } if (qName == "mfrac") { mListOfUncompletedTags.push_back("mfrac_0"); tex += "\\frac"; } if (qName == "mfenced") { mListOfUncompletedTags.push_back("mfenced"); tex += "\\left("; } if (qName == "msub") { QString &last = mListOfUncompletedTags.last(); // <msub> direct after <mfrac> if (last.contains("mfrac")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); tex += "{"; } // <msub> direct after <mfenced> if (last.contains("mfenced") && (!tex.endsWith("(") && !tex.endsWith("("))) { tex += ", \\, "; } mListOfUncompletedTags.push_back("msub_0"); } if (qName == "msup") { QString &last = mListOfUncompletedTags.last(); // <msup> direct after <mfrac> if (last.contains("mfrac")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); tex += "{"; } // <msup> direct after <mfenced> if (last.contains("mfenced") && (!tex.endsWith("(") && !tex.endsWith("("))) { tex += ", \\, "; } mListOfUncompletedTags.push_back("msup_0"); } if (qName == "mrow") { QString &last = mListOfUncompletedTags.last(); // increase the index if (last.contains("mfrac") || last.contains("msub") || last.contains("msup")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); if (lastUncompletedTags.contains("msub") && idx == 2) tex += "_"; if (lastUncompletedTags.contains("msup") && idx == 2) tex += "^"; } mListOfUncompletedTags.push_back("mrow"); tex += " {"; } if (qName == "mi" || qName == "mn") { QString &last = mListOfUncompletedTags.last(); if (last.contains("mfenced") && (!tex.endsWith("(") && !tex.endsWith("("))) { tex += ", \\, "; } } if (qName == "mi" || qName == "mo" || qName == "mn") { QString &last = mListOfUncompletedTags.last(); if (last.contains("mfrac") || last.contains("msub") || last.contains("msup")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); if (lastUncompletedTags.contains("msub") && idx == 2) tex += "_"; if (lastUncompletedTags.contains("msup") && idx == 2) tex += "^"; } } indent += " "; return TRUE; } bool CStructureParser::characters(const QString& str) { QRegExp rx("\\w"); QString strAux = str.stripWhiteSpace(); int pos = rx.search(strAux); if (pos != -1) { // handling word character within <mrow> ... </mrow> if (tagName == "mrow") { if (strAux.length() > 1) tex += "{\\text{" + strAux + "}}"; else // exactly only one character tex += "{" + strAux + "}"; } // handling word character within <mi> ... </mi> if (tagName == "mi") { if (strAux.contains("\\")) // for, eg., \sin, \cos tex += strAux; else if (strAux.length() > 1) { if (strAux == "sech" || strAux == "csch" || strAux == "arcsec" || strAux == "arccsc" || strAux == "arccot" || strAux == "arcsinh" || strAux == "arccosh" || strAux == "arctanh" || strAux == "arcsech" || strAux == "arccsch" || strAux == "arccoth") tex += "{\\mathrm{" + strAux + " \\: }}"; else tex += "{\\mathrm{" + strAux + "}}"; } else // exactly only one character tex += "{" + strAux + "}"; } // handling word character within <mo> ... </mo> if (tagName == "mo") { if (strAux.contains("\\")) // for, eg.,\cdot, \ge, \le, \ne { if (strAux == "\\log") tex += " \\, " + strAux; else if (strAux == "\\lt") tex += " \\, < \\, "; else tex += " \\, " + strAux + " \\, "; } else if (strAux.contains("xor")) tex += "\\; \\mathrm{" + strAux + "} \\; "; else if (strAux == "e") tex += strAux; else tex += "\\mathrm{" + strAux + "}"; } // handling word character within <mn> ... </mn> if (tagName == "mn") tex += "{" + strAux + "}"; } // handling non-word character else if (strAux == "=" || strAux == "!" || strAux == "|") tex += strAux; else if (strAux == "-" || strAux == "+" || strAux == ">" || strAux.contains("%")) tex += " \\, " + strAux + " \\, "; return TRUE; } bool CStructureParser::endElement(const QString&, const QString&, const QString& qName) { std::cout << std::endl << "on End Element of " << TO_UTF8(qName) << std::endl; std::cout << "BEFORE: List of Uncompleted Tags: " << std::endl; Q3ValueList<QString>::iterator itL; for (itL = mListOfUncompletedTags.begin(); itL != mListOfUncompletedTags.end(); ++itL) std::cout << TO_UTF8(*itL) << std::endl; std::cout << std::endl; indent.remove((uint)0, 4); if (qName == "mtable") texTail = "\\end{array}"; if (qName == "mfrac") { if (mListOfUncompletedTags.last().contains("mfrac")) mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; } if (qName == "mtr") tex += "\\\\ \n && \\\\ \n"; if (qName == "mtd") { if (indexColumns > 0 && indexColumns < sumColumns - 1) tex += "& \\; "; indexColumns++; } if (qName == "mrow") { std::cout << std::endl << "on End Element of mrow, mListOfUncompletedTags = " << TO_UTF8(mListOfUncompletedTags.last()) << std::endl; if (mListOfUncompletedTags.last() == "mrow") mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; tex += " } "; std::cout << "on endElement of mrow, tex = " << TO_UTF8(tex) << std::endl; } if (qName == "mfenced") { if (mListOfUncompletedTags.last() == "mfenced") mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; tex += "\\right)"; QString &last = mListOfUncompletedTags.last(); // </msub> direct after </mfenced> if (last.contains("msub")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); std::cout << TO_UTF8(last) << " --> split: " << TO_UTF8(lastUncompletedTags) << " & " << idx << std::endl; idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); std::cout << "mfenced L" << __LINE__ << std::endl; std::cout << TO_UTF8(mListOfUncompletedTags.last()) << std::endl; if (lastUncompletedTags.contains("msub") && idx == 2) tex += "_"; } // </msup> direct after </mfenced> if (last.contains("msup")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); std::cout << TO_UTF8(last) << " --> split: " << TO_UTF8(lastUncompletedTags) << " & " << idx << std::endl; idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); std::cout << "mfenced L" << __LINE__ << std::endl; std::cout << TO_UTF8(mListOfUncompletedTags.last()) << std::endl; if (lastUncompletedTags.contains("msup") && idx == 2) tex += "^"; } } if (qName == "msub") { if (mListOfUncompletedTags.last().contains("msub")) mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; // </mfrac> direct after </msub> if (mListOfUncompletedTags.last().contains("mfrac")) tex += " }"; } if (qName == "msup") { if (mListOfUncompletedTags.last().contains("msup")) mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; // </mfrac> direct after </msup> if (mListOfUncompletedTags.last().contains("mfrac")) tex += " }"; } std::cout << "AFTER: List of Uncompleted Tags: " << std::endl; for (itL = mListOfUncompletedTags.begin(); itL != mListOfUncompletedTags.end(); ++itL) std::cout << TO_UTF8(*itL) << std::endl; std::cout << std::endl; return TRUE; } bool CStructureParser::ignorableWhitespace (const QString& /* str */) { return TRUE; } bool CStructureParser::skippedEntity (const QString& /* str */) { return TRUE; } QString CStructureParser::getTeX() { if (!texHead.isNull()) return "$$\n" + texHead + "\n" + tex + texTail + "\n$$"; else return "$$\n" + tex + "\n$$"; }
// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/tex/CStructureParser.cpp,v $ // $Revision: 1.7 $ // $Name: $ // $Author: pwilly $ // $Date: 2009/06/19 08:05:23 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Written by pwilly on 09.07.08 #include "CStructureParser.h" #include <qstring.h> #include <qregexp.h> //Added by qt3to4: #include <Q3ValueList> #include <iostream> #include "UI/qtUtilities.h" //#include <qvaluelist.h> CStructureParser::CStructureParser(int n) { sumColumns = n; } bool CStructureParser::startDocument() { indent = ""; tex = ""; indexColumns = -1; if (!sumColumns) needToWriteColumnAllignment = false; else needToWriteColumnAllignment = true; return TRUE; } bool CStructureParser::startElement(const QString& /* str1 */, const QString& /* str2 */, const QString& qName, const QXmlAttributes& attr) { tagName = qName; if (qName == "mtable") texHead = "\\begin{array}"; if (qName == "mtr") indexColumns = 0; if (qName == "mtd") { if (indexColumns > 0 && indexColumns < sumColumns - 1) tex += " \\; &"; if (indexColumns == 0 && needToWriteColumnAllignment) texHead += "{"; if (indexColumns < sumColumns && needToWriteColumnAllignment) { if (attr.count()) { if (attr.value("columnalign") == "left") texHead += "l"; else if (attr.value("columnalign") == "center") texHead += "c"; else if (attr.value("columnalign") == "right") texHead += "r"; } else texHead += "c"; } if (indexColumns == sumColumns - 1) { if (needToWriteColumnAllignment) texHead += "}"; needToWriteColumnAllignment = false; } } if (qName == "mfrac") { mListOfUncompletedTags.push_back("mfrac_0"); tex += "\\frac"; } if (qName == "mfenced") { mListOfUncompletedTags.push_back("mfenced"); tex += "\\left("; } if (qName == "msub") { QString &last = mListOfUncompletedTags.last(); // must be not empty // <msub> direct after <mfrac> if (last.contains("mfrac")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); tex += "{"; } // <msub> direct after <mfenced> if (last.contains("mfenced") && (!tex.endsWith("(") && !tex.endsWith("("))) { tex += ", \\, "; } mListOfUncompletedTags.push_back("msub_0"); } if (qName == "msup") { QString &last = mListOfUncompletedTags.last(); // must be not empty // <msup> direct after <mfrac> if (last.contains("mfrac")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); tex += "{"; } // <msup> direct after <mfenced> if (last.contains("mfenced") && (!tex.endsWith("(") && !tex.endsWith("("))) { tex += ", \\, "; } mListOfUncompletedTags.push_back("msup_0"); } if (qName == "mrow") { // increment index, if any if (!mListOfUncompletedTags.isEmpty()) { QString &last = mListOfUncompletedTags.last(); // can be empty if (last.contains("mfrac") || last.contains("msub") || last.contains("msup")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); if (lastUncompletedTags.contains("msub") && idx == 2) tex += "_"; if (lastUncompletedTags.contains("msup") && idx == 2) tex += "^"; } } mListOfUncompletedTags.push_back("mrow"); tex += " {"; } if (qName == "mi" || qName == "mn") { QString &last = mListOfUncompletedTags.last(); // must be not empty if (last.contains("mfenced") && (!tex.endsWith("(") && !tex.endsWith("("))) { tex += ", \\, "; } } if (qName == "mi" || qName == "mo" || qName == "mn") { // increment index, if any if (!mListOfUncompletedTags.isEmpty()) { QString &last = mListOfUncompletedTags.last(); // can be empty if (last.contains("mfrac") || last.contains("msub") || last.contains("msup")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); if (lastUncompletedTags.contains("msub") && idx == 2) tex += "_"; if (lastUncompletedTags.contains("msup") && idx == 2) tex += "^"; } } } indent += " "; return TRUE; } bool CStructureParser::characters(const QString& str) { QRegExp rx("\\w"); QString strAux = str.stripWhiteSpace(); int pos = rx.search(strAux); if (pos != -1) { // handling word character within <mrow> ... </mrow> if (tagName == "mrow") { if (strAux.length() > 1) tex += "{\\text{" + strAux + "}}"; else // exactly only one character tex += "{" + strAux + "}"; } // handling word character within <mi> ... </mi> if (tagName == "mi") { if (strAux.contains("\\")) // for, eg., \sin, \cos tex += strAux; else if (strAux.length() > 1) { if (strAux == "sech" || strAux == "csch" || strAux == "arcsec" || strAux == "arccsc" || strAux == "arccot" || strAux == "arcsinh" || strAux == "arccosh" || strAux == "arctanh" || strAux == "arcsech" || strAux == "arccsch" || strAux == "arccoth") tex += "{\\mathrm{" + strAux + " \\: }}"; else tex += "{\\mathrm{" + strAux + "}}"; } else // exactly only one character tex += "{" + strAux + "}"; } // handling word character within <mo> ... </mo> if (tagName == "mo") { if (strAux.contains("\\")) // for, eg.,\cdot, \ge, \le, \ne { if (strAux == "\\log") tex += " \\, " + strAux; else if (strAux == "\\lt") tex += " \\, < \\, "; else tex += " \\, " + strAux + " \\, "; } else if (strAux.contains("xor")) tex += "\\; \\mathrm{" + strAux + "} \\; "; else if (strAux == "e") tex += strAux; else tex += "\\mathrm{" + strAux + "}"; } // handling word character within <mn> ... </mn> if (tagName == "mn") tex += "{" + strAux + "}"; } // handling non-word character else if (strAux == "=" || strAux == "!" || strAux == "|") tex += strAux; else if (strAux == "-" || strAux == "+" || strAux == ">" || strAux.contains("%")) tex += " \\, " + strAux + " \\, "; return TRUE; } bool CStructureParser::endElement(const QString&, const QString&, const QString& qName) { std::cout << std::endl << "on End Element of " << TO_UTF8(qName) << std::endl; std::cout << "BEFORE: List of Uncompleted Tags: " << std::endl; Q3ValueList<QString>::iterator itL; for (itL = mListOfUncompletedTags.begin(); itL != mListOfUncompletedTags.end(); ++itL) std::cout << TO_UTF8(*itL) << std::endl; std::cout << std::endl; indent.remove((uint)0, 4); if (qName == "mtable") texTail = "\\end{array}"; if (qName == "mfrac") { if (mListOfUncompletedTags.last().contains("mfrac")) // must be not empty mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; } if (qName == "mtr") tex += "\\\\ \n && \\\\ \n"; if (qName == "mtd") { if (indexColumns > 0 && indexColumns < sumColumns - 1) tex += "& \\; "; indexColumns++; } if (qName == "mrow") { std::cout << std::endl << "on End Element of mrow, mListOfUncompletedTags = " << TO_UTF8(mListOfUncompletedTags.last()) << std::endl; if (mListOfUncompletedTags.last() == "mrow") // must not be empty mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; tex += " } "; std::cout << "on endElement of mrow, tex = " << TO_UTF8(tex) << std::endl; } if (qName == "mfenced") { if (mListOfUncompletedTags.last() == "mfenced") // must be not empty mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; tex += "\\right)"; QString &last = mListOfUncompletedTags.last(); // must be not empty // </msub> direct after </mfenced> if (last.contains("msub")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); std::cout << TO_UTF8(last) << " --> split: " << TO_UTF8(lastUncompletedTags) << " & " << idx << std::endl; idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); std::cout << "mfenced L" << __LINE__ << std::endl; std::cout << TO_UTF8(mListOfUncompletedTags.last()) << std::endl; if (lastUncompletedTags.contains("msub") && idx == 2) tex += "_"; } // </msup> direct after </mfenced> if (last.contains("msup")) { QStringList strList = QStringList::split("_", last); QString &lastUncompletedTags = strList.first(); QString &idxStr = strList.last(); int idx = idxStr.toInt(); std::cout << TO_UTF8(last) << " --> split: " << TO_UTF8(lastUncompletedTags) << " & " << idx << std::endl; idx++; // update with incrementally index last = lastUncompletedTags + "_" + QString::number(idx); std::cout << "mfenced L" << __LINE__ << std::endl; std::cout << TO_UTF8(mListOfUncompletedTags.last()) << std::endl; if (lastUncompletedTags.contains("msup") && idx == 2) tex += "^"; } } if (qName == "msub") { if (mListOfUncompletedTags.last().contains("msub")) // must be not empty mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; // </mfrac> direct after </msub> if (mListOfUncompletedTags.last().contains("mfrac")) // must ne not empty tex += " }"; } if (qName == "msup") { if (mListOfUncompletedTags.last().contains("msup")) // must be not empty mListOfUncompletedTags.pop_back(); else std::cout << "WARNING on L" << __LINE__ << std::endl; // </mfrac> direct after </msup> if (mListOfUncompletedTags.last().contains("mfrac")) // must be not empty tex += " }"; } std::cout << "AFTER: List of Uncompleted Tags: " << std::endl; for (itL = mListOfUncompletedTags.begin(); itL != mListOfUncompletedTags.end(); ++itL) std::cout << TO_UTF8(*itL) << std::endl; std::cout << std::endl; return TRUE; } bool CStructureParser::ignorableWhitespace(const QString& /* str */) { return TRUE; } bool CStructureParser::skippedEntity(const QString& /* str */) { return TRUE; } QString CStructureParser::getTeX() { if (!texHead.isNull()) return "$$\n" + texHead + "\n" + tex + texTail + "\n$$"; else return "$$\n" + tex + "\n$$"; }
Fix a small problem because of converting to Qt4.
Fix a small problem because of converting to Qt4.
C++
artistic-2.0
copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI
3578c8d21bc77323e2ff5df90256446bd23ebe0d
src/models/galleryitemmodel.cpp
src/models/galleryitemmodel.cpp
/* Copyright (c) 2014, Martin Björkström All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "galleryitemmodel.h" #include <QDirIterator> #include <QStandardPaths> #include <QDateTime> #include <QTimer> GalleryItemModel::GalleryItemModel(QObject *parent) : QAbstractListModel(parent) { refresh(); } int GalleryItemModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) return m_imageFiles.count(); } QVariant GalleryItemModel::data(const QModelIndex &index, int role) const { if (index.row() < 0 || index.row() >= m_imageFiles.count()) { return QVariant(); } switch (role) { case UrlRole: return m_imageFiles[index.row()].absoluteFilePath(); break; case NameRole: return m_imageFiles[index.row()].fileName(); default: return QVariant(); break; } } void GalleryItemModel::refresh() { foreach (QFileInfo fi, m_imageFiles) { if(!QFile::exists(fi.absoluteFilePath())) { int index = m_imageFiles.indexOf(fi); beginRemoveRows(QModelIndex(),index,index); m_imageFiles.removeAt(index); endRemoveRows(); } } QDirIterator iter(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation), QStringList() << "*.png" << "*.jpg" << "*.jpeg", QDir::NoFilter, QDirIterator::Subdirectories); while(iter.hasNext()) { iter.next(); if (iter.fileInfo().isFile() && !m_imageFiles.contains(iter.fileInfo())) { AddImageFileSorted(iter.fileInfo(), 0, m_imageFiles.length() -1); } } } QHash<int, QByteArray> GalleryItemModel::roleNames() const { QHash<int, QByteArray> roles; roles[UrlRole] = "url"; roles[NameRole] = "name"; return roles; } void GalleryItemModel::AddImageFileSorted(const QFileInfo &file, int min, int max) { if (max < min) { beginInsertRows(QModelIndex(),min,min); m_imageFiles.insert(min,file); endInsertRows(); } else { // calculate midpoint to cut set in half int mid = min + ((max - min) / 2); uint lastModified = file.lastModified().toTime_t(); uint midLastModified = m_imageFiles[mid].lastModified().toTime_t(); // three-way comparison if (midLastModified < lastModified) { // key is in lower subset AddImageFileSorted(file, min, mid-1); } else if (midLastModified > lastModified) { // key is in upper subset AddImageFileSorted(file, mid+1, max); } else { // key has been found beginInsertRows(QModelIndex(),mid,mid); m_imageFiles.insert(mid,file); endInsertRows(); } } }
/* Copyright (c) 2014, Martin Björkström All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "galleryitemmodel.h" #include <QDirIterator> #include <QStandardPaths> #include <QDateTime> #include <QTimer> #include <QStorageInfo> #include <QDebug> GalleryItemModel::GalleryItemModel(QObject *parent) : QAbstractListModel(parent) { refresh(); } int GalleryItemModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) return m_imageFiles.count(); } QVariant GalleryItemModel::data(const QModelIndex &index, int role) const { if (index.row() < 0 || index.row() >= m_imageFiles.count()) { return QVariant(); } switch (role) { case UrlRole: return m_imageFiles[index.row()].absoluteFilePath(); break; case NameRole: return m_imageFiles[index.row()].fileName(); default: return QVariant(); break; } } void GalleryItemModel::refresh() { foreach (QFileInfo fi, m_imageFiles) { if(!QFile::exists(fi.absoluteFilePath())) { int index = m_imageFiles.indexOf(fi); beginRemoveRows(QModelIndex(),index,index); m_imageFiles.removeAt(index); endRemoveRows(); } } QSet<QString> pictureLocations; pictureLocations << QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); // iterate through mount volumes and try to find external drives with Pictures for (const QStorageInfo &storage : QStorageInfo::mountedVolumes()) { QString mountPoint = storage.rootPath(); QString pictureDir = mountPoint + QDir::separator() + "Pictures"; if (storage.isValid() && storage.isReady() && mountPoint.startsWith("/run/media/") && // Sailfish OS specific mount point base for SD cards! QDir(pictureDir).exists()) { qDebug() << "Found photo storage:" << pictureDir; pictureLocations << pictureDir; } } foreach (QString dir, pictureLocations) { QDirIterator iter(dir, QStringList() << "*.png" << "*.jpg" << "*.jpeg", QDir::NoFilter, QDirIterator::Subdirectories); while(iter.hasNext()) { iter.next(); if (iter.fileInfo().isFile() && !m_imageFiles.contains(iter.fileInfo())) { AddImageFileSorted(iter.fileInfo(), 0, m_imageFiles.length() -1); } } } } QHash<int, QByteArray> GalleryItemModel::roleNames() const { QHash<int, QByteArray> roles; roles[UrlRole] = "url"; roles[NameRole] = "name"; return roles; } void GalleryItemModel::AddImageFileSorted(const QFileInfo &file, int min, int max) { if (max < min) { beginInsertRows(QModelIndex(),min,min); m_imageFiles.insert(min,file); endInsertRows(); } else { // calculate midpoint to cut set in half int mid = min + ((max - min) / 2); uint lastModified = file.lastModified().toTime_t(); uint midLastModified = m_imageFiles[mid].lastModified().toTime_t(); // three-way comparison if (midLastModified < lastModified) { // key is in lower subset AddImageFileSorted(file, min, mid-1); } else if (midLastModified > lastModified) { // key is in upper subset AddImageFileSorted(file, mid+1, max); } else { // key has been found beginInsertRows(QModelIndex(),mid,mid); m_imageFiles.insert(mid,file); endInsertRows(); } } }
load photos from SD card also
load photos from SD card also
C++
bsd-2-clause
mholo65/harbour-filters
7d020d0e6033ec8e783baca1b8e8d8abfb89dd01
src/modules/custommaterials.cpp
src/modules/custommaterials.cpp
/* * custommaterials.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "custommaterials.h" CustomMaterials::CustomMaterials() { materialConfig = new KeyValues("materials"); materialConfig->LoadFromFile(Interfaces::pFileSystem, "resource/custommaterials.res", "mod"); enabled = new ConVar("statusspec_custommaterials_enabled", "0", FCVAR_NONE, "enable custom materials", [](IConVar *var, const char *pOldValue, float flOldValue) { g_CustomMaterials->ToggleEnabled(var, pOldValue, flOldValue); }); load_replacement_group = new ConCommand("statusspec_custommaterials_load_replacement_group", [](const CCommand &command) { g_CustomMaterials->LoadReplacementGroup(command); }, "load a material replacement group", FCVAR_NONE); unload_replacement_group = new ConCommand("statusspec_custommaterials_unload_replacement_group", [](const CCommand &command) { g_CustomMaterials->UnloadReplacementGroup(command); }, "unload a material replacement group", FCVAR_NONE); } IMaterial *CustomMaterials::FindMaterialOverride(char const *pMaterialName, const char *pTextureGroupName, bool complain, const char *pComplainPrefix) { if (materialReplacements.find(pMaterialName) != materialReplacements.end()) { RETURN_META_VALUE_NEWPARAMS(MRES_HANDLED, nullptr, &IMaterialSystem::FindMaterial, (materialReplacements[pMaterialName].replacement.c_str(), pTextureGroupName, complain, pComplainPrefix)); } RETURN_META_VALUE(MRES_IGNORED, nullptr); } void CustomMaterials::LoadReplacementGroup(const CCommand &command) { if (command.ArgC() >= 2) { Warning("Must specify a replacement group to load!\n"); return; } const char *group = command.Arg(1); KeyValues *replacementsConfig = materialConfig->FindKey(group); if (replacementsConfig) { FOR_EACH_VALUE(replacementsConfig, materialReplacement) { std::string original = materialReplacement->GetName(); if (materialReplacements.find(original) != materialReplacements.end()) { materialReplacements.erase(original); } materialReplacements[original].group = group; materialReplacements[original].replacement = materialReplacement->GetString(); } } else { Warning("Must specify a valid replacement group to load!\n"); } } void CustomMaterials::ToggleEnabled(IConVar *var, const char *pOldValue, float flOldValue) { if (enabled->GetBool()) { if (!findMaterialHook) { findMaterialHook = Funcs::AddHook_IMaterialSystem_FindMaterial(g_pMaterialSystem, SH_MEMBER(this, &CustomMaterials::FindMaterialOverride), false); } } else { if (findMaterialHook) { if (Funcs::RemoveHook(findMaterialHook)) { findMaterialHook = 0; } } } } void CustomMaterials::UnloadReplacementGroup(const CCommand &command) { if (command.ArgC() >= 2) { Warning("Must specify a replacement group to load!\n"); return; } const char *group = command.Arg(1); KeyValues *replacementsConfig = materialConfig->FindKey(group); if (replacementsConfig) { auto iterator = materialReplacements.begin(); while (iterator != materialReplacements.end()) { if (iterator->second.group.compare(group) == 0) { materialReplacements.erase(iterator++); } else { ++iterator; } } } else { Warning("Must specify a valid replacement group to unload!\n"); } }
/* * custommaterials.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "custommaterials.h" CustomMaterials::CustomMaterials() { materialConfig = new KeyValues("materials"); materialConfig->LoadFromFile(Interfaces::pFileSystem, "resource/custommaterials.res", "mod"); enabled = new ConVar("statusspec_custommaterials_enabled", "0", FCVAR_NONE, "enable custom materials", [](IConVar *var, const char *pOldValue, float flOldValue) { g_CustomMaterials->ToggleEnabled(var, pOldValue, flOldValue); }); load_replacement_group = new ConCommand("statusspec_custommaterials_load_replacement_group", [](const CCommand &command) { g_CustomMaterials->LoadReplacementGroup(command); }, "load a material replacement group", FCVAR_NONE); unload_replacement_group = new ConCommand("statusspec_custommaterials_unload_replacement_group", [](const CCommand &command) { g_CustomMaterials->UnloadReplacementGroup(command); }, "unload a material replacement group", FCVAR_NONE); } IMaterial *CustomMaterials::FindMaterialOverride(char const *pMaterialName, const char *pTextureGroupName, bool complain, const char *pComplainPrefix) { if (materialReplacements.find(pMaterialName) != materialReplacements.end()) { RETURN_META_VALUE_NEWPARAMS(MRES_HANDLED, nullptr, &IMaterialSystem::FindMaterial, (materialReplacements[pMaterialName].replacement.c_str(), pTextureGroupName, complain, pComplainPrefix)); } RETURN_META_VALUE(MRES_IGNORED, nullptr); } void CustomMaterials::LoadReplacementGroup(const CCommand &command) { if (command.ArgC() < 2) { Warning("Must specify a replacement group to load!\n"); return; } const char *group = command.Arg(1); KeyValues *replacementsConfig = materialConfig->FindKey(group); if (replacementsConfig) { FOR_EACH_VALUE(replacementsConfig, materialReplacement) { std::string original = materialReplacement->GetName(); if (materialReplacements.find(original) != materialReplacements.end()) { materialReplacements.erase(original); } materialReplacements[original].group = group; materialReplacements[original].replacement = materialReplacement->GetString(); } } else { Warning("Must specify a valid replacement group to load!\n"); } } void CustomMaterials::ToggleEnabled(IConVar *var, const char *pOldValue, float flOldValue) { if (enabled->GetBool()) { if (!findMaterialHook) { findMaterialHook = Funcs::AddHook_IMaterialSystem_FindMaterial(g_pMaterialSystem, SH_MEMBER(this, &CustomMaterials::FindMaterialOverride), false); } } else { if (findMaterialHook) { if (Funcs::RemoveHook(findMaterialHook)) { findMaterialHook = 0; } } } } void CustomMaterials::UnloadReplacementGroup(const CCommand &command) { if (command.ArgC() < 2) { Warning("Must specify a replacement group to load!\n"); return; } const char *group = command.Arg(1); KeyValues *replacementsConfig = materialConfig->FindKey(group); if (replacementsConfig) { auto iterator = materialReplacements.begin(); while (iterator != materialReplacements.end()) { if (iterator->second.group.compare(group) == 0) { materialReplacements.erase(iterator++); } else { ++iterator; } } } else { Warning("Must specify a valid replacement group to unload!\n"); } }
Fix commands not working.
Fix commands not working.
C++
bsd-2-clause
fwdcp/StatusSpec,fwdcp/StatusSpec
ffaf887a96efe7e18098e59ac052b4114fb95651
ouzel/assets/LoaderMTL.cpp
ouzel/assets/LoaderMTL.cpp
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <sstream> #include "LoaderMTL.hpp" #include "Cache.hpp" #include "core/Engine.hpp" #include "utils/Log.hpp" namespace ouzel { namespace assets { LoaderMTL::LoaderMTL(): Loader({"mtl"}) { } bool LoaderMTL::loadAsset(const std::string& filename, const std::vector<uint8_t>& data) { std::stringstream stream; std::copy(data.begin(), data.end(), std::ostream_iterator<uint8_t>(stream)); std::string name = filename; std::shared_ptr<graphics::Texture> diffuseTexture; std::shared_ptr<graphics::Texture> ambientTexture; Color diffuseColor = Color::WHITE; float opacity = 1.0f; uint32_t materialCount = 0; std::string read; for (std::string line; std::getline(stream, line);) { if (!line.empty()) { if (line[0] == '#') continue; // comment std::stringstream lineStream; lineStream << line; lineStream >> read; if (read == "newmtl") { if (materialCount) { std::shared_ptr<graphics::Material> material = std::make_shared<graphics::Material>(); material->blendState = sharedEngine->getCache()->getBlendState(graphics::BLEND_ALPHA); material->shader = sharedEngine->getCache()->getShader(graphics::SHADER_TEXTURE); material->textures[0] = diffuseTexture; material->textures[1] = ambientTexture; material->diffuseColor = diffuseColor; material->opacity = opacity; sharedEngine->getCache()->setMaterial(name, material); } if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse material name"; return false; } lineStream >> read; name = read; diffuseTexture.reset(); ambientTexture.reset(); diffuseColor = Color::WHITE; opacity = 1.0f; } else if (read == "map_Ka") // ambient texture map { if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse ambient texture file name"; return false; } lineStream >> read; ambientTexture = sharedEngine->getCache()->getTexture(read); } else if (read == "map_Kd") // diffuse texture map { if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse texture file name"; return false; } lineStream >> read; diffuseTexture = sharedEngine->getCache()->getTexture(read); } else if (read == "Ka") // ambient color { } else if (read == "Kd") // diffuse color { float color[4]; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse color"; return false; } lineStream >> color[0]; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse color"; return false; } lineStream >> color[1]; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse color"; return false; } lineStream >> color[2]; color[3] = 1.0f; diffuseColor = Color(color); } else if (read == "Ks") // specular color { } else if (read == "Ke") // emissive color { } else if (read == "d") // opacity { if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse opacity"; return false; } lineStream >> opacity; } else if (read == "Tr") // transparency { float transparency; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse transparency"; return false; } lineStream >> transparency; // d = 1 - Tr opacity = 1.0f - transparency; } if (!materialCount) ++materialCount; // if we got at least one attribute, we have an material } } if (materialCount) { std::shared_ptr<graphics::Material> material = std::make_shared<graphics::Material>(); material->blendState = sharedEngine->getCache()->getBlendState(graphics::BLEND_ALPHA); material->shader = sharedEngine->getCache()->getShader(graphics::SHADER_TEXTURE); material->textures[0] = diffuseTexture; material->textures[1] = ambientTexture; material->diffuseColor = diffuseColor; material->opacity = opacity; sharedEngine->getCache()->setMaterial(name, material); } return true; } } // namespace assets } // namespace ouzel
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <iterator> #include <sstream> #include "LoaderMTL.hpp" #include "Cache.hpp" #include "core/Engine.hpp" #include "utils/Log.hpp" namespace ouzel { namespace assets { LoaderMTL::LoaderMTL(): Loader({"mtl"}) { } bool LoaderMTL::loadAsset(const std::string& filename, const std::vector<uint8_t>& data) { std::stringstream stream; std::copy(data.begin(), data.end(), std::ostream_iterator<uint8_t>(stream)); std::string name = filename; std::shared_ptr<graphics::Texture> diffuseTexture; std::shared_ptr<graphics::Texture> ambientTexture; Color diffuseColor = Color::WHITE; float opacity = 1.0f; uint32_t materialCount = 0; std::string read; for (std::string line; std::getline(stream, line);) { if (!line.empty()) { if (line[0] == '#') continue; // comment std::stringstream lineStream; lineStream << line; lineStream >> read; if (read == "newmtl") { if (materialCount) { std::shared_ptr<graphics::Material> material = std::make_shared<graphics::Material>(); material->blendState = sharedEngine->getCache()->getBlendState(graphics::BLEND_ALPHA); material->shader = sharedEngine->getCache()->getShader(graphics::SHADER_TEXTURE); material->textures[0] = diffuseTexture; material->textures[1] = ambientTexture; material->diffuseColor = diffuseColor; material->opacity = opacity; sharedEngine->getCache()->setMaterial(name, material); } if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse material name"; return false; } lineStream >> read; name = read; diffuseTexture.reset(); ambientTexture.reset(); diffuseColor = Color::WHITE; opacity = 1.0f; } else if (read == "map_Ka") // ambient texture map { if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse ambient texture file name"; return false; } lineStream >> read; ambientTexture = sharedEngine->getCache()->getTexture(read); } else if (read == "map_Kd") // diffuse texture map { if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse texture file name"; return false; } lineStream >> read; diffuseTexture = sharedEngine->getCache()->getTexture(read); } else if (read == "Ka") // ambient color { } else if (read == "Kd") // diffuse color { float color[4]; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse color"; return false; } lineStream >> color[0]; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse color"; return false; } lineStream >> color[1]; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse diffuse color"; return false; } lineStream >> color[2]; color[3] = 1.0f; diffuseColor = Color(color); } else if (read == "Ks") // specular color { } else if (read == "Ke") // emissive color { } else if (read == "d") // opacity { if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse opacity"; return false; } lineStream >> opacity; } else if (read == "Tr") // transparency { float transparency; if (lineStream.eof()) { Log(Log::Level::ERR) << "Failed to parse transparency"; return false; } lineStream >> transparency; // d = 1 - Tr opacity = 1.0f - transparency; } if (!materialCount) ++materialCount; // if we got at least one attribute, we have an material } } if (materialCount) { std::shared_ptr<graphics::Material> material = std::make_shared<graphics::Material>(); material->blendState = sharedEngine->getCache()->getBlendState(graphics::BLEND_ALPHA); material->shader = sharedEngine->getCache()->getShader(graphics::SHADER_TEXTURE); material->textures[0] = diffuseTexture; material->textures[1] = ambientTexture; material->diffuseColor = diffuseColor; material->opacity = opacity; sharedEngine->getCache()->setMaterial(name, material); } return true; } } // namespace assets } // namespace ouzel
Add iterator include
Add iterator include
C++
unlicense
elnormous/ouzel,elvman/ouzel,elvman/ouzel,elnormous/ouzel,elnormous/ouzel
4c5e7c6bbabff0d57765ea6f8ed4d87f4f280835
renderscript/v8/rs_support/cpu_ref/rsCpuRuntimeMathFuncs.cpp
renderscript/v8/rs_support/cpu_ref/rsCpuRuntimeMathFuncs.cpp
/* * Copyright (C) 2011-2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // exports unavailable mathlib functions to compat lib typedef unsigned int uint32_t; typedef int int32_t; extern uint32_t SC_abs_i32(int32_t v); uint32_t __attribute__((overloadable)) abs(int32_t v) {return SC_abs_i32(v);} #define IMPORT_F32_FN_F32(func) \ extern float SC_##func##f(float v); \ float __attribute__((overloadable)) func(float v) {return SC_##func##f(v);} #define IMPORT_F32_FN_F32_F32(func) \ extern float SC_##func##f(float t, float v); \ float __attribute__((overloadable)) func(float t, float v) {return SC_##func##f(t, v);} IMPORT_F32_FN_F32(acos) IMPORT_F32_FN_F32(acosh) IMPORT_F32_FN_F32(asin) IMPORT_F32_FN_F32(asinh) IMPORT_F32_FN_F32_F32(atan2) IMPORT_F32_FN_F32(atanh) IMPORT_F32_FN_F32(cbrt) IMPORT_F32_FN_F32_F32(copysign) IMPORT_F32_FN_F32(cos) IMPORT_F32_FN_F32(cosh) IMPORT_F32_FN_F32(erfc) IMPORT_F32_FN_F32(erf) IMPORT_F32_FN_F32(expm1) IMPORT_F32_FN_F32_F32(fdim) extern float SC_fmaf(float u, float t, float v); float __attribute__((overloadable)) fma(float u, float t, float v) {return SC_fmaf(u, t, v);} IMPORT_F32_FN_F32_F32(fmax) IMPORT_F32_FN_F32_F32(fmin) IMPORT_F32_FN_F32_F32(fmod) extern float SC_frexpf(float v, int* ptr); float __attribute__((overloadable)) frexp(float v, int* ptr) {return SC_frexpf(v, ptr);} IMPORT_F32_FN_F32_F32(hypot) IMPORT_F32_FN_F32(ilogb) extern float SC_ldexpf(float v, int i); float __attribute__((overloadable)) ldexp(float v, int i) {return SC_ldexpf(v, i);} IMPORT_F32_FN_F32(lgamma) extern float SC_lgammaf_r(float v, int* ptr); float __attribute__((overloadable)) lgamma(float v, int* ptr) {return SC_lgammaf_r(v, ptr);} IMPORT_F32_FN_F32(log10) IMPORT_F32_FN_F32(log1p) IMPORT_F32_FN_F32(logb) extern float SC_modff(float v, float* ptr); float modf(float v, float* ptr) {return SC_modff(v, ptr);} IMPORT_F32_FN_F32_F32(nextafter) IMPORT_F32_FN_F32_F32(remainder) extern float SC_remquof(float t, float v, int* ptr); float remquo(float t, float v, int* ptr) {return SC_remquof(t, v, ptr);} IMPORT_F32_FN_F32(rint) IMPORT_F32_FN_F32(round) IMPORT_F32_FN_F32(sin) IMPORT_F32_FN_F32(sinh) IMPORT_F32_FN_F32(sqrt) IMPORT_F32_FN_F32(tan) IMPORT_F32_FN_F32(tanh) IMPORT_F32_FN_F32(tgamma) IMPORT_F32_FN_F32(trunc)
/* * Copyright (C) 2011-2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // exports unavailable mathlib functions to compat lib typedef unsigned int uint32_t; typedef int int32_t; extern uint32_t SC_abs_i32(int32_t v); uint32_t __attribute__((overloadable)) abs(int32_t v) {return SC_abs_i32(v);} #define IMPORT_F32_FN_F32(func) \ extern float SC_##func##f(float v); \ float __attribute__((overloadable)) func(float v) {return SC_##func##f(v);} #define IMPORT_F32_FN_F32_F32(func) \ extern float SC_##func##f(float t, float v); \ float __attribute__((overloadable)) func(float t, float v) {return SC_##func##f(t, v);} IMPORT_F32_FN_F32(acos) IMPORT_F32_FN_F32(acosh) IMPORT_F32_FN_F32(asin) IMPORT_F32_FN_F32(asinh) IMPORT_F32_FN_F32_F32(atan2) IMPORT_F32_FN_F32(atanh) IMPORT_F32_FN_F32(cbrt) IMPORT_F32_FN_F32_F32(copysign) IMPORT_F32_FN_F32(cos) IMPORT_F32_FN_F32(cosh) IMPORT_F32_FN_F32(erfc) IMPORT_F32_FN_F32(erf) IMPORT_F32_FN_F32(expm1) IMPORT_F32_FN_F32_F32(fdim) extern float SC_fmaf(float u, float t, float v); float __attribute__((overloadable)) fma(float u, float t, float v) {return SC_fmaf(u, t, v);} IMPORT_F32_FN_F32_F32(fmax) IMPORT_F32_FN_F32_F32(fmin) IMPORT_F32_FN_F32_F32(fmod) extern float SC_frexpf(float v, int* ptr); float __attribute__((overloadable)) frexp(float v, int* ptr) {return SC_frexpf(v, ptr);} IMPORT_F32_FN_F32_F32(hypot) IMPORT_F32_FN_F32(ilogb) extern float SC_ldexpf(float v, int i); float __attribute__((overloadable)) ldexp(float v, int i) {return SC_ldexpf(v, i);} IMPORT_F32_FN_F32(lgamma) extern float SC_lgammaf_r(float v, int* ptr); float __attribute__((overloadable)) lgamma(float v, int* ptr) {return SC_lgammaf_r(v, ptr);} IMPORT_F32_FN_F32(log10) IMPORT_F32_FN_F32(log1p) IMPORT_F32_FN_F32(logb) extern float SC_modff(float v, float* ptr); float modf(float v, float* ptr) {return SC_modff(v, ptr);} IMPORT_F32_FN_F32_F32(nextafter) IMPORT_F32_FN_F32_F32(remainder) extern float SC_remquof(float t, float v, int* ptr); float remquo(float t, float v, int* ptr) {return SC_remquof(t, v, ptr);} IMPORT_F32_FN_F32(rint) IMPORT_F32_FN_F32(round) IMPORT_F32_FN_F32(sin) IMPORT_F32_FN_F32(sinh) IMPORT_F32_FN_F32(sqrt) IMPORT_F32_FN_F32(tan) IMPORT_F32_FN_F32(tanh) IMPORT_F32_FN_F32(tgamma) IMPORT_F32_FN_F32(trunc) // !!! DANGER !!! // These functions are potentially missing on older Android versions. // Work around the issue by supplying our own variants. // !!! DANGER !!! // The logbl() implementation is taken from the latest bionic/, since // double == long double on Android. extern "C" long double logbl(long double x) { return logb(x); } // __aeabi_idiv0 is a missing function in libcompiler_rt.so, so we just // pick the simplest implementation based on the ARM EABI doc. extern "C" int __aeabi_idiv0(int v) { return v; }
Add local implementations of logbl and __aeabi_idiv0() to the RS compat lib.
Add local implementations of logbl and __aeabi_idiv0() to the RS compat lib. We won't have access to these functions on older devices, so we supply our own implementations. Change-Id: Ibcf32bdeb3c0729f255806ed6fd6ad2fe04c7895
C++
apache-2.0
aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx
887167add20354b1852e8e004571ca6fe027cfa3
src/nostalgia/core/sdl/core.cpp
src/nostalgia/core/sdl/core.cpp
/* * Copyright 2016 - 2019 [email protected] * * 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 <SDL.h> #include <nostalgia/core/core.hpp> namespace nostalgia::core { void draw(Context *ctx); ox::Error run(Context *ctx) { for (auto running = true; running;) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_q) { running = false; } break; case SDL_QUIT: { running = false; break; } } } draw(ctx); } return OxError(0); } }
/* * Copyright 2016 - 2019 [email protected] * * 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 <SDL.h> #include <nostalgia/core/core.hpp> namespace nostalgia::core { void draw(Context *ctx); ox::Error run(Context *ctx) { for (auto running = true; running;) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_q) { running = false; } break; case SDL_QUIT: { running = false; break; } } } draw(ctx); SDL_Delay(1); } return OxError(0); } }
Add sleep 1 ms to main loop
[nostalgia/core/sdl] Add sleep 1 ms to main loop
C++
mpl-2.0
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
573ebe5ed578b171aafd931828563f7e5e225681
modules/base/rendering/renderableprism.cpp
modules/base/rendering/renderableprism.cpp
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/base/rendering/renderableprism.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/engine/globals.h> #include <openspace/rendering/renderengine.h> #include <openspace/util/updatestructures.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/opengl/openglstatecache.h> #include <ghoul/opengl/programobject.h> #include <optional> namespace { constexpr const char _loggerCat[] = "RenderablePrism"; constexpr const std::array<const char*, 2> UniformNames = { "modelViewProjectionTransform", "vs_color" }; constexpr openspace::properties::Property::PropertyInfo SegmentsInfo = { "Segments", "Segments", "The number of segments the shape of the prism should have." }; constexpr openspace::properties::Property::PropertyInfo LinesInfo = { "NumLines", "Number of Lines", "The number of lines connecting the two shapes of the prism." }; static const openspace::properties::Property::PropertyInfo RadiusInfo = { "Radius", "Radius", "The radius of the prism's shape in meters." }; constexpr openspace::properties::Property::PropertyInfo LineWidthInfo = { "LineWidth", "Line Width", "This value specifies the line width." }; constexpr openspace::properties::Property::PropertyInfo LineColorInfo = { "Color", "Color", "This value determines the RGB color for the line." }; constexpr openspace::properties::Property::PropertyInfo LengthInfo = { "Length", "Length", "The length of the prism in meters." }; // Generate vertices around the unit circle on the XY-plane std::vector<float> unitCircleVertices(int sectorCount) { std::vector<float> vertices; vertices.reserve(2 * sectorCount); float sectorStep = glm::two_pi<float>() / sectorCount; for (int i = 0; i < sectorCount; ++i) { float sectorAngle = i * sectorStep; vertices.push_back(cos(sectorAngle)); // x vertices.push_back(sin(sectorAngle)); // y } return vertices; } struct [[codegen::Dictionary(RenderablePrism)]] Parameters { // [[codegen::verbatim(SegmentsInfo.description)]] int segments; // [[codegen::verbatim(LinesInfo.description)]] std::optional<int> lines; // [[codegen::verbatim(RadiusInfo.description)]] std::optional<float> radius; // [[codegen::verbatim(LineWidthInfo.description)]] std::optional<float> lineWidth; // [[codegen::verbatim(LineColorInfo.description)]] std::optional<glm::vec3> color [[codegen::color()]]; // [[codegen::verbatim(LengthInfo.description)]] std::optional<float> length; }; #include "renderableprism_codegen.cpp" } // namespace namespace openspace { documentation::Documentation RenderablePrism::Documentation() { documentation::Documentation doc = codegen::doc<Parameters>("base_renderable_prism"); return doc; } RenderablePrism::RenderablePrism(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _nShapeSegments(SegmentsInfo, 6, 3, 32) , _nLines(LinesInfo, 6, 0, 32) , _radius(RadiusInfo, 10.f, 0.f, 3.0e12f) , _lineWidth(LineWidthInfo, 1.f, 1.f, 20.f) , _lineColor(LineColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) , _length(LengthInfo, 20.f, 1.f, 3.0e12f) { const Parameters p = codegen::bake<Parameters>(dictionary); _nShapeSegments.onChange([&]() { _prismIsDirty = true; }); _nShapeSegments = p.segments; addProperty(_nShapeSegments); _nLines.onChange([&]() { _prismIsDirty = true; }); _nLines = p.lines.value_or(_nShapeSegments); addProperty(_nLines); _radius.setExponent(10.f); _radius.onChange([&]() { _prismIsDirty = true; }); _radius = p.radius.value_or(_radius); addProperty(_radius); _lineWidth = p.lineWidth.value_or(_lineWidth); addProperty(_lineWidth); _lineColor.setViewOption(properties::Property::ViewOptions::Color); _lineColor = p.color.value_or(_lineColor); addProperty(_lineColor); _length.setExponent(12.f); _length.onChange([&]() { _prismIsDirty = true; }); _length = p.length.value_or(_length); addProperty(_length); addProperty(_opacity); } bool RenderablePrism::isReady() const { return _shader != nullptr; } void RenderablePrism::initialize() { updateVertexData(); } void RenderablePrism::initializeGL() { _shader = global::renderEngine->buildRenderProgram( "PrismProgram", absPath("${MODULE_BASE}/shaders/prism_vs.glsl"), absPath("${MODULE_BASE}/shaders/prism_fs.glsl") ); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); glGenVertexArrays(1, &_vaoId); glGenBuffers(1, &_vboId); glGenBuffers(1, &_iboId); glBindVertexArray(_vaoId); updateBufferData(); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glBindVertexArray(0); } void RenderablePrism::deinitializeGL() { global::renderEngine->removeRenderProgram(_shader.get()); _shader = nullptr; glDeleteVertexArrays(1, &_vaoId); _vaoId = 0; glDeleteBuffers(1, &_vboId); _vboId = 0; glDeleteBuffers(1, &_iboId); _iboId = 0; } void RenderablePrism::updateVertexData() { _vertexArray.clear(); _indexArray.clear(); // Get unit circle vertices on the XY-plane std::vector<float> unitVertices = unitCircleVertices(_nShapeSegments); std::vector<float> unitVerticesLines = unitCircleVertices(_nLines); // Put base and top shape vertices into array for (int i = 0; i < 2; ++i) { float h = i * _length; // z value, 0 to _length for (int j = 0, k = 0; j < _nShapeSegments && k < unitVertices.size(); ++j, k += 2) { float ux = unitVertices[k]; float uy = unitVertices[k + 1]; _vertexArray.push_back(ux * _radius); // x _vertexArray.push_back(uy * _radius); // y _vertexArray.push_back(h); // z } } // Put the vertices for the connecting lines into array if (_nLines == 1) { // In the case of just one line then connect the center points instead // Center for base shape _vertexArray.push_back(0.f); _vertexArray.push_back(0.f); _vertexArray.push_back(0.f); // Center for top shape _vertexArray.push_back(0.f); _vertexArray.push_back(0.f); _vertexArray.push_back(_length); } else { for (int j = 0, k = 0; j < _nLines && k < unitVerticesLines.size(); ++j, k += 2) { float ux = unitVerticesLines[k]; float uy = unitVerticesLines[k + 1]; // Base _vertexArray.push_back(ux * _radius); // x _vertexArray.push_back(uy * _radius); // y _vertexArray.push_back(0.f); // z // Top _vertexArray.push_back(ux * _radius); // x _vertexArray.push_back(uy * _radius); // y _vertexArray.push_back(_length); // z } } // Indices for Base shape ghoul_assert(_nShapeSegments.value <= std::numeric_limit<uint8_t>::max(), "Too many shape segments") for (uint8_t i = 0; i < _nShapeSegments; ++i) { _indexArray.push_back(i); } // Reset _indexArray.push_back(255); // Indices for Top shape for (uint8_t i = _nShapeSegments; i < 2 * _nShapeSegments; ++i) { _indexArray.push_back(i); } // Indices for connecting lines for (int i = 0, k = 0; i < _nLines; ++i, k += 2) { // Reset _indexArray.push_back(255); _indexArray.push_back(2 * _nShapeSegments + k); _indexArray.push_back(2 * _nShapeSegments + k + 1); } } void RenderablePrism::updateBufferData() { glBindBuffer(GL_ARRAY_BUFFER, _vboId); glBufferData( GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(float), _vertexArray.data(), GL_STREAM_DRAW ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iboId); glBufferData( GL_ELEMENT_ARRAY_BUFFER, _indexArray.size() * sizeof(uint8_t), _indexArray.data(), GL_STREAM_DRAW ); } void RenderablePrism::render(const RenderData& data, RendererTasks&) { _shader->activate(); // Model transform and view transform needs to be in double precision glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(data.modelTransform.rotation) * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); glm::mat4 modelViewProjectionTransform = data.camera.projectionMatrix() * glm::mat4(data.camera.combinedViewMatrix() * modelTransform); // Uniforms _shader->setUniform(_uniformCache.modelViewProjection, modelViewProjectionTransform); _shader->setUniform(_uniformCache.color, glm::vec4(_lineColor.value(), _opacity)); // Render glEnable(GL_PRIMITIVE_RESTART); glPrimitiveRestartIndex(255); glLineWidth(_lineWidth); glBindVertexArray(_vaoId); glDrawElements(GL_LINE_LOOP, static_cast<GLsizei>(_indexArray.size()), GL_UNSIGNED_BYTE, nullptr); glBindVertexArray(0); global::renderEngine->openglStateCache().resetLineState(); glDisable(GL_PRIMITIVE_RESTART); _shader->deactivate(); } void RenderablePrism::update(const UpdateData&) { if (_shader->isDirty()) { _shader->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); } if (_prismIsDirty) { updateVertexData(); updateBufferData(); _prismIsDirty = false; } } } // namespace openspace
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/base/rendering/renderableprism.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/engine/globals.h> #include <openspace/rendering/renderengine.h> #include <openspace/util/updatestructures.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/opengl/openglstatecache.h> #include <ghoul/opengl/programobject.h> #include <optional> namespace { constexpr const char _loggerCat[] = "RenderablePrism"; constexpr const std::array<const char*, 2> UniformNames = { "modelViewProjectionTransform", "vs_color" }; constexpr openspace::properties::Property::PropertyInfo SegmentsInfo = { "Segments", "Segments", "The number of segments the shape of the prism should have." }; constexpr openspace::properties::Property::PropertyInfo LinesInfo = { "NumLines", "Number of Lines", "The number of lines connecting the two shapes of the prism." }; static const openspace::properties::Property::PropertyInfo RadiusInfo = { "Radius", "Radius", "The radius of the prism's shape in meters." }; constexpr openspace::properties::Property::PropertyInfo LineWidthInfo = { "LineWidth", "Line Width", "This value specifies the line width." }; constexpr openspace::properties::Property::PropertyInfo LineColorInfo = { "Color", "Color", "This value determines the RGB color for the line." }; constexpr openspace::properties::Property::PropertyInfo LengthInfo = { "Length", "Length", "The length of the prism in meters." }; // Generate vertices around the unit circle on the XY-plane std::vector<float> unitCircleVertices(int sectorCount) { std::vector<float> vertices; vertices.reserve(2 * sectorCount); float sectorStep = glm::two_pi<float>() / sectorCount; for (int i = 0; i < sectorCount; ++i) { float sectorAngle = i * sectorStep; vertices.push_back(cos(sectorAngle)); // x vertices.push_back(sin(sectorAngle)); // y } return vertices; } struct [[codegen::Dictionary(RenderablePrism)]] Parameters { // [[codegen::verbatim(SegmentsInfo.description)]] int segments; // [[codegen::verbatim(LinesInfo.description)]] std::optional<int> lines; // [[codegen::verbatim(RadiusInfo.description)]] std::optional<float> radius; // [[codegen::verbatim(LineWidthInfo.description)]] std::optional<float> lineWidth; // [[codegen::verbatim(LineColorInfo.description)]] std::optional<glm::vec3> color [[codegen::color()]]; // [[codegen::verbatim(LengthInfo.description)]] std::optional<float> length; }; #include "renderableprism_codegen.cpp" } // namespace namespace openspace { documentation::Documentation RenderablePrism::Documentation() { documentation::Documentation doc = codegen::doc<Parameters>("base_renderable_prism"); return doc; } RenderablePrism::RenderablePrism(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _nShapeSegments(SegmentsInfo, 6, 3, 32) , _nLines(LinesInfo, 6, 0, 32) , _radius(RadiusInfo, 10.f, 0.f, 3.0e12f) , _lineWidth(LineWidthInfo, 1.f, 1.f, 20.f) , _lineColor(LineColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) , _length(LengthInfo, 20.f, 1.f, 3.0e12f) { const Parameters p = codegen::bake<Parameters>(dictionary); _nShapeSegments.onChange([&]() { _prismIsDirty = true; }); _nShapeSegments = p.segments; addProperty(_nShapeSegments); _nLines.onChange([&]() { _prismIsDirty = true; }); _nLines = p.lines.value_or(_nShapeSegments); addProperty(_nLines); _radius.setExponent(10.f); _radius.onChange([&]() { _prismIsDirty = true; }); _radius = p.radius.value_or(_radius); addProperty(_radius); _lineWidth = p.lineWidth.value_or(_lineWidth); addProperty(_lineWidth); _lineColor.setViewOption(properties::Property::ViewOptions::Color); _lineColor = p.color.value_or(_lineColor); addProperty(_lineColor); _length.setExponent(12.f); _length.onChange([&]() { _prismIsDirty = true; }); _length = p.length.value_or(_length); addProperty(_length); addProperty(_opacity); } bool RenderablePrism::isReady() const { return _shader != nullptr; } void RenderablePrism::initialize() { updateVertexData(); } void RenderablePrism::initializeGL() { _shader = global::renderEngine->buildRenderProgram( "PrismProgram", absPath("${MODULE_BASE}/shaders/prism_vs.glsl"), absPath("${MODULE_BASE}/shaders/prism_fs.glsl") ); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); glGenVertexArrays(1, &_vaoId); glGenBuffers(1, &_vboId); glGenBuffers(1, &_iboId); glBindVertexArray(_vaoId); updateBufferData(); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glBindVertexArray(0); } void RenderablePrism::deinitializeGL() { global::renderEngine->removeRenderProgram(_shader.get()); _shader = nullptr; glDeleteVertexArrays(1, &_vaoId); _vaoId = 0; glDeleteBuffers(1, &_vboId); _vboId = 0; glDeleteBuffers(1, &_iboId); _iboId = 0; } void RenderablePrism::updateVertexData() { _vertexArray.clear(); _indexArray.clear(); // Get unit circle vertices on the XY-plane std::vector<float> unitVertices = unitCircleVertices(_nShapeSegments); std::vector<float> unitVerticesLines = unitCircleVertices(_nLines); // Put base and top shape vertices into array for (int i = 0; i < 2; ++i) { float h = i * _length; // z value, 0 to _length for (int j = 0, k = 0; j < _nShapeSegments && k < unitVertices.size(); ++j, k += 2) { float ux = unitVertices[k]; float uy = unitVertices[k + 1]; _vertexArray.push_back(ux * _radius); // x _vertexArray.push_back(uy * _radius); // y _vertexArray.push_back(h); // z } } // Put the vertices for the connecting lines into array if (_nLines == 1) { // In the case of just one line then connect the center points instead // Center for base shape _vertexArray.push_back(0.f); _vertexArray.push_back(0.f); _vertexArray.push_back(0.f); // Center for top shape _vertexArray.push_back(0.f); _vertexArray.push_back(0.f); _vertexArray.push_back(_length); } else { for (int j = 0, k = 0; j < _nLines && k < unitVerticesLines.size(); ++j, k += 2) { float ux = unitVerticesLines[k]; float uy = unitVerticesLines[k + 1]; // Base _vertexArray.push_back(ux * _radius); // x _vertexArray.push_back(uy * _radius); // y _vertexArray.push_back(0.f); // z // Top _vertexArray.push_back(ux * _radius); // x _vertexArray.push_back(uy * _radius); // y _vertexArray.push_back(_length); // z } } // Indices for Base shape ghoul_assert(_nShapeSegments.value <= std::numeric_limit<uint8_t>::max(), "Too many shape segments") for (uint8_t i = 0; i < _nShapeSegments; ++i) { _indexArray.push_back(i); } // Reset _indexArray.push_back(255); // Indices for Top shape for (uint8_t i = _nShapeSegments; i < 2 * _nShapeSegments; ++i) { _indexArray.push_back(i); } // Indices for connecting lines for (int i = 0, k = 0; i < _nLines; ++i, k += 2) { // Reset _indexArray.push_back(255); _indexArray.push_back(2 * _nShapeSegments + k); _indexArray.push_back(2 * _nShapeSegments + k + 1); } } void RenderablePrism::updateBufferData() { glBindBuffer(GL_ARRAY_BUFFER, _vboId); glBufferData( GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(float), _vertexArray.data(), GL_STREAM_DRAW ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iboId); glBufferData( GL_ELEMENT_ARRAY_BUFFER, _indexArray.size() * sizeof(uint8_t), _indexArray.data(), GL_STREAM_DRAW ); } void RenderablePrism::render(const RenderData& data, RendererTasks&) { _shader->activate(); // Model transform and view transform needs to be in double precision glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(data.modelTransform.rotation) * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); glm::mat4 modelViewProjectionTransform = data.camera.projectionMatrix() * glm::mat4(data.camera.combinedViewMatrix() * modelTransform); // Uniforms _shader->setUniform(_uniformCache.modelViewProjection, modelViewProjectionTransform); _shader->setUniform(_uniformCache.color, glm::vec4(_lineColor.value(), _opacity)); // Render glEnable(GL_PRIMITIVE_RESTART); glPrimitiveRestartIndex(255); glLineWidth(_lineWidth); glBindVertexArray(_vaoId); glDrawElements(GL_LINE_LOOP, static_cast<GLsizei>(_indexArray.size()), GL_UNSIGNED_BYTE, nullptr); glBindVertexArray(0); global::renderEngine->openglStateCache().resetLineState(); glDisable(GL_PRIMITIVE_RESTART); _shader->deactivate(); } void RenderablePrism::update(const UpdateData& data) { if (_shader->isDirty()) { _shader->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); } if (_prismIsDirty) { updateVertexData(); updateBufferData(); setBoundingSphere(_length * glm::compMax(data.modelTransform.scale)); _prismIsDirty = false; } } } // namespace openspace
Add boundingSphere for RenderablePrism
Add boundingSphere for RenderablePrism
C++
mit
OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace
d32fb285237f35604ae413d33f69b6dc462a4b7e
src/shaders/FragmentLooping.cpp
src/shaders/FragmentLooping.cpp
// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #include <sh/sh.hpp> #include <sh/shutil.hpp> #include <iostream> #include "Shader.hpp" #include "Globals.hpp" using namespace SH; using namespace ShUtil; class FragmentLooping : public Shader { public: FragmentLooping(); ~FragmentLooping(); bool init(); ShProgram vertex() { return vsh;} ShProgram fragment() { return fsh;} ShProgram vsh, fsh; static FragmentLooping instance; }; FragmentLooping::FragmentLooping() : Shader("Branching: Loops in Fragment Unit") { } FragmentLooping::~FragmentLooping() { } bool FragmentLooping::init() { vsh = ShKernelLib::shVsh( Globals::mv, Globals::mvp ); vsh = vsh << shExtract("lightPos") << Globals::lightPos; vsh = shSwizzle("texcoord", "posh") << vsh; ShColor3f SH_DECL(diffuse) = ShColor3f(1.0, 0.0, 0.0); ShAttrib1f SH_DECL(julia_max_iter) = 20.0; julia_max_iter.range(1.0, 40.0); ShAttrib2f SH_DECL(julia_c) = ShAttrib2f(0.54, -0.51); julia_c.range(-1.0, 1.0); ShAttrib1f SH_DECL(brightness) = 1.0; brightness.range(0.0, 10.0); ShAttrib1f SH_DECL(height) = 0.2; height.range(0.0, 4.0); ShAttrib1f SH_DECL(zoom) = 0.33; zoom.range(0.0, 10.0); ShPoint2f SH_DECL(centre) = ShPoint2f(0.0, 0.0); centre.range(-2.0, 2.0); ShAttrib1f SH_DECL(gamma) = 0.7; gamma.range(0.0, 1.0); fsh = SH_BEGIN_PROGRAM("gpu:fragment") { ShInputTexCoord2f u; ShOutputColor3f ocol; // Color of result u = u - centre; u /= zoom; ShAttrib1f i = 0.0; SH_WHILE((dot(u, u) < 2.0) * (i < julia_max_iter)) { ShTexCoord2f v; v(0) = u(0)*u(0) - u(1)*u(1); v(1) = 2.0 * u(0) * u(1); u = v + julia_c; i += 1.0; } SH_ENDWHILE; ShAttrib1f disp = pow(i / julia_max_iter, gamma); ocol = disp * diffuse * brightness; } SH_END; return true; } FragmentLooping FragmentLooping::instance = FragmentLooping();
// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #include <sh/sh.hpp> #include <sh/shutil.hpp> #include <iostream> #include "Shader.hpp" #include "Globals.hpp" using namespace SH; using namespace ShUtil; class FragmentLooping : public Shader { public: FragmentLooping(); ~FragmentLooping(); bool init(); ShProgram vertex() { return vsh;} ShProgram fragment() { return fsh;} ShProgram vsh, fsh; static FragmentLooping instance; }; FragmentLooping::FragmentLooping() : Shader("Branching: Loops in Fragment Unit") { } FragmentLooping::~FragmentLooping() { } bool FragmentLooping::init() { vsh = ShKernelLib::shVsh( Globals::mv, Globals::mvp ); vsh = vsh << shExtract("lightPos") << Globals::lightPos; vsh = shSwizzle("texcoord", "posh") << vsh; ShColor3f SH_DECL(diffuse) = ShColor3f(1.0, 0.0, 0.0); ShAttrib1f SH_DECL(julia_max_iter) = 20.0; julia_max_iter.range(1.0, 40.0); ShAttrib2f SH_DECL(julia_c) = ShAttrib2f(0.54, -0.51); julia_c.range(-1.0, 1.0); ShAttrib1f SH_DECL(brightness) = 1.0; brightness.range(0.0, 10.0); ShAttrib1f SH_DECL(height) = 0.2; height.range(0.0, 4.0); ShAttrib1f SH_DECL(zoom) = 0.33; zoom.range(0.0, 10.0); ShPoint2f SH_DECL(centre) = ShPoint2f(0.0, 0.0); centre.range(-2.0, 2.0); ShAttrib1f SH_DECL(gamma) = 0.7; gamma.range(0.0, 1.0); fsh = SH_BEGIN_PROGRAM("gpu:fragment") { ShInputTexCoord2f u; ShOutputColor3f ocol; // Color of result u = u - centre; u /= zoom; ShAttrib1f i = 0.0; SH_DO { ShTexCoord2f v; v(0) = u(0)*u(0) - u(1)*u(1); v(1) = 2.0 * u(0) * u(1); u = v + julia_c; i += 1.0; } SH_UNTIL (0 == ((dot(u, u) < 2.0) * (i < julia_max_iter))); ShAttrib1f disp = pow(i / julia_max_iter, gamma); ocol = disp * diffuse * brightness; } SH_END; return true; } FragmentLooping FragmentLooping::instance = FragmentLooping();
Use a 'do..until' loop instead of a 'while', just so we have a shader that exercises that loop construct.
Use a 'do..until' loop instead of a 'while', just so we have a shader that exercises that loop construct. git-svn-id: 1d2ffecffb2a9ae52c786cff8ae6d2f25f277313@2125 afdca40c-03d6-0310-8ede-e9f093b21075
C++
lgpl-2.1
libsh-archive/shrike,libsh-archive/shrike