text stringlengths 54 60.6k |
|---|
<commit_before>/*
(c) Gabriel L. Dunne, 2014
*/
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
// of stuff
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofEnableDepthTest();
// settings
showHelp = true;
editMode = true;
camMouse = false;
mouseDragging = false;
nearestIndex = 0;
normalSmoothAmt = 20;
// set up material
// shininess is a value between 0 - 128, 128 being the most shiny //
material.setShininess( 120 );
material.setSpecularColor(ofColor(255, 255, 255));
material.setAmbientColor(ofColor(0, 0, 0));
material.setShininess(25.0f);
// load mesh
mesh.load("landscape-squ.ply");
// mesh.load("mesh-tweaked.ply");
//sceneMesh.append(mesh);
//sceneMesh.smoothNormals( normalSmoothAmt );
// reference sphere
sphere.setRadius( 20 );
// set up lights
ofSetGlobalAmbientColor(ofColor(0, 0, 0));
ofSetSmoothLighting(true);
light.setup();
light.setPointLight();
light.setDiffuseColor( ofFloatColor(1.0f, 1.0f, 1.0f) );
light.setSpecularColor( ofFloatColor(1.0f, 1.0f, 1.0f) );
// light.setAttenuation(0.5, 0, 0);
// setAttenuation(float constant=1.f, float linear=0.f, float quadratic=0.f))
// load camera settings
ofxLoadCamera(cam, "cameraSettings");
// start w/ mouse input disabled
cam.disableMouseInput();
}
//--------------------------------------------------------------
void ofApp::update(){
// move light around
light.setPosition(cos(ofGetElapsedTimef()) * 100.0, 40, sin(ofGetElapsedTimef()) * 100.0);
}
//--------------------------------------------------------------
void ofApp::draw(){
if (editMode) {
// if editing, show background gradient
ofBackgroundGradient(ofColor(64), ofColor(0));
} else {
// black bg
ofBackground(ofColor(0));
}
// begin camera
cam.begin();
// enable lighting
ofEnableLighting();
// ofEnableSeparateSpecularLight();
light.enable();
// light.setGlobalPosition(1000, 1000, 1000);
// light.lookAt(ofVec3f(0,0,0));
// start material
material.begin();
ofSetColor(255);
ofFill();
// test sphere
//sphere.setPosition(0, 60, 0);
//sphere.draw();
// draw mesh faces
if (!editMode) {
sceneMesh.draw();
}
// end material
material.end();
// end lighting
ofDisableLighting();
// draw light position
if (editMode) {
ofSetColor(ofColor::gray);
ofSetLineWidth(1);
ofLine(light.getPosition(), ofVec3f(0));
ofFill();
ofSetColor(light.getDiffuseColor());
light.draw();
}
// draw verts and wireframe when editing
if (editMode) {
// draw wireframe
//ofSetColor(ofColor::yellow);
//glLineWidth(2);
//mesh.drawWireframe();
// draw verts
ofSetColor(ofColor::white);
glPointSize(4);
mesh.drawVertices();
}
// end camera
cam.end();
// vert selection
if (editMode) {
// create vec2 of the mouse for reference
ofVec2f mouse(mouseX, mouseY);
// if not dragging the mouse, find the nearest vert
if (!mouseDragging) {
// loop through all verticies in mesh and find the nearest vert position and index
int n = mesh.getNumVertices();
float nearestDistance = 0;
for(int i = 0; i < n; i++) {
ofVec3f cur = cam.worldToScreen(mesh.getVertex(i));
float distance = cur.distance(mouse);
if(i == 0 || distance < nearestDistance) {
nearestDistance = distance;
nearestVertex = cur;
nearestIndex = i;
}
}
}
// draw a line from the nearest vertex to the mouse position
ofSetColor(ofColor::gray);
ofSetLineWidth(1);
ofLine(nearestVertex, mouse);
// draw a cirle around the nearest vertex
ofNoFill();
ofSetColor(ofColor::magenta);
ofSetLineWidth(2);
if (mouseDragging) {
ofCircle(mouse, 4);
} else {
ofCircle(nearestVertex, 4);
}
ofSetLineWidth(1);
// edit position of nearest vert with mousedrag
if (!camMouse && mouseDragging) {
mesh.setVertex(nearestIndex, cam.screenToWorld(ofVec3f(mouse.x, mouse.y, nearestVertex.z)));
}
// draw a label with the nearest vertex index
ofDrawBitmapStringHighlight(ofToString(nearestIndex), mouse + ofVec2f(10, -10));
}
// draw info text
if (showHelp) {
stringstream ss;
ss << "Framerate " << ofToString(ofGetFrameRate(),0) << "\n";
ss << " f : Toggle Fullscreen" << "\n";
ss << " h : Toggle Help Text" << "\n";
ss << " c : Toggle Camera Control : " << (camMouse == true ? "ON" : "OFF") << "\n";
ss << "TAB : Toggle Mesh Edit : " << (editMode == true ? "ON" : "OFF") << "\n";
ss << " s : Save Scene" << "\n";
ss << " l : Load Scene";
ofSetColor(ofColor::white);
ofDrawBitmapStringHighlight(ss.str().c_str(), ofVec3f(10, 20), ofColor(45), ofColor(255));
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key) {
// toggle fullscreen
case 'f':
ofToggleFullscreen();
break;
// toggle camera control
case 'c':
camMouse = !camMouse;
camMouse ? cam.enableMouseInput() : cam.disableMouseInput();
break;
// saves the camera and mesh settings
case 's':
ofxSaveCamera(cam, "cameraSettings");
mesh.save("mesh-tweaked.ply");
break;
// loads camera and mesh settings
case 'l':
ofxLoadCamera(cam, "cameraSettings");
mesh.load("mesh-tweaked.ply");
camMouse = false;
editMode = false;
break;
// show help
case 'h':
showHelp = !showHelp;
break;
// toggle 'TAB' to edit verts
case OF_KEY_TAB:
editMode = !editMode;
if (!editMode) {
sceneMesh.clear();
sceneMesh.append(mesh);
sceneMesh.smoothNormals( normalSmoothAmt );
}
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
mouseDragging = true;
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
mouseDragging = false;
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>Using round model<commit_after>/*
(c) Gabriel L. Dunne, 2014
*/
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
// of stuff
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofEnableDepthTest();
// settings
showHelp = true;
editMode = true;
camMouse = false;
mouseDragging = false;
nearestIndex = 0;
normalSmoothAmt = 20;
// set up material
// shininess is a value between 0 - 128, 128 being the most shiny //
material.setShininess( 120 );
material.setSpecularColor(ofColor(255, 255, 255));
material.setAmbientColor(ofColor(0, 0, 0));
material.setShininess(25.0f);
// load mesh
mesh.load("landscape-round.ply");
// mesh.load("mesh-tweaked.ply");
//sceneMesh.append(mesh);
//sceneMesh.smoothNormals( normalSmoothAmt );
// reference sphere
sphere.setRadius( 20 );
// set up lights
ofSetGlobalAmbientColor(ofColor(0, 0, 0));
ofSetSmoothLighting(true);
light.setup();
light.setPointLight();
light.setDiffuseColor( ofFloatColor(1.0f, 1.0f, 1.0f) );
light.setSpecularColor( ofFloatColor(1.0f, 1.0f, 1.0f) );
// light.setAttenuation(0.5, 0, 0);
// setAttenuation(float constant=1.f, float linear=0.f, float quadratic=0.f))
// load camera settings
ofxLoadCamera(cam, "cameraSettings");
// start w/ mouse input disabled
cam.disableMouseInput();
}
//--------------------------------------------------------------
void ofApp::update(){
// move light around
light.setPosition(cos(ofGetElapsedTimef()) * 100.0, 40, sin(ofGetElapsedTimef()) * 100.0);
}
//--------------------------------------------------------------
void ofApp::draw(){
if (editMode) {
// if editing, show background gradient
ofBackgroundGradient(ofColor(80), ofColor(5));
} else {
// black bg
ofBackground(ofColor(0));
}
// begin camera
cam.begin();
// enable lighting
ofEnableLighting();
// ofEnableSeparateSpecularLight();
light.enable();
// light.setGlobalPosition(1000, 1000, 1000);
// light.lookAt(ofVec3f(0,0,0));
// start material
material.begin();
ofSetColor(255);
ofFill();
// test sphere
//sphere.setPosition(0, 60, 0);
//sphere.draw();
// draw mesh faces
if (!editMode) {
sceneMesh.draw();
}
// end material
material.end();
// end lighting
ofDisableLighting();
// draw light position
if (editMode) {
ofSetColor(ofColor::gray);
ofSetLineWidth(1);
ofLine(light.getPosition(), ofVec3f(0));
ofFill();
ofSetColor(light.getDiffuseColor());
light.draw();
}
// draw verts and wireframe when editing
if (editMode) {
// draw wireframe
//ofSetColor(ofColor::yellow);
//glLineWidth(2);
//mesh.drawWireframe();
// mesh.getFace(<#int faceId#>);
// draw verts
ofSetColor(ofColor::white);
glPointSize(4);
mesh.drawVertices();
}
// end camera
cam.end();
// vert selection
if (editMode) {
// create vec2 of the mouse for reference
ofVec2f mouse(mouseX, mouseY);
// if not dragging the mouse, find the nearest vert
if (!mouseDragging) {
// loop through all verticies in mesh and find the nearest vert position and index
int n = mesh.getNumVertices();
float nearestDistance = 0;
for(int i = 0; i < n; i++) {
ofVec3f cur = cam.worldToScreen(mesh.getVertex(i));
float distance = cur.distance(mouse);
if(i == 0 || distance < nearestDistance) {
nearestDistance = distance;
nearestVertex = cur;
nearestIndex = i;
}
}
}
// draw a line from the nearest vertex to the mouse position
ofSetColor(ofColor::gray);
ofSetLineWidth(1);
ofLine(nearestVertex, mouse);
// draw a cirle around the nearest vertex
ofNoFill();
ofSetColor(ofColor::magenta);
ofSetLineWidth(2);
if (mouseDragging) {
ofCircle(mouse, 4);
} else {
ofCircle(nearestVertex, 4);
}
ofSetLineWidth(1);
// edit position of nearest vert with mousedrag
if (!camMouse && mouseDragging) {
mesh.setVertex(nearestIndex, cam.screenToWorld(ofVec3f(mouse.x, mouse.y, nearestVertex.z)));
}
// draw a label with the nearest vertex index
ofDrawBitmapStringHighlight(ofToString(nearestIndex), mouse + ofVec2f(10, -10));
}
// draw info text
if (showHelp) {
stringstream ss;
ss << "Framerate " << ofToString(ofGetFrameRate(),0) << "\n";
ss << " f : Toggle Fullscreen" << "\n";
ss << " h : Toggle Help Text" << "\n";
ss << " c : Toggle Camera Control : " << (camMouse == true ? "ON" : "OFF") << "\n";
ss << "TAB : Toggle Mesh Edit : " << (editMode == true ? "ON" : "OFF") << "\n";
ss << " s : Save Scene" << "\n";
ss << " l : Load Scene";
ofSetColor(ofColor::white);
ofDrawBitmapStringHighlight(ss.str().c_str(), ofVec3f(10, 20), ofColor(45), ofColor(255));
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key) {
// toggle fullscreen
case 'f':
ofToggleFullscreen();
break;
// toggle camera control
case 'c':
camMouse = !camMouse;
camMouse ? cam.enableMouseInput() : cam.disableMouseInput();
break;
// saves the camera and mesh settings
case 's':
ofxSaveCamera(cam, "cameraSettings");
mesh.save("mesh-tweaked.ply");
break;
// loads camera and mesh settings
case 'l':
ofxLoadCamera(cam, "cameraSettings");
mesh.load("mesh-tweaked.ply");
camMouse = false;
editMode = false;
break;
// show help
case 'h':
showHelp = !showHelp;
break;
// toggle 'TAB' to edit verts
case OF_KEY_TAB:
editMode = !editMode;
if (!editMode) {
sceneMesh.clear();
sceneMesh.append(mesh);
sceneMesh.smoothNormals( normalSmoothAmt );
}
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
mouseDragging = true;
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
mouseDragging = false;
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
showHelp = true;
editMode = false;
camMouse = false;
mouseDragging = false;
nearestIndex = 0;
isShaderDirty = true;
// load camera settings
ofxLoadCamera(cam, "cameraSettings");
// initialize scene with mouse input disabled
cam.disableMouseInput();
ofSetVerticalSync(true);
// load mesh
mesh.load("landscape-squ.ply");
// mesh.load("mesh-tweaked.ply");
// mesh.smoothNormals( 15 );
// reference sphere
sphere.setRadius( 20 );
// set up lights
ofSetGlobalAmbientColor(ofColor(0, 0, 0));
ofSetSmoothLighting(true);
light.setPointLight();
light.setDiffuseColor( ofFloatColor(0.6f, 0.6f, 0.6f));
light.setSpecularColor( ofFloatColor(1.0f, 1.0f, 1.0f));
// light.setAttenuation(0.5, 0, 0);
// setAttenuation(float constant=1.f, float linear=0.f, float quadratic=0.f))
// set up material
// shininess is a value between 0 - 128, 128 being the most shiny //
material.setShininess( 120 );
material.setSpecularColor(ofColor(255, 255, 255));
material.setAmbientColor(ofColor(0, 0, 0));
}
//--------------------------------------------------------------
void ofApp::update(){
// move light around
light.setPosition(cos(ofGetElapsedTimef()) * 100.0, 40, sin(ofGetElapsedTimef()) * 100.0);
// update shader
if (isShaderDirty){
GLuint err = glGetError(); // we need this to clear out the error buffer.
if (shader != NULL ) delete shader;
shader = new ofShader();
shader->load("shaders/phong");
err = glGetError(); // we need this to clear out the error buffer.
ofLogNotice() << "Loaded Shader: " << err;
isShaderDirty = false;
}
}
//--------------------------------------------------------------
void ofApp::draw(){
// glShadeModel(GL_SMOOTH);
// glProvokingVertex(GL_LAST_VERTEX_CONVENTION);
if (editMode) {
// if editing, show background gradient
ofBackgroundGradient(ofColor(64), ofColor(0));
} else {
// black bg
ofBackground(ofColor(0));
}
// set main color to white
ofSetColor(255);
// enable depth test so objects draw in correct z-order
ofEnableDepthTest();
// glEnable(GL_DEPTH_TEST);
// glEnable(GL_CULL_FACE);
// glCullFace(GL_BACK);
// begin camera
cam.begin();
// enable lighting
ofEnableLighting();
// ofEnableSeparateSpecularLight();
light.enable();
// light.setGlobalPosition(1000, 1000, 1000);
// light.lookAt(ofVec3f(0,0,0));
// start material
ofSetColor(light.getDiffuseColor());
material.begin();
ofFill();
ofSetColor(255);
// shader->begin();
// shader->setUniform1f("shouldRenderNormals", 0.0);
// shader->setUniform1f("shouldUseFlatShading", 0.0);
// glShadeModel(GL_FLAT);
// glProvokingVertex(GL_FIRST_VERTEX_CONVENTION); // OpenGL default is GL_LAST_VERTEX_CONVENTION
// restores shade model
// glPopAttrib();
// restores vertex convention defaults.
// glProvokingVertex(GL_LAST_VERTEX_CONVENTION);
// shader->end();
// test sphere
// sphere.setPosition(0, 60, 0);
// sphere.draw();
// draw mesh faces
mesh.draw();
// draw light position
if (editMode) {
ofSetColor(255);
ofFill();
light.draw();
}
// end material
material.end();
// end lighting
light.disable();
ofDisableLighting();
// draw verts when editing
if (editMode) {
// set point size to 2
glPointSize(2);
// draw all verts as white
ofSetColor(ofColor::white);
mesh.drawVertices();
}
// end camera
cam.end();
ofDisableDepthTest();
// glDisable(GL_CULL_FACE);
// glDisable(GL_DEPTH_TEST);
// vert selection
if (editMode) {
// create vec2 of the mouse for reference
ofVec2f mouse(mouseX, mouseY);
// if not dragging the mouse, find the nearest vert
if (!mouseDragging) {
// loop through all verticies in mesh and find the nearest vert position and index
int n = mesh.getNumVertices();
float nearestDistance = 0;
for(int i = 0; i < n; i++) {
ofVec3f cur = cam.worldToScreen(mesh.getVertex(i));
float distance = cur.distance(mouse);
if(i == 0 || distance < nearestDistance) {
nearestDistance = distance;
nearestVertex = cur;
nearestIndex = i;
}
}
}
// draw a gray line from the nearest vertex to the mouse position
ofSetColor(ofColor::gray);
ofLine(nearestVertex, mouse);
// draw a cirle around the nearest vertex
ofNoFill();
ofSetColor(ofColor::magenta);
ofSetLineWidth(2);
ofCircle(nearestVertex, 4);
ofSetLineWidth(1);
// edit position of nearest vert with mousedrag
if (!camMouse && mouseDragging) {
mesh.setVertex(nearestIndex, cam.screenToWorld(ofVec3f(mouse.x, mouse.y, nearestVertex.z)));
}
// draw a label with the nearest vertex index
ofDrawBitmapStringHighlight(ofToString(nearestIndex), mouse + ofVec2f(10, -10));
}
// draw info text
if (showHelp) {
stringstream ss;
ss << "Framerate " << ofToString(ofGetFrameRate(),0) << "\n";
ss << " f : Toggle Fullscreen" << "\n";
ss << " h : Toggle Help Text" << "\n";
ss << " c : Toggle Camera Control : " << (camMouse == true ? "ON" : "OFF") << "\n";
ss << "TAB : Toggle Mesh Edit : " << (editMode == true ? "ON" : "OFF") << "\n";
ss << " s : Save Scene" << "\n";
ss << " l : Load Scene";
ofSetColor(ofColor::white);
ofDrawBitmapStringHighlight(ss.str().c_str(), ofVec3f(10, 20), ofColor(45), ofColor(255));
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key) {
// toggle fullscreen
case 'f':
ofToggleFullscreen();
break;
// toggle camera control
case 'c':
camMouse = !camMouse;
camMouse ? cam.enableMouseInput() : cam.disableMouseInput();
break;
// saves the camera and mesh settings
case 's':
ofxSaveCamera(cam, "cameraSettings");
mesh.save("mesh-tweaked.ply");
break;
// loads camera and mesh settings
case 'l':
ofxLoadCamera(cam, "cameraSettings");
mesh.load("mesh-tweaked.ply");
camMouse = false;
editMode = false;
break;
// show help
case 'h':
showHelp = !showHelp;
break;
// toggle 'TAB' to edit verts
case OF_KEY_TAB:
editMode = !editMode;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
mouseDragging = true;
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
mouseDragging = false;
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>Getting lights and wireframe rendering<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
showHelp = true;
editMode = false;
camMouse = false;
mouseDragging = false;
nearestIndex = 0;
isShaderDirty = true;
// load camera settings
ofxLoadCamera(cam, "cameraSettings");
// initialize scene with mouse input disabled
cam.disableMouseInput();
ofSetVerticalSync(true);
// load mesh
mesh.load("landscape-squ.ply");
// mesh.load("mesh-tweaked.ply");
// mesh.smoothNormals( 15 );
// reference sphere
sphere.setRadius( 20 );
// set up lights
ofSetGlobalAmbientColor(ofColor(0, 0, 0));
ofSetSmoothLighting(true);
light.setPointLight();
light.setDiffuseColor( ofFloatColor(1.0f, 1.0f, 1.0f) );
light.setSpecularColor( ofFloatColor(1.0f, 1.0f, 1.0f) );
// light.setAttenuation(0.5, 0, 0);
// setAttenuation(float constant=1.f, float linear=0.f, float quadratic=0.f))
// set up material
// shininess is a value between 0 - 128, 128 being the most shiny //
material.setShininess( 120 );
material.setSpecularColor(ofColor(255, 255, 255));
material.setAmbientColor(ofColor(0, 0, 0));
}
//--------------------------------------------------------------
void ofApp::update(){
// move light around
light.setPosition(cos(ofGetElapsedTimef()) * 100.0, 40, sin(ofGetElapsedTimef()) * 100.0);
// update shader
if (isShaderDirty){
GLuint err = glGetError(); // we need this to clear out the error buffer.
if (shader != NULL ) delete shader;
shader = new ofShader();
shader->load("shaders/phong");
err = glGetError(); // we need this to clear out the error buffer.
ofLogNotice() << "Loaded Shader: " << err;
isShaderDirty = false;
}
}
//--------------------------------------------------------------
void ofApp::draw(){
// glShadeModel(GL_SMOOTH);
// glProvokingVertex(GL_LAST_VERTEX_CONVENTION);
if (editMode) {
// if editing, show background gradient
ofBackgroundGradient(ofColor(64), ofColor(0));
} else {
// black bg
ofBackground(ofColor(0));
}
// set main color to white
ofSetColor(255);
// enable depth test so objects draw in correct z-order
ofEnableDepthTest();
// begin camera
cam.begin();
// enable lighting
ofEnableLighting();
// ofEnableSeparateSpecularLight();
light.enable();
// light.setGlobalPosition(1000, 1000, 1000);
// light.lookAt(ofVec3f(0,0,0));
// start material
ofSetColor(light.getDiffuseColor());
material.begin();
ofFill();
ofSetColor(255);
// shader->begin();
// shader->setUniform1f("shouldRenderNormals", 0.0);
// shader->setUniform1f("shouldUseFlatShading", 0.0);
// glShadeModel(GL_FLAT);
// glProvokingVertex(GL_FIRST_VERTEX_CONVENTION); // OpenGL default is GL_LAST_VERTEX_CONVENTION
// restores shade model
// glPopAttrib();
// restores vertex convention defaults.
// glProvokingVertex(GL_LAST_VERTEX_CONVENTION);
// shader->end();
// test sphere
sphere.setPosition(0, 60, 0);
sphere.draw();
// draw mesh faces
mesh.draw();
// end material
material.end();
// end lighting
ofDisableLighting();
// draw light position
if (editMode) {
ofFill();
ofSetColor(light.getDiffuseColor());
light.draw();
}
// draw verts and wireframe when editing
if (editMode) {
// draw wireframe
ofSetColor(ofColor::yellow);
glLineWidth(2);
mesh.drawWireframe();
// draw verts
ofSetColor(ofColor::white);
glPointSize(2);
mesh.drawVertices();
}
// end camera
cam.end();
ofDisableDepthTest();
// vert selection
if (editMode) {
// create vec2 of the mouse for reference
ofVec2f mouse(mouseX, mouseY);
// if not dragging the mouse, find the nearest vert
if (!mouseDragging) {
// loop through all verticies in mesh and find the nearest vert position and index
int n = mesh.getNumVertices();
float nearestDistance = 0;
for(int i = 0; i < n; i++) {
ofVec3f cur = cam.worldToScreen(mesh.getVertex(i));
float distance = cur.distance(mouse);
if(i == 0 || distance < nearestDistance) {
nearestDistance = distance;
nearestVertex = cur;
nearestIndex = i;
}
}
}
// draw a line from the nearest vertex to the mouse position
ofSetColor(ofColor::gray);
ofSetLineWidth(1);
ofLine(nearestVertex, mouse);
// draw a cirle around the nearest vertex
ofNoFill();
ofSetColor(ofColor::magenta);
ofSetLineWidth(2);
ofCircle(nearestVertex, 4);
ofSetLineWidth(1);
// edit position of nearest vert with mousedrag
if (!camMouse && mouseDragging) {
mesh.setVertex(nearestIndex, cam.screenToWorld(ofVec3f(mouse.x, mouse.y, nearestVertex.z)));
}
// draw a label with the nearest vertex index
ofDrawBitmapStringHighlight(ofToString(nearestIndex), mouse + ofVec2f(10, -10));
}
// draw info text
if (showHelp) {
stringstream ss;
ss << "Framerate " << ofToString(ofGetFrameRate(),0) << "\n";
ss << " f : Toggle Fullscreen" << "\n";
ss << " h : Toggle Help Text" << "\n";
ss << " c : Toggle Camera Control : " << (camMouse == true ? "ON" : "OFF") << "\n";
ss << "TAB : Toggle Mesh Edit : " << (editMode == true ? "ON" : "OFF") << "\n";
ss << " s : Save Scene" << "\n";
ss << " l : Load Scene";
ofSetColor(ofColor::white);
ofDrawBitmapStringHighlight(ss.str().c_str(), ofVec3f(10, 20), ofColor(45), ofColor(255));
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key) {
// toggle fullscreen
case 'f':
ofToggleFullscreen();
break;
// toggle camera control
case 'c':
camMouse = !camMouse;
camMouse ? cam.enableMouseInput() : cam.disableMouseInput();
break;
// saves the camera and mesh settings
case 's':
ofxSaveCamera(cam, "cameraSettings");
mesh.save("mesh-tweaked.ply");
break;
// loads camera and mesh settings
case 'l':
ofxLoadCamera(cam, "cameraSettings");
mesh.load("mesh-tweaked.ply");
camMouse = false;
editMode = false;
break;
// show help
case 'h':
showHelp = !showHelp;
break;
// toggle 'TAB' to edit verts
case OF_KEY_TAB:
editMode = !editMode;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
mouseDragging = true;
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
mouseDragging = false;
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.1 1999/11/09 01:08:28 twl
* Initial revision
*
* Revision 1.2 1999/11/08 20:44:35 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLUni.hpp>
#include <util/XMLString.hpp>
#include <framework/XMLAttr.hpp>
// ---------------------------------------------------------------------------
// XMLAttr: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLAttr::XMLAttr() :
fName(0)
, fPrefix(0)
, fQName(0)
, fType(XMLAttDef::CData)
, fValue(0)
, fSpecified(false)
, fURIId(0)
{
}
XMLAttr::XMLAttr( const unsigned int uriId
, const XMLCh* const attrName
, const XMLCh* const attrPrefix
, const XMLCh* const attrValue
, const XMLAttDef::AttTypes type
, const bool specified) :
fName(0)
, fPrefix(0)
, fQName(0)
, fType(type)
, fValue(0)
, fSpecified(specified)
, fURIId(0)
{
try
{
set(uriId, attrName, attrPrefix, attrValue);
}
catch(...)
{
cleanUp();
}
}
// ---------------------------------------------------------------------------
// XMLAttr: Getter methods
// ---------------------------------------------------------------------------
const XMLCh* XMLAttr::getQName() const
{
// Fault in the QName if not already done
if (!fQName)
{
if (*fPrefix)
{
const unsigned int len = XMLString::stringLen(fPrefix)
+ XMLString::stringLen(fName)
+ 1;
const XMLCh colonStr[] = { chColon, chNull };
// We are faulting this guy in, so cast of const'ness
((XMLAttr*)this)->fQName = new XMLCh[len + 1];
XMLString::copyString(fQName, fPrefix);
XMLString::catString(fQName, colonStr);
XMLString::catString(fQName, fName);
}
else
{
// We are faulting this guy in, so cast of const'ness
((XMLAttr*)this)->fQName = XMLString::replicate(fName);
}
}
return fQName;
}
// ---------------------------------------------------------------------------
// XMLAttr: Setter methods
// ---------------------------------------------------------------------------
void XMLAttr::set( const unsigned int uriId
, const XMLCh* const attrName
, const XMLCh* const attrPrefix
, const XMLCh* const attrValue
, const XMLAttDef::AttTypes type)
{
// Clean up the old stuff
delete [] fName;
fName = 0;
delete [] fPrefix;
fPrefix = 0;
delete [] fValue;
fValue = 0;
// And clean up the QName and leave it undone until asked for
delete [] fQName;
fQName = 0;
// And now replicate the stuff into our members
fType = type;
fURIId = uriId;
fName = XMLString::replicate(attrName);
fPrefix = XMLString::replicate(attrPrefix);
fValue = XMLString::replicate(attrValue);
}
void XMLAttr::setName( const unsigned int uriId
, const XMLCh* const attrName
, const XMLCh* const attrPrefix)
{
// Clean up the old stuff
delete [] fName;
fName = 0;
delete [] fPrefix;
fPrefix = 0;
// And clean up the QName and leave it undone until asked for
delete [] fQName;
fQName = 0;
// And now replicate the stuff into our members
fURIId = uriId;
fName = XMLString::replicate(attrName);
fPrefix = XMLString::replicate(attrPrefix);
}
void XMLAttr::setURIId(const unsigned int uriId)
{
fURIId = uriId;
}
void XMLAttr::setValue(const XMLCh* const newValue)
{
delete [] fValue;
fValue = XMLString::replicate(newValue);
}
// ---------------------------------------------------------------------------
// XMLAttr: Private, helper methods
// ---------------------------------------------------------------------------
void XMLAttr::cleanUp()
{
delete [] fName;
delete [] fQName;
delete [] fValue;
}
<commit_msg>Fixed a small reported memory leak in destructor.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.2 1999/12/18 00:18:39 roddey
* Fixed a small reported memory leak in destructor.
*
* Revision 1.1.1.1 1999/11/09 01:08:28 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:44:35 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLUni.hpp>
#include <util/XMLString.hpp>
#include <framework/XMLAttr.hpp>
// ---------------------------------------------------------------------------
// XMLAttr: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLAttr::XMLAttr() :
fName(0)
, fPrefix(0)
, fQName(0)
, fType(XMLAttDef::CData)
, fValue(0)
, fSpecified(false)
, fURIId(0)
{
}
XMLAttr::XMLAttr( const unsigned int uriId
, const XMLCh* const attrName
, const XMLCh* const attrPrefix
, const XMLCh* const attrValue
, const XMLAttDef::AttTypes type
, const bool specified) :
fName(0)
, fPrefix(0)
, fQName(0)
, fType(type)
, fValue(0)
, fSpecified(specified)
, fURIId(0)
{
try
{
set(uriId, attrName, attrPrefix, attrValue);
}
catch(...)
{
cleanUp();
}
}
// ---------------------------------------------------------------------------
// XMLAttr: Getter methods
// ---------------------------------------------------------------------------
const XMLCh* XMLAttr::getQName() const
{
// Fault in the QName if not already done
if (!fQName)
{
if (*fPrefix)
{
const unsigned int len = XMLString::stringLen(fPrefix)
+ XMLString::stringLen(fName)
+ 1;
const XMLCh colonStr[] = { chColon, chNull };
// We are faulting this guy in, so cast of const'ness
((XMLAttr*)this)->fQName = new XMLCh[len + 1];
XMLString::copyString(fQName, fPrefix);
XMLString::catString(fQName, colonStr);
XMLString::catString(fQName, fName);
}
else
{
// We are faulting this guy in, so cast of const'ness
((XMLAttr*)this)->fQName = XMLString::replicate(fName);
}
}
return fQName;
}
// ---------------------------------------------------------------------------
// XMLAttr: Setter methods
// ---------------------------------------------------------------------------
void XMLAttr::set( const unsigned int uriId
, const XMLCh* const attrName
, const XMLCh* const attrPrefix
, const XMLCh* const attrValue
, const XMLAttDef::AttTypes type)
{
// Clean up the old stuff
delete [] fName;
fName = 0;
delete [] fPrefix;
fPrefix = 0;
delete [] fValue;
fValue = 0;
// And clean up the QName and leave it undone until asked for
delete [] fQName;
fQName = 0;
// And now replicate the stuff into our members
fType = type;
fURIId = uriId;
fName = XMLString::replicate(attrName);
fPrefix = XMLString::replicate(attrPrefix);
fValue = XMLString::replicate(attrValue);
}
void XMLAttr::setName( const unsigned int uriId
, const XMLCh* const attrName
, const XMLCh* const attrPrefix)
{
// Clean up the old stuff
delete [] fName;
fName = 0;
delete [] fPrefix;
fPrefix = 0;
// And clean up the QName and leave it undone until asked for
delete [] fQName;
fQName = 0;
// And now replicate the stuff into our members
fURIId = uriId;
fName = XMLString::replicate(attrName);
fPrefix = XMLString::replicate(attrPrefix);
}
void XMLAttr::setURIId(const unsigned int uriId)
{
fURIId = uriId;
}
void XMLAttr::setValue(const XMLCh* const newValue)
{
delete [] fValue;
fValue = XMLString::replicate(newValue);
}
// ---------------------------------------------------------------------------
// XMLAttr: Private, helper methods
// ---------------------------------------------------------------------------
void XMLAttr::cleanUp()
{
delete [] fName;
delete [] fPrefix;
delete [] fQName;
delete [] fValue;
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* editor_plugin_settings.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "editor_plugin_settings.h"
#include "core/io/config_file.h"
#include "core/os/file_access.h"
#include "core/os/main_loop.h"
#include "core/project_settings.h"
#include "editor_node.h"
#include "scene/gui/margin_container.h"
void EditorPluginSettings::_notification(int p_what) {
if (p_what == MainLoop::NOTIFICATION_WM_FOCUS_IN) {
update_plugins();
} else if (p_what == Node::NOTIFICATION_READY) {
plugin_config_dialog->connect("plugin_ready", EditorNode::get_singleton(), "_on_plugin_ready");
plugin_list->connect("button_pressed", this, "_cell_button_pressed");
}
}
void EditorPluginSettings::update_plugins() {
plugin_list->clear();
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
Error err = da->change_dir("res://addons");
if (err != OK) {
memdelete(da);
return;
}
updating = true;
TreeItem *root = plugin_list->create_item();
da->list_dir_begin();
String d = da->get_next();
Vector<String> plugins;
while (d != String()) {
bool dir = da->current_is_dir();
String path = "res://addons/" + d + "/plugin.cfg";
if (dir && FileAccess::exists(path)) {
plugins.push_back(d);
}
d = da->get_next();
}
da->list_dir_end();
memdelete(da);
plugins.sort();
for (int i = 0; i < plugins.size(); i++) {
Ref<ConfigFile> cf;
cf.instance();
String path = "res://addons/" + plugins[i] + "/plugin.cfg";
Error err = cf->load(path);
if (err != OK) {
WARN_PRINTS("Can't load plugin config: " + path);
} else if (!cf->has_section_key("plugin", "name")) {
WARN_PRINTS("Plugin misses plugin/name: " + path);
} else if (!cf->has_section_key("plugin", "author")) {
WARN_PRINTS("Plugin misses plugin/author: " + path);
} else if (!cf->has_section_key("plugin", "version")) {
WARN_PRINTS("Plugin misses plugin/version: " + path);
} else if (!cf->has_section_key("plugin", "description")) {
WARN_PRINTS("Plugin misses plugin/description: " + path);
} else if (!cf->has_section_key("plugin", "script")) {
WARN_PRINTS("Plugin misses plugin/script: " + path);
} else {
String d = plugins[i];
String name = cf->get_value("plugin", "name");
String author = cf->get_value("plugin", "author");
String version = cf->get_value("plugin", "version");
String description = cf->get_value("plugin", "description");
String script = cf->get_value("plugin", "script");
TreeItem *item = plugin_list->create_item(root);
item->set_text(0, name);
item->set_tooltip(0, "Name: " + name + "\nPath: " + path + "\nMain Script: " + script);
item->set_metadata(0, d);
item->set_text(1, version);
item->set_metadata(1, script);
item->set_text(2, author);
item->set_metadata(2, description);
item->set_cell_mode(3, TreeItem::CELL_MODE_RANGE);
item->set_range_config(3, 0, 1, 1);
item->set_text(3, "Inactive,Active");
item->set_editable(3, true);
item->add_button(4, get_icon("Edit", "EditorIcons"), BUTTON_PLUGIN_EDIT, false, TTR("Edit Plugin"));
if (EditorNode::get_singleton()->is_addon_plugin_enabled(d)) {
item->set_custom_color(3, get_color("success_color", "Editor"));
item->set_range(3, 1);
} else {
item->set_custom_color(3, get_color("disabled_font_color", "Editor"));
item->set_range(3, 0);
}
}
}
updating = false;
}
void EditorPluginSettings::_plugin_activity_changed() {
if (updating)
return;
TreeItem *ti = plugin_list->get_edited();
ERR_FAIL_COND(!ti);
bool active = ti->get_range(3);
String name = ti->get_metadata(0);
EditorNode::get_singleton()->set_addon_plugin_enabled(name, active);
bool is_active = EditorNode::get_singleton()->is_addon_plugin_enabled(name);
if (is_active != active) {
updating = true;
ti->set_range(3, is_active ? 1 : 0);
updating = false;
}
if (is_active)
ti->set_custom_color(3, get_color("success_color", "Editor"));
else
ti->set_custom_color(3, get_color("disabled_font_color", "Editor"));
}
void EditorPluginSettings::_create_clicked() {
plugin_config_dialog->config("");
plugin_config_dialog->popup_centered();
}
void EditorPluginSettings::_cell_button_pressed(Object *p_item, int p_column, int p_id) {
TreeItem *item = Object::cast_to<TreeItem>(p_item);
if (!item)
return;
if (p_id == BUTTON_PLUGIN_EDIT) {
if (p_column == 4) {
String dir = item->get_metadata(0);
plugin_config_dialog->config("res://addons/" + dir + "/plugin.cfg");
plugin_config_dialog->popup_centered();
}
}
}
void EditorPluginSettings::_bind_methods() {
ClassDB::bind_method("update_plugins", &EditorPluginSettings::update_plugins);
ClassDB::bind_method("_create_clicked", &EditorPluginSettings::_create_clicked);
ClassDB::bind_method("_plugin_activity_changed", &EditorPluginSettings::_plugin_activity_changed);
ClassDB::bind_method("_cell_button_pressed", &EditorPluginSettings::_cell_button_pressed);
}
EditorPluginSettings::EditorPluginSettings() {
plugin_config_dialog = memnew(PluginConfigDialog);
plugin_config_dialog->config("");
add_child(plugin_config_dialog);
HBoxContainer *title_hb = memnew(HBoxContainer);
title_hb->add_child(memnew(Label(TTR("Installed Plugins:"))));
title_hb->add_spacer();
create_plugin = memnew(Button(TTR("Create")));
create_plugin->connect("pressed", this, "_create_clicked");
title_hb->add_child(create_plugin);
update_list = memnew(Button(TTR("Update")));
update_list->connect("pressed", this, "update_plugins");
title_hb->add_child(update_list);
add_child(title_hb);
plugin_list = memnew(Tree);
plugin_list->set_v_size_flags(SIZE_EXPAND_FILL);
plugin_list->set_columns(5);
plugin_list->set_column_titles_visible(true);
plugin_list->set_column_title(0, TTR("Name:"));
plugin_list->set_column_title(1, TTR("Version:"));
plugin_list->set_column_title(2, TTR("Author:"));
plugin_list->set_column_title(3, TTR("Status:"));
plugin_list->set_column_title(4, TTR("Edit:"));
plugin_list->set_column_expand(0, true);
plugin_list->set_column_expand(1, false);
plugin_list->set_column_expand(2, false);
plugin_list->set_column_expand(3, false);
plugin_list->set_column_expand(4, false);
plugin_list->set_column_min_width(1, 100 * EDSCALE);
plugin_list->set_column_min_width(2, 250 * EDSCALE);
plugin_list->set_column_min_width(3, 80 * EDSCALE);
plugin_list->set_column_min_width(4, 40 * EDSCALE);
plugin_list->set_hide_root(true);
plugin_list->connect("item_edited", this, "_plugin_activity_changed");
VBoxContainer *mc = memnew(VBoxContainer);
mc->add_child(plugin_list);
mc->set_v_size_flags(SIZE_EXPAND_FILL);
mc->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(mc);
updating = false;
}
<commit_msg>Add EditorPlugin descriptions to their tooltip<commit_after>/*************************************************************************/
/* editor_plugin_settings.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "editor_plugin_settings.h"
#include "core/io/config_file.h"
#include "core/os/file_access.h"
#include "core/os/main_loop.h"
#include "core/project_settings.h"
#include "editor_node.h"
#include "scene/gui/margin_container.h"
void EditorPluginSettings::_notification(int p_what) {
if (p_what == MainLoop::NOTIFICATION_WM_FOCUS_IN) {
update_plugins();
} else if (p_what == Node::NOTIFICATION_READY) {
plugin_config_dialog->connect("plugin_ready", EditorNode::get_singleton(), "_on_plugin_ready");
plugin_list->connect("button_pressed", this, "_cell_button_pressed");
}
}
void EditorPluginSettings::update_plugins() {
plugin_list->clear();
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
Error err = da->change_dir("res://addons");
if (err != OK) {
memdelete(da);
return;
}
updating = true;
TreeItem *root = plugin_list->create_item();
da->list_dir_begin();
String d = da->get_next();
Vector<String> plugins;
while (d != String()) {
bool dir = da->current_is_dir();
String path = "res://addons/" + d + "/plugin.cfg";
if (dir && FileAccess::exists(path)) {
plugins.push_back(d);
}
d = da->get_next();
}
da->list_dir_end();
memdelete(da);
plugins.sort();
for (int i = 0; i < plugins.size(); i++) {
Ref<ConfigFile> cf;
cf.instance();
String path = "res://addons/" + plugins[i] + "/plugin.cfg";
Error err = cf->load(path);
if (err != OK) {
WARN_PRINTS("Can't load plugin config: " + path);
} else if (!cf->has_section_key("plugin", "name")) {
WARN_PRINTS("Plugin misses plugin/name: " + path);
} else if (!cf->has_section_key("plugin", "author")) {
WARN_PRINTS("Plugin misses plugin/author: " + path);
} else if (!cf->has_section_key("plugin", "version")) {
WARN_PRINTS("Plugin misses plugin/version: " + path);
} else if (!cf->has_section_key("plugin", "description")) {
WARN_PRINTS("Plugin misses plugin/description: " + path);
} else if (!cf->has_section_key("plugin", "script")) {
WARN_PRINTS("Plugin misses plugin/script: " + path);
} else {
String d = plugins[i];
String name = cf->get_value("plugin", "name");
String author = cf->get_value("plugin", "author");
String version = cf->get_value("plugin", "version");
String description = cf->get_value("plugin", "description");
String script = cf->get_value("plugin", "script");
TreeItem *item = plugin_list->create_item(root);
item->set_text(0, name);
item->set_tooltip(0, "Name: " + name + "\nPath: " + path + "\nMain Script: " + script + "\nDescription: " + description);
item->set_metadata(0, d);
item->set_text(1, version);
item->set_metadata(1, script);
item->set_text(2, author);
item->set_metadata(2, description);
item->set_cell_mode(3, TreeItem::CELL_MODE_RANGE);
item->set_range_config(3, 0, 1, 1);
item->set_text(3, "Inactive,Active");
item->set_editable(3, true);
item->add_button(4, get_icon("Edit", "EditorIcons"), BUTTON_PLUGIN_EDIT, false, TTR("Edit Plugin"));
if (EditorNode::get_singleton()->is_addon_plugin_enabled(d)) {
item->set_custom_color(3, get_color("success_color", "Editor"));
item->set_range(3, 1);
} else {
item->set_custom_color(3, get_color("disabled_font_color", "Editor"));
item->set_range(3, 0);
}
}
}
updating = false;
}
void EditorPluginSettings::_plugin_activity_changed() {
if (updating)
return;
TreeItem *ti = plugin_list->get_edited();
ERR_FAIL_COND(!ti);
bool active = ti->get_range(3);
String name = ti->get_metadata(0);
EditorNode::get_singleton()->set_addon_plugin_enabled(name, active);
bool is_active = EditorNode::get_singleton()->is_addon_plugin_enabled(name);
if (is_active != active) {
updating = true;
ti->set_range(3, is_active ? 1 : 0);
updating = false;
}
if (is_active)
ti->set_custom_color(3, get_color("success_color", "Editor"));
else
ti->set_custom_color(3, get_color("disabled_font_color", "Editor"));
}
void EditorPluginSettings::_create_clicked() {
plugin_config_dialog->config("");
plugin_config_dialog->popup_centered();
}
void EditorPluginSettings::_cell_button_pressed(Object *p_item, int p_column, int p_id) {
TreeItem *item = Object::cast_to<TreeItem>(p_item);
if (!item)
return;
if (p_id == BUTTON_PLUGIN_EDIT) {
if (p_column == 4) {
String dir = item->get_metadata(0);
plugin_config_dialog->config("res://addons/" + dir + "/plugin.cfg");
plugin_config_dialog->popup_centered();
}
}
}
void EditorPluginSettings::_bind_methods() {
ClassDB::bind_method("update_plugins", &EditorPluginSettings::update_plugins);
ClassDB::bind_method("_create_clicked", &EditorPluginSettings::_create_clicked);
ClassDB::bind_method("_plugin_activity_changed", &EditorPluginSettings::_plugin_activity_changed);
ClassDB::bind_method("_cell_button_pressed", &EditorPluginSettings::_cell_button_pressed);
}
EditorPluginSettings::EditorPluginSettings() {
plugin_config_dialog = memnew(PluginConfigDialog);
plugin_config_dialog->config("");
add_child(plugin_config_dialog);
HBoxContainer *title_hb = memnew(HBoxContainer);
title_hb->add_child(memnew(Label(TTR("Installed Plugins:"))));
title_hb->add_spacer();
create_plugin = memnew(Button(TTR("Create")));
create_plugin->connect("pressed", this, "_create_clicked");
title_hb->add_child(create_plugin);
update_list = memnew(Button(TTR("Update")));
update_list->connect("pressed", this, "update_plugins");
title_hb->add_child(update_list);
add_child(title_hb);
plugin_list = memnew(Tree);
plugin_list->set_v_size_flags(SIZE_EXPAND_FILL);
plugin_list->set_columns(5);
plugin_list->set_column_titles_visible(true);
plugin_list->set_column_title(0, TTR("Name:"));
plugin_list->set_column_title(1, TTR("Version:"));
plugin_list->set_column_title(2, TTR("Author:"));
plugin_list->set_column_title(3, TTR("Status:"));
plugin_list->set_column_title(4, TTR("Edit:"));
plugin_list->set_column_expand(0, true);
plugin_list->set_column_expand(1, false);
plugin_list->set_column_expand(2, false);
plugin_list->set_column_expand(3, false);
plugin_list->set_column_expand(4, false);
plugin_list->set_column_min_width(1, 100 * EDSCALE);
plugin_list->set_column_min_width(2, 250 * EDSCALE);
plugin_list->set_column_min_width(3, 80 * EDSCALE);
plugin_list->set_column_min_width(4, 40 * EDSCALE);
plugin_list->set_hide_root(true);
plugin_list->connect("item_edited", this, "_plugin_activity_changed");
VBoxContainer *mc = memnew(VBoxContainer);
mc->add_child(plugin_list);
mc->set_v_size_flags(SIZE_EXPAND_FILL);
mc->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(mc);
updating = false;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/geometry/interior.hpp>
#include <mapnik/geometry_envelope.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/geometry_centroid.hpp>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/optional.hpp>
#pragma GCC diagnostic pop
namespace mapnik { namespace geometry {
// Interior algorithm is realized as a modification of Polylabel algorithm
// from https://github.com/mapbox/polylabel.
// The modification aims to improve visual output by prefering
// placements closer to centroid.
namespace detail {
// get squared distance from a point to a segment
template <class T>
T segment_dist_sq(const point<T>& p,
const point<T>& a,
const point<T>& b)
{
auto x = a.x;
auto y = a.y;
auto dx = b.x - x;
auto dy = b.y - y;
if (dx != 0 || dy != 0) {
auto t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = b.x;
y = b.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return dx * dx + dy * dy;
}
template <class T>
void point_to_ring_dist(point<T> const& point, linear_ring<T> const& ring,
bool & inside, double & min_dist_sq)
{
for (std::size_t i = 0, len = ring.size(), j = len - 1; i < len; j = i++)
{
const auto& a = ring[i];
const auto& b = ring[j];
if ((a.y > point.y) != (b.y > point.y) &&
(point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x)) inside = !inside;
min_dist_sq = std::min(min_dist_sq, segment_dist_sq(point, a, b));
}
}
// signed distance from point to polygon outline (negative if point is outside)
template <class T>
double point_to_polygon_dist(const point<T>& point, const polygon<T>& polygon)
{
bool inside = false;
double min_dist_sq = std::numeric_limits<double>::infinity();
point_to_ring_dist(point, polygon.exterior_ring, inside, min_dist_sq);
for (const auto& ring : polygon.interior_rings)
{
point_to_ring_dist(point, ring, inside, min_dist_sq);
}
return (inside ? 1 : -1) * std::sqrt(min_dist_sq);
}
template <class T>
struct fitness_functor
{
fitness_functor(point<T> const& centroid, point<T> const& polygon_size)
: centroid(centroid),
max_size(std::max(polygon_size.x, polygon_size.y))
{}
T operator()(point<T> const& cell_center, T distance_polygon) const
{
if (distance_polygon <= 0)
{
return distance_polygon;
}
point<T> d(cell_center.x - centroid.x, cell_center.y - centroid.y);
double distance_centroid = std::sqrt(d.x * d.x + d.y * d.y);
return distance_polygon * (1 - distance_centroid / max_size);
}
point<T> centroid;
T max_size;
};
template <class T>
struct cell
{
template <class FitnessFunc>
cell(const point<T>& c_, T h_,
const polygon<T>& polygon,
const FitnessFunc& ff)
: c(c_),
h(h_),
d(point_to_polygon_dist(c, polygon)),
fitness(ff(c, d)),
max_fitness(ff(c, d + h * std::sqrt(2)))
{}
point<T> c; // cell center
T h; // half the cell size
T d; // distance from cell center to polygon
T fitness; // fitness of the cell center
T max_fitness; // a "potential" of the cell calculated from max distance to polygon within the cell
};
template <class T>
boost::optional<point<T>> polylabel(polygon<T> const& polygon, T precision = 1)
{
if (polygon.exterior_ring.empty())
{
return boost::none;
}
// find the bounding box of the outer ring
const box2d<T> bbox = envelope(polygon.exterior_ring);
const point<T> size { bbox.width(), bbox.height() };
const T cell_size = std::min(size.x, size.y);
T h = cell_size / 2;
// a priority queue of cells in order of their "potential" (max distance to polygon)
auto compare_func = [] (const cell<T>& a, const cell<T>& b)
{
return a.max_fitness < b.max_fitness;
};
using Queue = std::priority_queue<cell<T>, std::vector<cell<T>>, decltype(compare_func)>;
Queue queue(compare_func);
if (cell_size == 0)
{
return point<T>{ bbox.minx(), bbox.miny() };
}
point<T> centroid;
if (!mapnik::geometry::centroid(polygon, centroid))
{
auto center = bbox.center();
return point<T>{ center.x, center.y };
}
fitness_functor<T> fitness_func(centroid, size);
// cover polygon with initial cells
for (T x = bbox.minx(); x < bbox.maxx(); x += cell_size)
{
for (T y = bbox.miny(); y < bbox.maxy(); y += cell_size)
{
queue.push(cell<T>({x + h, y + h}, h, polygon, fitness_func));
}
}
// take centroid as the first best guess
auto best_cell = cell<T>(centroid, 0, polygon, fitness_func);
while (!queue.empty())
{
// pick the most promising cell from the queue
auto current_cell = queue.top();
queue.pop();
// update the best cell if we found a better one
if (current_cell.fitness > best_cell.fitness)
{
best_cell = current_cell;
}
// do not drill down further if there's no chance of a better solution
if (current_cell.max_fitness - best_cell.fitness <= precision) continue;
// split the cell into four cells
h = current_cell.h / 2;
queue.push(cell<T>({current_cell.c.x - h, current_cell.c.y - h}, h, polygon, fitness_func));
queue.push(cell<T>({current_cell.c.x + h, current_cell.c.y - h}, h, polygon, fitness_func));
queue.push(cell<T>({current_cell.c.x - h, current_cell.c.y + h}, h, polygon, fitness_func));
queue.push(cell<T>({current_cell.c.x + h, current_cell.c.y + h}, h, polygon, fitness_func));
}
return best_cell.c;
}
} // namespace detail
template <class T>
bool interior(polygon<T> const& polygon, double scale_factor, point<T> & pt)
{
// This precision has been chosen to work well in the map (viewport) coordinates.
double precision = 10.0 * scale_factor;
if (boost::optional<point<T>> opt = detail::polylabel(polygon, precision))
{
pt = *opt;
return true;
}
return false;
}
template
bool interior(polygon<double> const& polygon, double scale_factor, point<double> & pt);
} }
<commit_msg>interior, polylabel: Scale precision by polygon size<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/geometry/interior.hpp>
#include <mapnik/geometry_envelope.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/geometry_centroid.hpp>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/optional.hpp>
#pragma GCC diagnostic pop
namespace mapnik { namespace geometry {
// Interior algorithm is realized as a modification of Polylabel algorithm
// from https://github.com/mapbox/polylabel.
// The modification aims to improve visual output by prefering
// placements closer to centroid.
namespace detail {
// get squared distance from a point to a segment
template <class T>
T segment_dist_sq(const point<T>& p,
const point<T>& a,
const point<T>& b)
{
auto x = a.x;
auto y = a.y;
auto dx = b.x - x;
auto dy = b.y - y;
if (dx != 0 || dy != 0) {
auto t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = b.x;
y = b.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return dx * dx + dy * dy;
}
template <class T>
void point_to_ring_dist(point<T> const& point, linear_ring<T> const& ring,
bool & inside, double & min_dist_sq)
{
for (std::size_t i = 0, len = ring.size(), j = len - 1; i < len; j = i++)
{
const auto& a = ring[i];
const auto& b = ring[j];
if ((a.y > point.y) != (b.y > point.y) &&
(point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x)) inside = !inside;
min_dist_sq = std::min(min_dist_sq, segment_dist_sq(point, a, b));
}
}
// signed distance from point to polygon outline (negative if point is outside)
template <class T>
double point_to_polygon_dist(const point<T>& point, const polygon<T>& polygon)
{
bool inside = false;
double min_dist_sq = std::numeric_limits<double>::infinity();
point_to_ring_dist(point, polygon.exterior_ring, inside, min_dist_sq);
for (const auto& ring : polygon.interior_rings)
{
point_to_ring_dist(point, ring, inside, min_dist_sq);
}
return (inside ? 1 : -1) * std::sqrt(min_dist_sq);
}
template <class T>
struct fitness_functor
{
fitness_functor(point<T> const& centroid, point<T> const& polygon_size)
: centroid(centroid),
max_size(std::max(polygon_size.x, polygon_size.y))
{}
T operator()(point<T> const& cell_center, T distance_polygon) const
{
if (distance_polygon <= 0)
{
return distance_polygon;
}
point<T> d(cell_center.x - centroid.x, cell_center.y - centroid.y);
double distance_centroid = std::sqrt(d.x * d.x + d.y * d.y);
return distance_polygon * (1 - distance_centroid / max_size);
}
point<T> centroid;
T max_size;
};
template <class T>
struct cell
{
template <class FitnessFunc>
cell(const point<T>& c_, T h_,
const polygon<T>& polygon,
const FitnessFunc& ff)
: c(c_),
h(h_),
d(point_to_polygon_dist(c, polygon)),
fitness(ff(c, d)),
max_fitness(ff(c, d + h * std::sqrt(2)))
{}
point<T> c; // cell center
T h; // half the cell size
T d; // distance from cell center to polygon
T fitness; // fitness of the cell center
T max_fitness; // a "potential" of the cell calculated from max distance to polygon within the cell
};
template <class T>
point<T> polylabel(polygon<T> const& polygon, box2d<T> const& bbox , T precision = 1)
{
const point<T> size { bbox.width(), bbox.height() };
const T cell_size = std::min(size.x, size.y);
T h = cell_size / 2;
// a priority queue of cells in order of their "potential" (max distance to polygon)
auto compare_func = [] (const cell<T>& a, const cell<T>& b)
{
return a.max_fitness < b.max_fitness;
};
using Queue = std::priority_queue<cell<T>, std::vector<cell<T>>, decltype(compare_func)>;
Queue queue(compare_func);
if (cell_size == 0)
{
return { bbox.minx(), bbox.miny() };
}
point<T> centroid;
if (!mapnik::geometry::centroid(polygon, centroid))
{
auto center = bbox.center();
return { center.x, center.y };
}
fitness_functor<T> fitness_func(centroid, size);
// cover polygon with initial cells
for (T x = bbox.minx(); x < bbox.maxx(); x += cell_size)
{
for (T y = bbox.miny(); y < bbox.maxy(); y += cell_size)
{
queue.push(cell<T>({x + h, y + h}, h, polygon, fitness_func));
}
}
// take centroid as the first best guess
auto best_cell = cell<T>(centroid, 0, polygon, fitness_func);
while (!queue.empty())
{
// pick the most promising cell from the queue
auto current_cell = queue.top();
queue.pop();
// update the best cell if we found a better one
if (current_cell.fitness > best_cell.fitness)
{
best_cell = current_cell;
}
// do not drill down further if there's no chance of a better solution
if (current_cell.max_fitness - best_cell.fitness <= precision) continue;
// split the cell into four cells
h = current_cell.h / 2;
queue.push(cell<T>({current_cell.c.x - h, current_cell.c.y - h}, h, polygon, fitness_func));
queue.push(cell<T>({current_cell.c.x + h, current_cell.c.y - h}, h, polygon, fitness_func));
queue.push(cell<T>({current_cell.c.x - h, current_cell.c.y + h}, h, polygon, fitness_func));
queue.push(cell<T>({current_cell.c.x + h, current_cell.c.y + h}, h, polygon, fitness_func));
}
return best_cell.c;
}
} // namespace detail
template <class T>
bool interior(polygon<T> const& polygon, double scale_factor, point<T> & pt)
{
if (polygon.exterior_ring.empty())
{
return false;
}
const box2d<T> bbox = envelope(polygon.exterior_ring);
// Let the precision be 1% of the polygon size to be independent to map scale.
double precision = (std::max(bbox.width(), bbox.height()) / 100.0) * scale_factor;
pt = detail::polylabel(polygon, bbox, precision);
return true;
}
template
bool interior(polygon<double> const& polygon, double scale_factor, point<double> & pt);
} }
<|endoftext|> |
<commit_before>#ifndef DEDICATED_ONLY
#include "animators.h"
#include "base_animator.h"
#include "sprite_set.h"
#include "gusanos/allegro.h"
AnimPingPong::AnimPingPong( SpriteSet* sprite, int duration )
: BaseAnimator(0), m_totalFrames(sprite->getFramesWidth())
, m_duration(duration), m_animPos(duration)
{
if(m_totalFrames == 1)
{
// This will prevent single-frame sprite sets from breaking
m_totalFrames = 0;
m_animPos = 1;
}
}
void AnimPingPong::tick()
{
if ( freezeTicks <= 0 )
{
m_animPos -= m_totalFrames;
while(m_animPos <= 0)
{
m_animPos += m_duration;
if (m_currentDir == 1)
{
++m_frame;
if(m_frame >= m_totalFrames)
{
m_frame -= 2;
m_currentDir = -1;
}
}
else
{
--m_frame;
if(m_frame < 0)
{
m_frame = 1;
m_currentDir = 1;
}
}
}
}
else
{
--freezeTicks;
}
}
void AnimPingPong::reset()
{
m_animPos = 0;
m_frame = 0;
m_currentDir = 1;
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
AnimLoopRight::AnimLoopRight( SpriteSet* sprite, int duration )
: BaseAnimator(0), m_totalFrames(sprite->getFramesWidth())
, m_duration(duration), m_animPos(duration)
{
}
void AnimLoopRight::tick()
{
if ( freezeTicks <= 0)
{
m_animPos -= m_totalFrames;
while(m_animPos <= 0)
{
m_animPos += m_duration;
++m_frame;
if(m_frame >= m_totalFrames)
m_frame = 0;
}
}
else
{
--freezeTicks;
}
}
void AnimLoopRight::reset()
{
m_animPos = 0;
m_frame = 0;
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
AnimRightOnce::AnimRightOnce( SpriteSet* sprite, int duration )
: BaseAnimator(0), m_totalFrames(sprite->getFramesWidth())
, m_duration(duration), m_animPos(duration)
{
}
void AnimRightOnce::tick()
{
if ( freezeTicks <= 0)
{
m_animPos -= m_totalFrames;
while(m_animPos <= 0)
{
m_animPos += m_duration;
if(m_frame < m_totalFrames - 1)
++m_frame;
}
}
else
{
--freezeTicks;
}
}
void AnimRightOnce::reset()
{
m_animPos = 0;
m_frame = 0;
}
#endif
<commit_msg>fixed https://sourceforge.net/tracker/?func=detail&aid=2989371&group_id=180059&atid=891648<commit_after>#ifndef DEDICATED_ONLY
#include "animators.h"
#include "base_animator.h"
#include "sprite_set.h"
#include "gusanos/allegro.h"
AnimPingPong::AnimPingPong( SpriteSet* sprite, int duration )
: BaseAnimator(0), m_totalFrames(sprite->getFramesWidth())
, m_duration(duration), m_animPos(duration)
{
if(m_totalFrames == 1)
{
// This will prevent single-frame sprite sets from breaking
m_totalFrames = 0;
m_animPos = 1;
}
}
void AnimPingPong::tick()
{
if ( freezeTicks <= 0 )
{
m_animPos -= m_totalFrames;
while(m_animPos <= 0)
{
m_animPos += m_duration;
if (m_currentDir == 1)
{
++m_frame;
if(m_frame >= m_totalFrames)
{
m_frame -= 2;
m_currentDir = -1;
}
}
else
{
--m_frame;
if(m_frame < 0)
{
m_frame = 1;
m_currentDir = 1;
}
}
}
}
else
{
--freezeTicks;
}
}
void AnimPingPong::reset()
{
m_animPos = 0;
m_frame = 0;
m_currentDir = 1;
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
AnimLoopRight::AnimLoopRight( SpriteSet* sprite, int duration )
: BaseAnimator(0), m_totalFrames(sprite ? sprite->getFramesWidth() : 0)
, m_duration(duration), m_animPos(duration)
{
}
void AnimLoopRight::tick()
{
if ( freezeTicks <= 0)
{
m_animPos -= m_totalFrames;
while(m_animPos <= 0)
{
m_animPos += m_duration;
++m_frame;
if(m_frame >= m_totalFrames)
m_frame = 0;
}
}
else
{
--freezeTicks;
}
}
void AnimLoopRight::reset()
{
m_animPos = 0;
m_frame = 0;
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
AnimRightOnce::AnimRightOnce( SpriteSet* sprite, int duration )
: BaseAnimator(0), m_totalFrames(sprite ? sprite->getFramesWidth() : 0)
, m_duration(duration), m_animPos(duration)
{
}
void AnimRightOnce::tick()
{
if ( freezeTicks <= 0)
{
m_animPos -= m_totalFrames;
while(m_animPos <= 0)
{
m_animPos += m_duration;
if(m_frame < m_totalFrames - 1)
++m_frame;
}
}
else
{
--freezeTicks;
}
}
void AnimRightOnce::reset()
{
m_animPos = 0;
m_frame = 0;
}
#endif
<|endoftext|> |
<commit_before>#include "test.h"
#include "TestUtils.h"
#include <fstream>
#include <sstream>
#include "CmakeRegen.h"
#include "Component.h"
#include "Configuration.h"
#include "FstreamInclude.h"
TEST(MakeCmakeComment_Oneline) {
const std::string contents("A oneline comment");
const std::string expectedComment("# A oneline comment\n");
std::string comment;
MakeCmakeComment(comment, contents);
ASSERT(comment == expectedComment);
}
TEST(MakeCmakeComment_Multiline) {
const std::string contents("Multiple\n"
"lines\n"
"in\n"
"comment");
const std::string expectedComment("# Multiple\n"
"# lines\n"
"# in\n"
"# comment\n");
std::string comment;
MakeCmakeComment(comment, contents);
ASSERT(comment == expectedComment);
}
TEST(MakeCmakeComment_Multiline_LastWithEndLine) {
const std::string contents("Multiple\n"
"lines\n"
"in\n"
"comment\n");
const std::string expectedComment("# Multiple\n"
"# lines\n"
"# in\n"
"# comment\n");
std::string comment;
MakeCmakeComment(comment, contents);
ASSERT(comment == expectedComment);
}
TEST(RegenerateCmakeHeader) {
Configuration config;
config.companyName = "My Company";
config.licenseString = "My\nmultiline\nlicense.";
config.regenTag = "AUTOGENERATED";
const std::string expectedOutput(
"#\n"
"# Copyright (c) My Company. All rights reserved.\n"
"# My\n"
"# multiline\n"
"# license.\n"
"#\n"
"\n"
"# AUTOGENERATED - do not edit, your changes will be lost\n"
"# If you must edit, remove these two lines to avoid regeneration\n"
"\n");
std::ostringstream oss;
RegenerateCmakeHeader(oss, config);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddDependencies) {
Component comp("./MyComponent");
comp.buildAfters.insert("ComponentA");
comp.buildAfters.insert("ComponentB");
const std::string expectedOutput(
"add_dependencies(${PROJECT_NAME}\n"
" ComponentA\n"
" ComponentB\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddDependencies(oss, comp);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddDependencies_Empty) {
Component comp("./MyComponent");
std::ostringstream oss;
RegenerateCmakeAddDependencies(oss, comp);
ASSERT(oss.str().empty());
}
TEST(RegenerateCmakeTargetIncludeDirectories_PublicPrivate) {
bool isHeaderOnly = false;
const std::set<std::string> publicIncl{
"public_include_1",
"public_include_2"
};
const std::set<std::string> privateIncl{
"private_include_1",
"private_include_2"
};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" PUBLIC\n"
" public_include_1\n"
" public_include_2\n"
" PRIVATE\n"
" private_include_1\n"
" private_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetIncludeDirectories_Public) {
bool isHeaderOnly = false;
const std::set<std::string> publicIncl{
"public_include_1",
"public_include_2"
};
const std::set<std::string> privateIncl{};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" PUBLIC\n"
" public_include_1\n"
" public_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetIncludeDirectories_Private) {
bool isHeaderOnly = false;
const std::set<std::string> publicIncl{};
const std::set<std::string> privateIncl{
"private_include_1",
"private_include_2"
};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" PRIVATE\n"
" private_include_1\n"
" private_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetIncludeDirectories_Interface) {
bool isHeaderOnly = true;
const std::set<std::string> publicIncl{
"public_include_1",
"public_include_2"
};
const std::set<std::string> privateIncl{
"private_include_1",
"private_include_2"
};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" INTERFACE\n"
" public_include_1\n"
" public_include_2\n"
" private_include_1\n"
" private_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_PublicPrivate) {
bool isHeaderOnly = false;
const std::set<std::string> publicDeps{
"ComponentA",
"ComponentB"
};
const std::set<std::string> privateDeps{
"ComponentZ",
"ComponentY"
};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" PUBLIC\n"
" ComponentA\n"
" ComponentB\n"
" PRIVATE\n"
" ComponentY\n"
" ComponentZ\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_Public) {
bool isHeaderOnly = false;
const std::set<std::string> publicDeps{
"ComponentA",
"ComponentB"
};
const std::set<std::string> privateDeps{};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" PUBLIC\n"
" ComponentA\n"
" ComponentB\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_Private) {
bool isHeaderOnly = false;
const std::set<std::string> publicDeps{};
const std::set<std::string> privateDeps{
"ComponentZ",
"ComponentY"
};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" PRIVATE\n"
" ComponentY\n"
" ComponentZ\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_Interface) {
bool isHeaderOnly = true;
const std::set<std::string> publicDeps{
"ComponentA",
"ComponentB"
};
const std::set<std::string> privateDeps{
"ComponentZ",
"ComponentY"
};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" INTERFACE\n"
" ComponentA\n"
" ComponentB\n"
" ComponentY\n"
" ComponentZ\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_Interface) {
Component comp("./MyComponent/");
comp.type = "add_library";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
bool isHeaderOnly = true;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_library(${PROJECT_NAME} INTERFACE\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_Library) {
Component comp("./MyComponent/");
comp.type = "add_library";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
bool isHeaderOnly = false;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_library(${PROJECT_NAME} STATIC\n"
" Analysis.cpp\n"
" Analysis.h\n"
" main.cpp\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_LibraryAlias) {
Component comp("./MyComponent/");
comp.type = "add_library_alias";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
config.addLibraryAliases.insert("add_library_alias");
bool isHeaderOnly = false;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_library_alias(${PROJECT_NAME} STATIC\n"
" Analysis.cpp\n"
" Analysis.h\n"
" main.cpp\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_Executable) {
Component comp("./MyComponent/");
comp.type = "add_executable";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
bool isHeaderOnly = false;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_executable(${PROJECT_NAME}\n"
" Analysis.cpp\n"
" Analysis.h\n"
" main.cpp\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddSubdirectory_NoSubDirs) {
TemporaryWorkingDirectory workdir(name);
filesystem::create_directories(workdir() / "MyComponent");
Component comp("./MyComponent/");
const std::string expectedOutput("");
std::ostringstream oss;
RegenerateCmakeAddSubdirectory(oss, comp);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddSubdirectory_SubDirsWithAndWithoutCmakeLists) {
TemporaryWorkingDirectory workdir(name);
filesystem::create_directories(workdir() / "MyComponent");
filesystem::create_directories(workdir() / "MyComponent" / "SubComponentA");
std::ofstream((workdir() / "MyComponent" / "SubComponentA" / "CMakeLists.txt").c_str()).close();
filesystem::create_directories(workdir() / "MyComponent" / "SubComponentB");
std::ofstream((workdir() / "MyComponent" / "SubComponentB" / "CMakeLists.txt").c_str()).close();
filesystem::create_directories(workdir() / "MyComponent" / "Data");
Component comp("./MyComponent/");
const std::string expectedOutput(
"add_subdirectory(SubComponentA)\n"
"add_subdirectory(SubComponentB)\n");
std::ostringstream oss;
RegenerateCmakeAddSubdirectory(oss, comp);
ASSERT(oss.str() == expectedOutput);
}
<commit_msg>Add debugging for travis runs.<commit_after>#include "test.h"
#include "TestUtils.h"
#include <fstream>
#include <sstream>
#include "CmakeRegen.h"
#include "Component.h"
#include "Configuration.h"
#include "FstreamInclude.h"
TEST(MakeCmakeComment_Oneline) {
const std::string contents("A oneline comment");
const std::string expectedComment("# A oneline comment\n");
std::string comment;
MakeCmakeComment(comment, contents);
ASSERT(comment == expectedComment);
}
TEST(MakeCmakeComment_Multiline) {
const std::string contents("Multiple\n"
"lines\n"
"in\n"
"comment");
const std::string expectedComment("# Multiple\n"
"# lines\n"
"# in\n"
"# comment\n");
std::string comment;
MakeCmakeComment(comment, contents);
ASSERT(comment == expectedComment);
}
TEST(MakeCmakeComment_Multiline_LastWithEndLine) {
const std::string contents("Multiple\n"
"lines\n"
"in\n"
"comment\n");
const std::string expectedComment("# Multiple\n"
"# lines\n"
"# in\n"
"# comment\n");
std::string comment;
MakeCmakeComment(comment, contents);
ASSERT(comment == expectedComment);
}
TEST(RegenerateCmakeHeader) {
Configuration config;
config.companyName = "My Company";
config.licenseString = "My\nmultiline\nlicense.";
config.regenTag = "AUTOGENERATED";
const std::string expectedOutput(
"#\n"
"# Copyright (c) My Company. All rights reserved.\n"
"# My\n"
"# multiline\n"
"# license.\n"
"#\n"
"\n"
"# AUTOGENERATED - do not edit, your changes will be lost\n"
"# If you must edit, remove these two lines to avoid regeneration\n"
"\n");
std::ostringstream oss;
RegenerateCmakeHeader(oss, config);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddDependencies) {
Component comp("./MyComponent");
comp.buildAfters.insert("ComponentA");
comp.buildAfters.insert("ComponentB");
const std::string expectedOutput(
"add_dependencies(${PROJECT_NAME}\n"
" ComponentA\n"
" ComponentB\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddDependencies(oss, comp);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddDependencies_Empty) {
Component comp("./MyComponent");
std::ostringstream oss;
RegenerateCmakeAddDependencies(oss, comp);
ASSERT(oss.str().empty());
}
TEST(RegenerateCmakeTargetIncludeDirectories_PublicPrivate) {
bool isHeaderOnly = false;
const std::set<std::string> publicIncl{
"public_include_1",
"public_include_2"
};
const std::set<std::string> privateIncl{
"private_include_1",
"private_include_2"
};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" PUBLIC\n"
" public_include_1\n"
" public_include_2\n"
" PRIVATE\n"
" private_include_1\n"
" private_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetIncludeDirectories_Public) {
bool isHeaderOnly = false;
const std::set<std::string> publicIncl{
"public_include_1",
"public_include_2"
};
const std::set<std::string> privateIncl{};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" PUBLIC\n"
" public_include_1\n"
" public_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetIncludeDirectories_Private) {
bool isHeaderOnly = false;
const std::set<std::string> publicIncl{};
const std::set<std::string> privateIncl{
"private_include_1",
"private_include_2"
};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" PRIVATE\n"
" private_include_1\n"
" private_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetIncludeDirectories_Interface) {
bool isHeaderOnly = true;
const std::set<std::string> publicIncl{
"public_include_1",
"public_include_2"
};
const std::set<std::string> privateIncl{
"private_include_1",
"private_include_2"
};
const std::string expectedOutput(
"target_include_directories(${PROJECT_NAME}\n"
" INTERFACE\n"
" public_include_1\n"
" public_include_2\n"
" private_include_1\n"
" private_include_2\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetIncludeDirectories(oss, publicIncl, privateIncl, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_PublicPrivate) {
bool isHeaderOnly = false;
const std::set<std::string> publicDeps{
"ComponentA",
"ComponentB"
};
const std::set<std::string> privateDeps{
"ComponentZ",
"ComponentY"
};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" PUBLIC\n"
" ComponentA\n"
" ComponentB\n"
" PRIVATE\n"
" ComponentY\n"
" ComponentZ\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_Public) {
bool isHeaderOnly = false;
const std::set<std::string> publicDeps{
"ComponentA",
"ComponentB"
};
const std::set<std::string> privateDeps{};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" PUBLIC\n"
" ComponentA\n"
" ComponentB\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_Private) {
bool isHeaderOnly = false;
const std::set<std::string> publicDeps{};
const std::set<std::string> privateDeps{
"ComponentZ",
"ComponentY"
};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" PRIVATE\n"
" ComponentY\n"
" ComponentZ\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeTargetLinkLibraries_Interface) {
bool isHeaderOnly = true;
const std::set<std::string> publicDeps{
"ComponentA",
"ComponentB"
};
const std::set<std::string> privateDeps{
"ComponentZ",
"ComponentY"
};
const std::string expectedOutput(
"target_link_libraries(${PROJECT_NAME}\n"
" INTERFACE\n"
" ComponentA\n"
" ComponentB\n"
" ComponentY\n"
" ComponentZ\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeTargetLinkLibraries(oss, publicDeps, privateDeps, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_Interface) {
Component comp("./MyComponent/");
comp.type = "add_library";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
bool isHeaderOnly = true;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_library(${PROJECT_NAME} INTERFACE\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_Library) {
Component comp("./MyComponent/");
comp.type = "add_library";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
bool isHeaderOnly = false;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_library(${PROJECT_NAME} STATIC\n"
" Analysis.cpp\n"
" Analysis.h\n"
" main.cpp\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_LibraryAlias) {
Component comp("./MyComponent/");
comp.type = "add_library_alias";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
config.addLibraryAliases.insert("add_library_alias");
bool isHeaderOnly = false;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_library_alias(${PROJECT_NAME} STATIC\n"
" Analysis.cpp\n"
" Analysis.h\n"
" main.cpp\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddTarget_Executable) {
Component comp("./MyComponent/");
comp.type = "add_executable";
comp.additionalTargetParameters = " EXCLUDE_FROM_ALL\n";
Configuration config;
bool isHeaderOnly = false;
const std::list<std::string> files{
"Analysis.cpp",
"Analysis.h",
"main.cpp"
};
const std::string expectedOutput(
"add_executable(${PROJECT_NAME}\n"
" Analysis.cpp\n"
" Analysis.h\n"
" main.cpp\n"
" EXCLUDE_FROM_ALL\n"
")\n"
"\n");
std::ostringstream oss;
RegenerateCmakeAddTarget(oss, config, comp, files, isHeaderOnly);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddSubdirectory_NoSubDirs) {
TemporaryWorkingDirectory workdir(name);
filesystem::create_directories(workdir() / "MyComponent");
Component comp("./MyComponent/");
const std::string expectedOutput("");
std::ostringstream oss;
RegenerateCmakeAddSubdirectory(oss, comp);
ASSERT(oss.str() == expectedOutput);
}
TEST(RegenerateCmakeAddSubdirectory_SubDirsWithAndWithoutCmakeLists) {
TemporaryWorkingDirectory workdir(name);
filesystem::create_directories(workdir() / "MyComponent");
filesystem::create_directories(workdir() / "MyComponent" / "SubComponentA");
std::ofstream((workdir() / "MyComponent" / "SubComponentA" / "CMakeLists.txt").c_str()).close();
filesystem::create_directories(workdir() / "MyComponent" / "SubComponentB");
std::ofstream((workdir() / "MyComponent" / "SubComponentB" / "CMakeLists.txt").c_str()).close();
filesystem::create_directories(workdir() / "MyComponent" / "Data");
Component comp("./MyComponent/");
const std::string expectedOutput(
"add_subdirectory(SubComponentA)\n"
"add_subdirectory(SubComponentB)\n");
std::ostringstream oss;
RegenerateCmakeAddSubdirectory(oss, comp);
std::cout << std::endl << oss.str() << std::endl;
ASSERT(oss.str() == expectedOutput);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
class ActiveMapTest
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> {
protected:
static const int kWidth = 208;
static const int kHeight = 144;
ActiveMapTest() : EncoderTest(GET_PARAM(0)) {}
virtual ~ActiveMapTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(GET_PARAM(1));
cpu_used_ = GET_PARAM(2);
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
} else if (video->frame() == 3) {
vpx_active_map_t map = {0};
uint8_t active_map[9 * 13] = {
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1,
0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0,
};
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
ASSERT_EQ(map.cols, 13u);
ASSERT_EQ(map.rows, 9u);
map.active_map = active_map;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
} else if (video->frame() == 15) {
vpx_active_map_t map = {0};
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
map.active_map = NULL;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
}
}
int cpu_used_;
};
TEST_P(ActiveMapTest, Test) {
// Validate that this non multiple of 64 wide clip encodes
cfg_.g_lag_in_frames = 0;
cfg_.rc_target_bitrate = 400;
cfg_.rc_resize_allowed = 0;
cfg_.g_pass = VPX_RC_ONE_PASS;
cfg_.rc_end_usage = VPX_CBR;
cfg_.kf_max_dist = 90000;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", kWidth, kHeight, 30,
1, 0, 20);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
VP9_INSTANTIATE_TEST_CASE(ActiveMapTest,
::testing::Values(::libvpx_test::kRealTime),
::testing::Range(0, 6));
} // namespace
<commit_msg>active_map_test: use vpx_active_map_t() to initialize vars<commit_after>/*
* Copyright (c) 2014 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
class ActiveMapTest
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> {
protected:
static const int kWidth = 208;
static const int kHeight = 144;
ActiveMapTest() : EncoderTest(GET_PARAM(0)) {}
virtual ~ActiveMapTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(GET_PARAM(1));
cpu_used_ = GET_PARAM(2);
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
} else if (video->frame() == 3) {
vpx_active_map_t map = vpx_active_map_t();
uint8_t active_map[9 * 13] = {
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1,
0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0,
};
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
ASSERT_EQ(map.cols, 13u);
ASSERT_EQ(map.rows, 9u);
map.active_map = active_map;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
} else if (video->frame() == 15) {
vpx_active_map_t map = vpx_active_map_t();
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
map.active_map = NULL;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
}
}
int cpu_used_;
};
TEST_P(ActiveMapTest, Test) {
// Validate that this non multiple of 64 wide clip encodes
cfg_.g_lag_in_frames = 0;
cfg_.rc_target_bitrate = 400;
cfg_.rc_resize_allowed = 0;
cfg_.g_pass = VPX_RC_ONE_PASS;
cfg_.rc_end_usage = VPX_CBR;
cfg_.kf_max_dist = 90000;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", kWidth, kHeight, 30,
1, 0, 20);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
VP9_INSTANTIATE_TEST_CASE(ActiveMapTest,
::testing::Values(::libvpx_test::kRealTime),
::testing::Range(0, 6));
} // namespace
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/seq_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,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 workarounds/seq_workarounds.C
/// @brief Workarounds for the SEQ logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <generic/memory/lib/utils/scom.H>
#include <lib/workarounds/seq_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace seq
{
///
/// @brief ODT Config workaround
/// For Nimbus DD1, ODT2 and ODT3 bits are swapped in each of the PHY config registers
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed.
///
fapi2::ReturnCode odt_config( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// skip the workaroud if attribute is not set
if (! mss::chip_ec_feature_mss_odt_config(i_target) )
{
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_INF("Running ODT Config workaround on %s", mss::c_str(i_target));
std::vector<fapi2::buffer<uint64_t>> l_read;
static const std::vector<uint64_t> ODT_REGS =
{
MCA_DDRPHY_SEQ_ODT_RD_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_RD_CONFIG1_P0,
MCA_DDRPHY_SEQ_ODT_WR_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_WR_CONFIG1_P0
};
FAPI_TRY(mss::scom_suckah(i_target, ODT_REGS, l_read));
for (auto& l_data : l_read)
{
// Note these bit positions are the same in RD_CONFIG* and WR_CONFIG*
constexpr uint64_t EVEN_RANK_ODT2 = 50;
constexpr uint64_t EVEN_RANK_ODT3 = 51;
constexpr uint64_t ODD_RANK_ODT2 = 58;
constexpr uint64_t ODD_RANK_ODT3 = 59;
bool l_odt2 = 0;
bool l_odt3 = 0;
// swap even rank ODT2 and ODT3
l_odt2 = l_data.getBit<EVEN_RANK_ODT2>();
l_odt3 = l_data.getBit<EVEN_RANK_ODT3>();
l_data.writeBit<EVEN_RANK_ODT2>(l_odt3).writeBit<EVEN_RANK_ODT3>(l_odt2);
// swap odd rank ODT2 and ODT3
l_odt2 = l_data.getBit<ODD_RANK_ODT2>();
l_odt3 = l_data.getBit<ODD_RANK_ODT3>();
l_data.writeBit<ODD_RANK_ODT2>(l_odt3).writeBit<ODD_RANK_ODT3>(l_odt2);
}
FAPI_TRY(mss::scom_blastah(i_target, ODT_REGS, l_read));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace seq
} // close namespace workarounds
} // close namespace mss
<commit_msg>Update HPW Level for MSS API library<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/seq_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,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 workarounds/seq_workarounds.C
/// @brief Workarounds for the SEQ logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <generic/memory/lib/utils/scom.H>
#include <lib/workarounds/seq_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace seq
{
///
/// @brief ODT Config workaround
/// For Nimbus DD1, ODT2 and ODT3 bits are swapped in each of the PHY config registers
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed.
///
fapi2::ReturnCode odt_config( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// skip the workaroud if attribute is not set
if (! mss::chip_ec_feature_mss_odt_config(i_target) )
{
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_INF("Running ODT Config workaround on %s", mss::c_str(i_target));
std::vector<fapi2::buffer<uint64_t>> l_read;
static const std::vector<uint64_t> ODT_REGS =
{
MCA_DDRPHY_SEQ_ODT_RD_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_RD_CONFIG1_P0,
MCA_DDRPHY_SEQ_ODT_WR_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_WR_CONFIG1_P0
};
FAPI_TRY(mss::scom_suckah(i_target, ODT_REGS, l_read));
for (auto& l_data : l_read)
{
// Note these bit positions are the same in RD_CONFIG* and WR_CONFIG*
constexpr uint64_t EVEN_RANK_ODT2 = 50;
constexpr uint64_t EVEN_RANK_ODT3 = 51;
constexpr uint64_t ODD_RANK_ODT2 = 58;
constexpr uint64_t ODD_RANK_ODT3 = 59;
bool l_odt2 = 0;
bool l_odt3 = 0;
// swap even rank ODT2 and ODT3
l_odt2 = l_data.getBit<EVEN_RANK_ODT2>();
l_odt3 = l_data.getBit<EVEN_RANK_ODT3>();
l_data.writeBit<EVEN_RANK_ODT2>(l_odt3).writeBit<EVEN_RANK_ODT3>(l_odt2);
// swap odd rank ODT2 and ODT3
l_odt2 = l_data.getBit<ODD_RANK_ODT2>();
l_odt3 = l_data.getBit<ODD_RANK_ODT3>();
l_data.writeBit<ODD_RANK_ODT2>(l_odt3).writeBit<ODD_RANK_ODT3>(l_odt2);
}
FAPI_TRY(mss::scom_blastah(i_target, ODT_REGS, l_read));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace seq
} // close namespace workarounds
} // close namespace mss
<|endoftext|> |
<commit_before>#pragma once
#include "../../support/index/Logics.hpp"
#include "../../frontend/Logic.hpp"
#include "../../tags/Cardinality.hpp"
#include "../../support/cardinality.hpp"
#include <boost/tuple/tuple.hpp>
namespace metaSMT {
namespace support {
namespace idx {
namespace cardtags = metaSMT::logic::cardinality::tag;
// attribute ignore
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::ignore>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg arg, std::vector<T> const &args ) {
assert( false && "Unsupported attribute" );
return evaluate(*ctx, logic::False);
}
// attribute constant
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::constant>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg arg, std::vector<T> const &args ) {
return (*ctx)(Tag());
}
// attribute unary
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::unary>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg arg, std::vector<T> const &args ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]));
}
// attribute binary
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::binary>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
assert( args.size() == 2 );
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
// attribute ternary
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::ternary>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]), boost::proto::lit(args[2]));
}
// attribute left_assoc
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::left_assoc>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
if ( args.size() == 2 ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
assert( args.size() >= 2 );
return (*ctx)(Tag(), args);
}
// attribute right_assoc
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::right_assoc>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
// std::cerr << "right_assoc" << '\n';
if ( args.size() == 2 ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
else {
// resolve right associativity
assert( args.size() >= 2 );
typename Context::result_type r = (*ctx)(Tag(), boost::proto::lit(args[args.size()-2]), boost::proto::lit(args[args.size()-1]));
for ( unsigned u = 0; u < args.size()-2; ++u ) {
r = (*ctx)(Tag(), boost::proto::lit(args[args.size()-3-u]), boost::proto::lit(r));
}
return r;
}
}
// attibrute chainable
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::chainable>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
// std::cerr << "chainable" << '\n';
std::cerr << args.size() << '\n';
assert( args.size() == 2 );
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
// attibrute pairwise
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::pairwise>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
// std::cerr << "pairwise" << '\n';
assert( args.size() == 2 );
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
// zero_extend
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
bvtags::zero_extend_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const w = tuple.get<0>();
return (*ctx)(bvtags::zero_extend_tag(), boost::proto::lit(w), boost::proto::lit(args[0]));
}
// sign_extend
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
bvtags::sign_extend_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const w = tuple.get<0>();
return (*ctx)(bvtags::sign_extend_tag(), boost::proto::lit(w), boost::proto::lit(args[0]));
}
// extract
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
bvtags::extract_tag const &,
boost::tuple<unsigned long, unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
unsigned long const op1 = tuple.get<1>();
return (*ctx)(bvtags::extract_tag(), boost::proto::lit(op0), boost::proto::lit(op1), boost::proto::lit(args[0]));
}
// cardinality
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::lt_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::lt_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::le_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::le_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::eq_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::eq_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::ge_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::ge_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::gt_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::gt_tag(), a, op0, impl)
);
}
// fallback
template < typename Context, typename Tag, typename Arg, typename T >
typename Context::result_type
callCtx( Context *ctx,
Tag const &,
Arg const &,
T const & ) {
assert( false && "Unsupported" );
return typename Context::result_type();
}
template < typename Context, typename T, typename Arg >
struct CallByIndexVisitor {
CallByIndexVisitor(Context *ctx,
bool &found,
typename Context::result_type &r,
logic::index idx,
std::vector<T> const &args,
Arg arg)
: ctx(ctx)
, found(found)
, r(r)
, idx(idx)
, args(args)
, arg(arg)
{}
template < typename Tag >
void operator()( Tag const & ) {
if ( !found &&
logic::Index<Tag>::value == idx ) {
found = true;
r = callCtx(ctx, Tag(), arg, args);
}
}
Context *ctx;
bool &found;
typename Context::result_type &r;
logic::index idx;
std::vector<T> const &args;
Arg arg;
}; // CallByIndexVisitor
template < typename Context >
struct CallByIndex {
CallByIndex(Context &ctx)
: ctx(ctx)
{}
template < typename T, typename Arg >
typename Context::result_type
callByIndex( logic::index idx,
std::vector<T> const &args,
Arg p) {
bool found = false;
typename Context::result_type r;
CallByIndexVisitor<Context, T, Arg> visitor(&ctx, found, r, idx, args, p);
boost::mpl::for_each< _all_logic_tags::all_Tags >(visitor);
assert( found );
return r;
}
template < typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
std::vector< typename Context::result_type > const &args) {
return callByIndex(idx, args, arg);
}
template < typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg) {
std::vector< typename Context::result_type > args;
return callByIndex(idx, args, arg);
}
template < typename T, typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
T const &op0 ) {
std::vector< typename Context::result_type > args;
args.push_back( op0 );
return callByIndex(idx, args, arg);
}
template < typename T, typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
T const &op0,
T const &op1 ) {
std::vector< typename Context::result_type > args;
args.push_back( op0 );
args.push_back( op1 );
return callByIndex(idx, args, arg);
}
template < typename T, typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
T const &op0,
T const &op1,
T const &op2 ) {
std::vector< typename Context::result_type > args;
args.push_back( op0 );
args.push_back( op1 );
args.push_back( op2 );
return callByIndex(idx, args, arg);
}
Context &ctx;
}; // CallByIndex
} // idx
} // support
} // metaSMT
<commit_msg>added missing default impl (BDD) for card_eq<commit_after>#pragma once
#include "../../support/index/Logics.hpp"
#include "../../frontend/Logic.hpp"
#include "../../tags/Cardinality.hpp"
#include "../../support/cardinality.hpp"
#include <boost/tuple/tuple.hpp>
namespace metaSMT {
namespace support {
namespace idx {
namespace cardtags = metaSMT::logic::cardinality::tag;
// attribute ignore
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::ignore>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg arg, std::vector<T> const &args ) {
assert( false && "Unsupported attribute" );
return evaluate(*ctx, logic::False);
}
// attribute constant
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::constant>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg arg, std::vector<T> const &args ) {
return (*ctx)(Tag());
}
// attribute unary
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::unary>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg arg, std::vector<T> const &args ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]));
}
// attribute binary
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::binary>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
assert( args.size() == 2 );
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
// attribute ternary
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::ternary>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]), boost::proto::lit(args[2]));
}
// attribute left_assoc
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::left_assoc>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
if ( args.size() == 2 ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
assert( args.size() >= 2 );
return (*ctx)(Tag(), args);
}
// attribute right_assoc
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::right_assoc>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
// std::cerr << "right_assoc" << '\n';
if ( args.size() == 2 ) {
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
else {
// resolve right associativity
assert( args.size() >= 2 );
typename Context::result_type r = (*ctx)(Tag(), boost::proto::lit(args[args.size()-2]), boost::proto::lit(args[args.size()-1]));
for ( unsigned u = 0; u < args.size()-2; ++u ) {
r = (*ctx)(Tag(), boost::proto::lit(args[args.size()-3-u]), boost::proto::lit(r));
}
return r;
}
}
// attibrute chainable
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::chainable>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
// std::cerr << "chainable" << '\n';
std::cerr << args.size() << '\n';
assert( args.size() == 2 );
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
// attibrute pairwise
template < typename Context, typename Tag, typename T, typename Arg >
typename boost::disable_if<
typename boost::mpl::not_<
typename boost::is_same<typename Tag::attribute, attr::pairwise>::type
>::type
, typename Context::result_type
>::type
callCtx( Context *ctx, Tag const &, Arg tuple, std::vector<T> const &args ) {
// std::cerr << "pairwise" << '\n';
assert( args.size() == 2 );
return (*ctx)(Tag(), boost::proto::lit(args[0]), boost::proto::lit(args[1]));
}
// zero_extend
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
bvtags::zero_extend_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const w = tuple.get<0>();
return (*ctx)(bvtags::zero_extend_tag(), boost::proto::lit(w), boost::proto::lit(args[0]));
}
// sign_extend
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
bvtags::sign_extend_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const w = tuple.get<0>();
return (*ctx)(bvtags::sign_extend_tag(), boost::proto::lit(w), boost::proto::lit(args[0]));
}
// extract
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
bvtags::extract_tag const &,
boost::tuple<unsigned long, unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
unsigned long const op1 = tuple.get<1>();
return (*ctx)(bvtags::extract_tag(), boost::proto::lit(op0), boost::proto::lit(op1), boost::proto::lit(args[0]));
}
// cardinality
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::lt_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::lt_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::le_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::le_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::eq_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::eq_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::ge_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::ge_tag(), a, op0, impl)
);
}
template < typename Context, typename T >
typename Context::result_type
callCtx( Context *ctx,
cardtags::gt_tag const &,
boost::tuple<unsigned long> const &tuple,
std::vector<T> const &args ) {
unsigned long const op0 = tuple.get<0>();
std::string const impl = get_option(*ctx, "cardinality-implementation", "bdd");
std::vector< typename Context::result_type > a;
for ( unsigned u = 0; u < args.size(); ++u ) {
a.push_back( evaluate(*ctx, args[u]) );
}
return evaluate(*ctx,
metaSMT::cardinality::cardinality(metaSMT::logic::cardinality::tag::gt_tag(), a, op0, impl)
);
}
// fallback
template < typename Context, typename Tag, typename Arg, typename T >
typename Context::result_type
callCtx( Context *ctx,
Tag const &,
Arg const &,
T const & ) {
assert( false && "Unsupported" );
return typename Context::result_type();
}
template < typename Context, typename T, typename Arg >
struct CallByIndexVisitor {
CallByIndexVisitor(Context *ctx,
bool &found,
typename Context::result_type &r,
logic::index idx,
std::vector<T> const &args,
Arg arg)
: ctx(ctx)
, found(found)
, r(r)
, idx(idx)
, args(args)
, arg(arg)
{}
template < typename Tag >
void operator()( Tag const & ) {
if ( !found &&
logic::Index<Tag>::value == idx ) {
found = true;
r = callCtx(ctx, Tag(), arg, args);
}
}
Context *ctx;
bool &found;
typename Context::result_type &r;
logic::index idx;
std::vector<T> const &args;
Arg arg;
}; // CallByIndexVisitor
template < typename Context >
struct CallByIndex {
CallByIndex(Context &ctx)
: ctx(ctx)
{}
template < typename T, typename Arg >
typename Context::result_type
callByIndex( logic::index idx,
std::vector<T> const &args,
Arg p) {
bool found = false;
typename Context::result_type r;
CallByIndexVisitor<Context, T, Arg> visitor(&ctx, found, r, idx, args, p);
boost::mpl::for_each< _all_logic_tags::all_Tags >(visitor);
assert( found );
return r;
}
template < typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
std::vector< typename Context::result_type > const &args) {
return callByIndex(idx, args, arg);
}
template < typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg) {
std::vector< typename Context::result_type > args;
return callByIndex(idx, args, arg);
}
template < typename T, typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
T const &op0 ) {
std::vector< typename Context::result_type > args;
args.push_back( op0 );
return callByIndex(idx, args, arg);
}
template < typename T, typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
T const &op0,
T const &op1 ) {
std::vector< typename Context::result_type > args;
args.push_back( op0 );
args.push_back( op1 );
return callByIndex(idx, args, arg);
}
template < typename T, typename Arg >
typename Context::result_type operator()( logic::index idx,
Arg arg,
T const &op0,
T const &op1,
T const &op2 ) {
std::vector< typename Context::result_type > args;
args.push_back( op0 );
args.push_back( op1 );
args.push_back( op2 );
return callByIndex(idx, args, arg);
}
Context &ctx;
}; // CallByIndex
} // idx
} // support
} // metaSMT
<|endoftext|> |
<commit_before>#include <mantella_bits/optimisationAlgorithm/samplingBasedOptimisationAlgorithm/gridSearch.hpp>
// Mantella
#include <mantella_bits/helper/assert.hpp>
namespace mant {
GridSearch::GridSearch(
const std::shared_ptr<OptimisationProblem> optimisationProblem)
: SamplingBasedOptimisationAlgorithm(optimisationProblem) {
setNumberOfSamplesPerDimension(arma::zeros<arma::Col<arma::uword>>(numberOfDimensions_) + 10);
}
void GridSearch::optimiseImplementation() {
verify(arma::prod(numberOfSamplesPerDimension_) <= maximalNumberOfIterations_ * numberOfNodes_, "The product of all number of samples per dimension must be less than the maximal number of iterations.");
std::vector<arma::Col<double>> samples;
for (arma::uword n = 0; n < numberOfDimensions_; ++n) {
samples.push_back(arma::linspace<arma::Col<double>>(getLowerBounds()(n), getUpperBounds()(n), numberOfSamplesPerDimension_(n)));
}
arma::Col<arma::uword> sampleIndicies = arma::zeros<arma::Col<arma::uword>>(numberOfDimensions_);
for(arma::uword n = 0; n < arma::prod(numberOfSamplesPerDimension_); ++n) {
if (static_cast<int>(n) % numberOfNodes_ == nodeRank_) {
++numberOfIterations_;
arma::Col<double> candidateParameter(numberOfDimensions_);
for(arma::uword k = 0; k < sampleIndicies.n_elem; ++k) {
candidateParameter(k) = samples.at(k)(sampleIndicies(k));
}
updateBestParameter(candidateParameter, getObjectiveValue(candidateParameter));
if (isFinished()) {
break;
}
}
++sampleIndicies(0);
for(arma::uword k = 0; k < sampleIndicies.n_elem - 1; ++k) {
if(sampleIndicies(k) >= numberOfSamplesPerDimension_(k)) {
sampleIndicies(k) = 0;
++sampleIndicies(k + 1);
} else {
break;
}
}
}
}
void GridSearch::setNumberOfSamplesPerDimension(
const arma::Col<arma::uword>& numberOfSamplesPerDimension) {
verify(numberOfSamplesPerDimension.n_elem == numberOfDimensions_, "The number of elements must be equal to the number of dimensions.");
verify(arma::all(numberOfSamplesPerDimension > 1), ""); // TODO
numberOfSamplesPerDimension_ = numberOfSamplesPerDimension;
}
arma::Col<arma::uword> GridSearch::getNumberOfSamplesPerDimension() const {
return numberOfSamplesPerDimension_;
}
std::string GridSearch::toString() const {
return "grid_search";
}
}
<commit_msg>Fixed [-Wsign-conversion] implicit conversion changes signedness: 'int' to 'unsigned long long'<commit_after>#include <mantella_bits/optimisationAlgorithm/samplingBasedOptimisationAlgorithm/gridSearch.hpp>
// Mantella
#include <mantella_bits/helper/assert.hpp>
namespace mant {
GridSearch::GridSearch(
const std::shared_ptr<OptimisationProblem> optimisationProblem)
: SamplingBasedOptimisationAlgorithm(optimisationProblem) {
setNumberOfSamplesPerDimension(arma::zeros<arma::Col<arma::uword>>(numberOfDimensions_) + 10);
}
void GridSearch::optimiseImplementation() {
verify(arma::prod(numberOfSamplesPerDimension_) <= maximalNumberOfIterations_ * static_cast<arma::uword>(numberOfNodes_), "The product of all number of samples per dimension must be less than the maximal number of iterations.");
std::vector<arma::Col<double>> samples;
for (arma::uword n = 0; n < numberOfDimensions_; ++n) {
samples.push_back(arma::linspace<arma::Col<double>>(getLowerBounds()(n), getUpperBounds()(n), numberOfSamplesPerDimension_(n)));
}
arma::Col<arma::uword> sampleIndicies = arma::zeros<arma::Col<arma::uword>>(numberOfDimensions_);
for(arma::uword n = 0; n < arma::prod(numberOfSamplesPerDimension_); ++n) {
if (static_cast<int>(n) % numberOfNodes_ == nodeRank_) {
++numberOfIterations_;
arma::Col<double> candidateParameter(numberOfDimensions_);
for(arma::uword k = 0; k < sampleIndicies.n_elem; ++k) {
candidateParameter(k) = samples.at(k)(sampleIndicies(k));
}
updateBestParameter(candidateParameter, getObjectiveValue(candidateParameter));
if (isFinished()) {
break;
}
}
++sampleIndicies(0);
for(arma::uword k = 0; k < sampleIndicies.n_elem - 1; ++k) {
if(sampleIndicies(k) >= numberOfSamplesPerDimension_(k)) {
sampleIndicies(k) = 0;
++sampleIndicies(k + 1);
} else {
break;
}
}
}
}
void GridSearch::setNumberOfSamplesPerDimension(
const arma::Col<arma::uword>& numberOfSamplesPerDimension) {
verify(numberOfSamplesPerDimension.n_elem == numberOfDimensions_, "The number of elements must be equal to the number of dimensions.");
verify(arma::all(numberOfSamplesPerDimension > 1), ""); // TODO
numberOfSamplesPerDimension_ = numberOfSamplesPerDimension;
}
arma::Col<arma::uword> GridSearch::getNumberOfSamplesPerDimension() const {
return numberOfSamplesPerDimension_;
}
std::string GridSearch::toString() const {
return "grid_search";
}
}
<|endoftext|> |
<commit_before>#include "./rgtag.h"
#include <id3v2tag.h>
#include <textidentificationframe.h>
#include <relativevolumeframe.h>
#include <xiphcomment.h>
#include <apetag.h>
#include <mpegfile.h>
#include <flacfile.h>
#include <oggfile.h>
#include <vorbisfile.h>
#include <mpcfile.h>
#include <wavpackfile.h>
#include <cmath>
#include <sstream>
void set_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, std::string value) {
TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name);
if (!txxx) {
txxx = new TagLib::ID3v2::UserTextIdentificationFrame;
txxx->setDescription(tag_name);
tag->addFrame(txxx);
}
txxx->setText(value);
}
void clear_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) {
TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name);
if (txxx) {
tag->removeFrame(txxx);
}
}
void set_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, double gain, double peak) {
TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL;
TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2");
TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin();
for (; it != rva2_frame_list.end(); ++it) {
TagLib::ID3v2::RelativeVolumeFrame* fr =
dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it);
if (fr->identification() == tag_name) {
rva2 = fr;
break;
}
}
if (!rva2) {
rva2 = new TagLib::ID3v2::RelativeVolumeFrame;
rva2->setIdentification(tag_name);
tag->addFrame(rva2);
}
rva2->setChannelType(TagLib::ID3v2::RelativeVolumeFrame::MasterVolume);
rva2->setVolumeAdjustment(gain);
TagLib::ID3v2::RelativeVolumeFrame::PeakVolume peak_volume;
peak_volume.bitsRepresentingPeak = 16;
double amp_peak = peak * 32768.0 > 65535.0 ? 65535.0 : peak * 32768.0;
unsigned int amp_peak_int = static_cast<unsigned int>(std::ceil(amp_peak));
TagLib::ByteVector bv_uint = TagLib::ByteVector::fromUInt(amp_peak_int);
peak_volume.peakVolume = TagLib::ByteVector(&(bv_uint.data()[2]), 2);
rva2->setPeakVolume(peak_volume);
}
void clear_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) {
TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL;
TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2");
TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin();
for (; it != rva2_frame_list.end(); ++it) {
TagLib::ID3v2::RelativeVolumeFrame* fr =
dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it);
if (fr->identification() == tag_name) {
rva2 = fr;
break;
}
}
if (rva2) {
tag->removeFrame(rva2);
}
}
void set_rg_info(const char* filename,
double track_gain,
double track_peak,
int album_mode,
double album_gain,
double album_peak) {
std::string fn(filename);
std::string ag, tg, ap, tp;
std::stringstream ss;
ss.precision(2);
ss << std::fixed;
ss << album_gain; ss >> ag; ss.clear();
ss << track_gain; ss >> tg; ss.clear();
ss.precision(8);
ss << album_peak; ss >> ap; ss.clear();
ss << track_peak; ss >> tp; ss.clear();
std::string extension = fn.substr(fn.find_last_of(".") + 1);
if (extension == "mp3") {
TagLib::MPEG::File f(filename);
TagLib::ID3v2::Tag* id3v2tag = f.ID3v2Tag(true);
set_txxx_tag(id3v2tag, "replaygain_track_gain", tg + " dB");
set_txxx_tag(id3v2tag, "replaygain_track_peak", tp);
set_rva2_tag(id3v2tag, "track", track_gain, track_peak);
if (album_mode) {
set_txxx_tag(id3v2tag, "replaygain_album_gain", ag + " dB");
set_txxx_tag(id3v2tag, "replaygain_album_peak", ap);
set_rva2_tag(id3v2tag, "album", album_gain, album_peak);
} else {
clear_txxx_tag(id3v2tag, "replaygain_album_gain");
clear_txxx_tag(id3v2tag, "replaygain_album_peak");
clear_rva2_tag(id3v2tag, "album");
}
f.save();
} else if (extension == "flac" || extension == "ogg" || extension == "oga") {
TagLib::File* file = NULL;
TagLib::Ogg::XiphComment* xiph = NULL;
if (extension == "flac") {
TagLib::FLAC::File* f = new TagLib::FLAC::File(filename);
xiph = f->xiphComment(true);
file = f;
} else if (extension == "ogg" || extension == "oga") {
TagLib::Ogg::Vorbis::File* f = new TagLib::Ogg::Vorbis::File(filename);
xiph = f->tag();
file = f;
}
xiph->addField("replaygain_track_gain", tg + " dB");
xiph->addField("replaygain_track_peak", tp);
if (album_mode) {
xiph->addField("replaygain_album_gain", ag + " dB");
xiph->addField("replaygain_album_peak", ap);
} else {
xiph->removeField("replaygain_album_gain");
xiph->removeField("replaygain_album_peak");
}
file->save();
delete file;
} else if (extension == "mpc" || extension == "wv") {
TagLib::File* file = NULL;
TagLib::APE::Tag* ape = NULL;
if (extension == "mpc") {
TagLib::MPC::File* f = new TagLib::MPC::File(filename);
ape = f->APETag(true);
file = f;
} else if (extension == "wv") {
TagLib::WavPack::File* f = new TagLib::WavPack::File(filename);
ape = f->APETag(true);
file = f;
}
ape->addValue("replaygain_track_gain", tg + " dB");
ape->addValue("replaygain_track_peak", tp);
if (album_mode) {
ape->addValue("replaygain_album_gain", ag + " dB");
ape->addValue("replaygain_album_peak", ap);
} else {
ape->removeItem("replaygain_album_gain");
ape->removeItem("replaygain_album_peak");
}
file->save();
delete file;
}
}
#if 0
int main(int argc, char* argv[]) {
double track_gain, track_peak, album_gain, album_peak;
int album_mode = atoi(argv[2]);
track_gain = atof(argv[3]);
track_peak = atof(argv[4]);
album_gain = atof(argv[5]);
album_peak = atof(argv[6]);
set_rg_info(argv[1], track_gain, track_peak, album_mode,
album_gain, album_peak);
return 0;
}
#endif
<commit_msg>taglib: correctly remove fields<commit_after>#include "./rgtag.h"
#include <id3v2tag.h>
#include <textidentificationframe.h>
#include <relativevolumeframe.h>
#include <xiphcomment.h>
#include <apetag.h>
#include <mpegfile.h>
#include <flacfile.h>
#include <oggfile.h>
#include <vorbisfile.h>
#include <mpcfile.h>
#include <wavpackfile.h>
#include <cmath>
#include <sstream>
void set_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, std::string value) {
TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name);
if (!txxx) {
txxx = new TagLib::ID3v2::UserTextIdentificationFrame;
txxx->setDescription(tag_name);
tag->addFrame(txxx);
}
txxx->setText(value);
}
void clear_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) {
TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name);
if (txxx) {
tag->removeFrame(txxx);
}
}
void set_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, double gain, double peak) {
TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL;
TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2");
TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin();
for (; it != rva2_frame_list.end(); ++it) {
TagLib::ID3v2::RelativeVolumeFrame* fr =
dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it);
if (fr->identification() == tag_name) {
rva2 = fr;
break;
}
}
if (!rva2) {
rva2 = new TagLib::ID3v2::RelativeVolumeFrame;
rva2->setIdentification(tag_name);
tag->addFrame(rva2);
}
rva2->setChannelType(TagLib::ID3v2::RelativeVolumeFrame::MasterVolume);
rva2->setVolumeAdjustment(gain);
TagLib::ID3v2::RelativeVolumeFrame::PeakVolume peak_volume;
peak_volume.bitsRepresentingPeak = 16;
double amp_peak = peak * 32768.0 > 65535.0 ? 65535.0 : peak * 32768.0;
unsigned int amp_peak_int = static_cast<unsigned int>(std::ceil(amp_peak));
TagLib::ByteVector bv_uint = TagLib::ByteVector::fromUInt(amp_peak_int);
peak_volume.peakVolume = TagLib::ByteVector(&(bv_uint.data()[2]), 2);
rva2->setPeakVolume(peak_volume);
}
void clear_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) {
TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL;
TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2");
TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin();
for (; it != rva2_frame_list.end(); ++it) {
TagLib::ID3v2::RelativeVolumeFrame* fr =
dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it);
if (fr->identification() == tag_name) {
rva2 = fr;
break;
}
}
if (rva2) {
tag->removeFrame(rva2);
}
}
void set_rg_info(const char* filename,
double track_gain,
double track_peak,
int album_mode,
double album_gain,
double album_peak) {
std::string fn(filename);
std::string ag, tg, ap, tp;
std::stringstream ss;
ss.precision(2);
ss << std::fixed;
ss << album_gain; ss >> ag; ss.clear();
ss << track_gain; ss >> tg; ss.clear();
ss.precision(8);
ss << album_peak; ss >> ap; ss.clear();
ss << track_peak; ss >> tp; ss.clear();
std::string extension = fn.substr(fn.find_last_of(".") + 1);
if (extension == "mp3") {
TagLib::MPEG::File f(filename);
TagLib::ID3v2::Tag* id3v2tag = f.ID3v2Tag(true);
set_txxx_tag(id3v2tag, "replaygain_track_gain", tg + " dB");
set_txxx_tag(id3v2tag, "replaygain_track_peak", tp);
set_rva2_tag(id3v2tag, "track", track_gain, track_peak);
if (album_mode) {
set_txxx_tag(id3v2tag, "replaygain_album_gain", ag + " dB");
set_txxx_tag(id3v2tag, "replaygain_album_peak", ap);
set_rva2_tag(id3v2tag, "album", album_gain, album_peak);
} else {
clear_txxx_tag(id3v2tag, "replaygain_album_gain");
clear_txxx_tag(id3v2tag, "replaygain_album_peak");
clear_rva2_tag(id3v2tag, "album");
}
f.save();
} else if (extension == "flac" || extension == "ogg" || extension == "oga") {
TagLib::File* file = NULL;
TagLib::Ogg::XiphComment* xiph = NULL;
if (extension == "flac") {
TagLib::FLAC::File* f = new TagLib::FLAC::File(filename);
xiph = f->xiphComment(true);
file = f;
} else if (extension == "ogg" || extension == "oga") {
TagLib::Ogg::Vorbis::File* f = new TagLib::Ogg::Vorbis::File(filename);
xiph = f->tag();
file = f;
}
xiph->addField("replaygain_track_gain", tg + " dB");
xiph->addField("replaygain_track_peak", tp);
if (album_mode) {
xiph->addField("replaygain_album_gain", ag + " dB");
xiph->addField("replaygain_album_peak", ap);
} else {
xiph->removeField("replaygain_album_gain");
xiph->removeField("replaygain_album_peak");
xiph->removeField("REPLAYGAIN_ALBUM_GAIN");
xiph->removeField("REPLAYGAIN_ALBUM_PEAK");
}
file->save();
delete file;
} else if (extension == "mpc" || extension == "wv") {
TagLib::File* file = NULL;
TagLib::APE::Tag* ape = NULL;
if (extension == "mpc") {
TagLib::MPC::File* f = new TagLib::MPC::File(filename);
ape = f->APETag(true);
file = f;
} else if (extension == "wv") {
TagLib::WavPack::File* f = new TagLib::WavPack::File(filename);
ape = f->APETag(true);
file = f;
}
ape->addValue("replaygain_track_gain", tg + " dB");
ape->addValue("replaygain_track_peak", tp);
if (album_mode) {
ape->addValue("replaygain_album_gain", ag + " dB");
ape->addValue("replaygain_album_peak", ap);
} else {
ape->removeItem("replaygain_album_gain");
ape->removeItem("replaygain_album_peak");
ape->removeItem("REPLAYGAIN_ALBUM_GAIN");
ape->removeItem("REPLAYGAIN_ALBUM_PEAK");
}
file->save();
delete file;
}
}
#if 0
int main(int argc, char* argv[]) {
double track_gain, track_peak, album_gain, album_peak;
int album_mode = atoi(argv[2]);
track_gain = atof(argv[3]);
track_peak = atof(argv[4]);
album_gain = atof(argv[5]);
album_peak = atof(argv[6]);
set_rg_info(argv[1], track_gain, track_peak, album_mode,
album_gain, album_peak);
return 0;
}
#endif
<|endoftext|> |
<commit_before>#include <cassert>
#include <string>
#include <vector>
#include <map>
#include "variable.h"
#include "formula.h"
#include "registry.h"
using namespace std;
extern bool CaselessStrCmp(const string& lhs, const string& rhs);
#ifndef NSBML
#include "sbmlx.h"
// SBase objects no longer have IDs :( //update: now they do again!
string getNameFromSBMLObject(const SBase* sbml, string basename)
{
string name = sbml->getId();
if (name == "") {
name = sbml->getName();
//Names can have spaces, so...
while (name.find(" ") != string::npos) {
name.replace(name.find(" "), 1, "_");
}
}
if (name=="") {
long num=0;
Variable* foundvar = NULL;
do {
char charnum[50];
sprintf(charnum, "%li", num);
num++;
name = basename;
name += charnum;
vector<string> fullname;
fullname.push_back(name);
foundvar = g_registry.CurrentModule()->GetVariable(fullname);
} while (foundvar != NULL);
}
assert(name != "");
if (name != sbml->getId()) {
SBase* varsbml = const_cast<SBase*>(sbml);
varsbml->setId(name);
}
return name;
}
/*
string getNameFromSBMLObject(string ID, string name, string basename)
{
if (ID != "") return ID;
if (name != "") return name;
long num=0;
Variable* foundvar = NULL;
do {
char charnum[50];
sprintf(charnum, "%li", num);
num++;
name = basename;
name += charnum;
vector<string> fullname;
fullname.push_back(name);
foundvar = g_registry.CurrentModule()->GetVariable(fullname);
} while (foundvar != NULL);
assert(name != "");
return name;
}
*/
void matchNamesToTypes(ASTNode *node)
{
if (node->getType() == AST_NAME_TIME) {
node->setName("time");
}
if (node->getType() == AST_NAME_AVOGADRO) {
node->setName("avogadro");
}
if (node->getType() == AST_FUNCTION_DELAY) {
node->setName("delay");
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
matchNamesToTypes(node->getChild(c));
}
}
string parseASTNodeToString(const ASTNode* ASTform, bool carat) {
if (ASTform==NULL) return "";
ASTNode clone(*ASTform);
matchNamesToTypes(&clone);
if (carat) {
powerToCarat(&clone);
}
char* formula = SBML_formulaToString(&clone);
string ret = formula;
#ifndef WIN32
free(formula);
#endif
return ret;
}
void matchTypesToNames(ASTNode_t* node)
{
if (node->isOperator() == false && node->isNumber() == false) {
if (string(node->getName()) == "time") {
node->setType(AST_NAME_TIME);
}
if (string(node->getName()) == "avogadro") {
node->setType(AST_NAME_AVOGADRO);
}
if (string(node->getName()) == "delay") {
node->setType(AST_FUNCTION_DELAY);
}
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
matchTypesToNames(node->getChild(c));
}
}
ASTNode* parseStringToASTNode(const string& formula)
{
L3ParserSettings l3ps;
l3ps.setParseCollapseMinus(true);
l3ps.setParseLog(L3P_PARSE_LOG_AS_LOG10);
ASTNode* rootnode = SBML_parseL3FormulaWithSettings(formula.c_str(), &l3ps);
if (rootnode == NULL) {
g_registry.SetError(SBML_getLastParseL3Error());
return NULL;
}
if (formula.find("time") != string::npos ||
formula.find("avogadro") != string::npos ||
formula.find("delay") != string::npos) {
matchTypesToNames(rootnode);
}
return rootnode;
}
void caratToPower(ASTNode* node)
{
if (node->getType() == AST_POWER) {
node->setType(AST_FUNCTION_POWER);
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
caratToPower(node->getChild(c));
}
}
void powerToCarat(ASTNode* node)
{
if (node->getType() == AST_FUNCTION_POWER) {
node->setType(AST_POWER);
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
powerToCarat(node->getChild(c));
}
}
set<string> GetUnitNames(ASTNode* astn)
{
set<string> ret;
if (astn==NULL) return ret;
if (astn->isSetUnits()) {
ret.insert(astn->getUnits());
}
for (unsigned int c=0; c<astn->getNumChildren(); c++) {
set<string> addme = GetUnitNames(astn->getChild(c));
ret.insert(addme.begin(), addme.end());
}
return ret;
}
double GetValueFrom(ASTNode* astn)
{
switch (astn->getType()) {
case AST_RATIONAL:
case AST_REAL:
case AST_REAL_E:
return astn->getReal();
case AST_INTEGER:
return astn->getInteger();
default:
assert(false);
return 0;
}
}
UnitDef GetUnitDefFrom(const UnitDefinition* unitdefinition, string modulename)
{
UnitDef ret(unitdefinition->getId(), modulename);
ret.ClearComponents();
for (unsigned int ue=0; ue<unitdefinition->getNumUnits(); ue++) {
const Unit* unit = unitdefinition->getUnit(ue);
ret.AddUnitElement(unit);
}
return ret;
}
#endif
//SBML models might have variable names in them that are reserved keywords in Antimony (like 'compartment', to take a huge example). FixName fixes this so that you can output readable Antimony again.
bool FixName(string& name)
{
while (name.size() && name[0] == ' ') {
name.erase(0, 1);
}
while (name.size() && name[name.size()-1] == ' ') {
name.erase(name.size()-1, 1);
}
const char* keywords[] = {
"DNA",
"at",
"compartment",
"const",
"delete",
"end",
"event",
"ext",
"formula",
"function",
"gene",
"has",
"import",
"in",
"is",
"model",
"module",
"operator",
"reaction",
"species",
"var",
"abs"
, "acos"
, "arccos"
, "acosh"
, "arccosh"
, "acot"
, "arccot"
, "acoth"
, "arccoth"
, "acsc"
, "arccsc"
, "acsch"
, "arccsch"
, "asec"
, "arcsec"
, "asech"
, "arcsech"
, "asin"
, "arcsin"
, "atan"
, "arctan"
, "atanh"
, "arctanh"
, "ceil"
, "ceiling"
, "cos"
, "cosh"
, "cot"
, "coth"
, "csc"
, "csch"
, "delay"
, "exp"
, "factorial"
, "floor"
, "log"
, "ln"
, "log10"
, "piecewise"
, "power"
, "pow"
, "sqr"
, "sqrt"
, "root"
, "sech"
, "sin"
, "sinh"
, "tan"
, "tanh"
, "and"
, "not"
, "or"
, "xor"
, "eq"
, "equals"
, "geq"
, "gt"
, "leq"
, "lt"
, "neq"
, "divide"
, "minus"
, "plus"
, "times"
, "true"
, "false"
, "pi"
, "exponentiale"
, "avogadro"
, "time"
, "inf"
, "infinity"
, "nan"
, "notanumber"
};
for (size_t kw=0; kw<94; kw++) {
if (CaselessStrCmp(name, keywords[kw])) {
name += "_";
return true;
}
}
for (size_t pos=0; pos<name.size(); pos++) {
if (!(isalpha(name[pos]) || isdigit(name[pos]) || name[pos]=='_')) {
name[pos] = '_';
}
}
return false;
}
bool FixName(vector<string>& names)
{
bool ret = false;
for (size_t n=0; n<names.size(); n++) {
if (FixName(names[n])) {
ret = true;
}
}
return ret;
}
void FixName(vector<vector<string> >& allnames)
{
for (size_t n=0; n<allnames.size(); n++) {
FixName(allnames[n]);
}
}
void FixName(map<vector<string>, Variable*>& varmap)
{
for (map<vector<string>, Variable*>::iterator vm=varmap.begin(); vm != varmap.end();)
{
vector<string> name = vm->first;
if (FixName(name)) {
map<vector<string>, Variable*>::iterator vm2 = vm;
vm++;
varmap.insert(make_pair(name, vm2->second));
varmap.erase(vm2);
}
else {
vm++;
}
}
}
#ifdef USE_COMP
Model* getModelFromExternalModelDefinition(const ExternalModelDefinition* cextmoddef)
{
ExternalModelDefinition* extmoddef = const_cast<ExternalModelDefinition*>(cextmoddef);
Model* extmod = extmoddef->getReferencedModel();
if (extmod == NULL) {
string error = "Unable to open ";
if (extmoddef->isSetModelRef()) {
error += "the model " + extmoddef->getModelRef() + " from ";
}
if (extmoddef->isSetSource()) {
error += "the URI " + extmoddef->getSource() + ".";
}
else {
error += "the external model definition, because it did not have the required 'source' attribute.";
}
g_registry.AddWarning(error);
}
return extmod;
}
#endif
<commit_msg>Natural logs weren't being round-tripped properly (whoops).<commit_after>#include <cassert>
#include <string>
#include <vector>
#include <map>
#include "variable.h"
#include "formula.h"
#include "registry.h"
using namespace std;
extern bool CaselessStrCmp(const string& lhs, const string& rhs);
#ifndef NSBML
#include "sbmlx.h"
// SBase objects no longer have IDs :( //update: now they do again!
string getNameFromSBMLObject(const SBase* sbml, string basename)
{
string name = sbml->getId();
if (name == "") {
name = sbml->getName();
//Names can have spaces, so...
while (name.find(" ") != string::npos) {
name.replace(name.find(" "), 1, "_");
}
}
if (name=="") {
long num=0;
Variable* foundvar = NULL;
do {
char charnum[50];
sprintf(charnum, "%li", num);
num++;
name = basename;
name += charnum;
vector<string> fullname;
fullname.push_back(name);
foundvar = g_registry.CurrentModule()->GetVariable(fullname);
} while (foundvar != NULL);
}
assert(name != "");
if (name != sbml->getId()) {
SBase* varsbml = const_cast<SBase*>(sbml);
varsbml->setId(name);
}
return name;
}
/*
string getNameFromSBMLObject(string ID, string name, string basename)
{
if (ID != "") return ID;
if (name != "") return name;
long num=0;
Variable* foundvar = NULL;
do {
char charnum[50];
sprintf(charnum, "%li", num);
num++;
name = basename;
name += charnum;
vector<string> fullname;
fullname.push_back(name);
foundvar = g_registry.CurrentModule()->GetVariable(fullname);
} while (foundvar != NULL);
assert(name != "");
return name;
}
*/
void matchNamesToTypes(ASTNode *node)
{
if (node->getType() == AST_NAME_TIME) {
node->setName("time");
}
if (node->getType() == AST_NAME_AVOGADRO) {
node->setName("avogadro");
}
if (node->getType() == AST_FUNCTION_DELAY) {
node->setName("delay");
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
matchNamesToTypes(node->getChild(c));
}
}
string parseASTNodeToString(const ASTNode* ASTform, bool carat) {
if (ASTform==NULL) return "";
ASTNode clone(*ASTform);
matchNamesToTypes(&clone);
if (carat) {
powerToCarat(&clone);
}
char* formula = SBML_formulaToString(&clone);
string ret = formula;
#ifndef WIN32
free(formula);
#endif
return ret;
}
void matchTypesToNames(ASTNode_t* node)
{
if (node->isOperator() == false && node->isNumber() == false) {
if (string(node->getName()) == "time") {
node->setType(AST_NAME_TIME);
}
if (string(node->getName()) == "avogadro") {
node->setType(AST_NAME_AVOGADRO);
}
if (string(node->getName()) == "delay") {
node->setType(AST_FUNCTION_DELAY);
}
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
matchTypesToNames(node->getChild(c));
}
}
ASTNode* parseStringToASTNode(const string& formula)
{
L3ParserSettings l3ps;
l3ps.setParseCollapseMinus(true);
l3ps.setParseLog(L3P_PARSE_LOG_AS_LN);
ASTNode* rootnode = SBML_parseL3FormulaWithSettings(formula.c_str(), &l3ps);
if (rootnode == NULL) {
g_registry.SetError(SBML_getLastParseL3Error());
return NULL;
}
if (formula.find("time") != string::npos ||
formula.find("avogadro") != string::npos ||
formula.find("delay") != string::npos) {
matchTypesToNames(rootnode);
}
return rootnode;
}
void caratToPower(ASTNode* node)
{
if (node->getType() == AST_POWER) {
node->setType(AST_FUNCTION_POWER);
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
caratToPower(node->getChild(c));
}
}
void powerToCarat(ASTNode* node)
{
if (node->getType() == AST_FUNCTION_POWER) {
node->setType(AST_POWER);
}
for (unsigned int c = 0; c < node->getNumChildren() ; c++) {
powerToCarat(node->getChild(c));
}
}
set<string> GetUnitNames(ASTNode* astn)
{
set<string> ret;
if (astn==NULL) return ret;
if (astn->isSetUnits()) {
ret.insert(astn->getUnits());
}
for (unsigned int c=0; c<astn->getNumChildren(); c++) {
set<string> addme = GetUnitNames(astn->getChild(c));
ret.insert(addme.begin(), addme.end());
}
return ret;
}
double GetValueFrom(ASTNode* astn)
{
switch (astn->getType()) {
case AST_RATIONAL:
case AST_REAL:
case AST_REAL_E:
return astn->getReal();
case AST_INTEGER:
return astn->getInteger();
default:
assert(false);
return 0;
}
}
UnitDef GetUnitDefFrom(const UnitDefinition* unitdefinition, string modulename)
{
UnitDef ret(unitdefinition->getId(), modulename);
ret.ClearComponents();
for (unsigned int ue=0; ue<unitdefinition->getNumUnits(); ue++) {
const Unit* unit = unitdefinition->getUnit(ue);
ret.AddUnitElement(unit);
}
return ret;
}
#endif
//SBML models might have variable names in them that are reserved keywords in Antimony (like 'compartment', to take a huge example). FixName fixes this so that you can output readable Antimony again.
bool FixName(string& name)
{
while (name.size() && name[0] == ' ') {
name.erase(0, 1);
}
while (name.size() && name[name.size()-1] == ' ') {
name.erase(name.size()-1, 1);
}
const char* keywords[] = {
"DNA",
"at",
"compartment",
"const",
"delete",
"end",
"event",
"ext",
"formula",
"function",
"gene",
"has",
"import",
"in",
"is",
"model",
"module",
"operator",
"reaction",
"species",
"var",
"abs"
, "acos"
, "arccos"
, "acosh"
, "arccosh"
, "acot"
, "arccot"
, "acoth"
, "arccoth"
, "acsc"
, "arccsc"
, "acsch"
, "arccsch"
, "asec"
, "arcsec"
, "asech"
, "arcsech"
, "asin"
, "arcsin"
, "atan"
, "arctan"
, "atanh"
, "arctanh"
, "ceil"
, "ceiling"
, "cos"
, "cosh"
, "cot"
, "coth"
, "csc"
, "csch"
, "delay"
, "exp"
, "factorial"
, "floor"
, "log"
, "ln"
, "log10"
, "piecewise"
, "power"
, "pow"
, "sqr"
, "sqrt"
, "root"
, "sech"
, "sin"
, "sinh"
, "tan"
, "tanh"
, "and"
, "not"
, "or"
, "xor"
, "eq"
, "equals"
, "geq"
, "gt"
, "leq"
, "lt"
, "neq"
, "divide"
, "minus"
, "plus"
, "times"
, "true"
, "false"
, "pi"
, "exponentiale"
, "avogadro"
, "time"
, "inf"
, "infinity"
, "nan"
, "notanumber"
};
for (size_t kw=0; kw<94; kw++) {
if (CaselessStrCmp(name, keywords[kw])) {
name += "_";
return true;
}
}
for (size_t pos=0; pos<name.size(); pos++) {
if (!(isalpha(name[pos]) || isdigit(name[pos]) || name[pos]=='_')) {
name[pos] = '_';
}
}
return false;
}
bool FixName(vector<string>& names)
{
bool ret = false;
for (size_t n=0; n<names.size(); n++) {
if (FixName(names[n])) {
ret = true;
}
}
return ret;
}
void FixName(vector<vector<string> >& allnames)
{
for (size_t n=0; n<allnames.size(); n++) {
FixName(allnames[n]);
}
}
void FixName(map<vector<string>, Variable*>& varmap)
{
for (map<vector<string>, Variable*>::iterator vm=varmap.begin(); vm != varmap.end();)
{
vector<string> name = vm->first;
if (FixName(name)) {
map<vector<string>, Variable*>::iterator vm2 = vm;
vm++;
varmap.insert(make_pair(name, vm2->second));
varmap.erase(vm2);
}
else {
vm++;
}
}
}
#ifdef USE_COMP
Model* getModelFromExternalModelDefinition(const ExternalModelDefinition* cextmoddef)
{
ExternalModelDefinition* extmoddef = const_cast<ExternalModelDefinition*>(cextmoddef);
Model* extmod = extmoddef->getReferencedModel();
if (extmod == NULL) {
string error = "Unable to open ";
if (extmoddef->isSetModelRef()) {
error += "the model " + extmoddef->getModelRef() + " from ";
}
if (extmoddef->isSetSource()) {
error += "the URI " + extmoddef->getSource() + ".";
}
else {
error += "the external model definition, because it did not have the required 'source' attribute.";
}
g_registry.AddWarning(error);
}
return extmod;
}
#endif
<|endoftext|> |
<commit_before>#include "./shadow_constraint_drawer.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <vector>
#include "../utils/memory.h"
#include "../graphics/vertex_array.h"
#include "./constraint_drawer.h"
ShadowConstraintDrawer::ShadowConstraintDrawer(
int width, int height)
: width(width), height(height)
{
Eigen::Affine3f pixelToNDCTransform(
Eigen::Translation3f(Eigen::Vector3f(-1, -1, 0)) *
Eigen::Scaling(Eigen::Vector3f(2.0f / width, 2.0f / height, 1)));
Eigen::Matrix4f pixelToNDC = pixelToNDCTransform.matrix();
renderData.viewMatrix = pixelToNDC;
renderData.viewProjectionMatrix = pixelToNDC;
}
ShadowConstraintDrawer::~ShadowConstraintDrawer()
{
}
void ShadowConstraintDrawer::initialize(Graphics::Gl *gl,
std::shared_ptr<Graphics::ShaderManager> shaderManager)
{
this->gl = gl;
constraintDrawer = std::make_unique<ConstraintDrawer>(
gl, shaderManager, ":/shader/line_constraint.vert",
":/shader/constraint.geom");
const int maxLabelCount = 100;
vertexArray = std::make_unique<Graphics::VertexArray>(gl, GL_POINTS, 2);
vertexArray->addStream(maxLabelCount, 2);
vertexArray->addStream(maxLabelCount, 2);
vertexArray->addStream(maxLabelCount, 2);
}
void ShadowConstraintDrawer::update(const std::vector<float> &sources,
const std::vector<float> &starts,
const std::vector<float> &ends)
{
vertexArray->updateStream(0, sources);
vertexArray->updateStream(1, starts);
vertexArray->updateStream(2, ends);
}
void ShadowConstraintDrawer::draw(float color, Eigen::Vector2f halfSize)
{
constraintDrawer->draw(vertexArray.get(), renderData, color, halfSize);
}
void ShadowConstraintDrawer::clear()
{
gl->glViewport(0, 0, width, height);
gl->glClearColor(0, 0, 0, 0);
gl->glClear(GL_COLOR_BUFFER_BIT);
}
<commit_msg>Minor: fix linting errors.<commit_after>#include "./shadow_constraint_drawer.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <vector>
#include "../utils/memory.h"
#include "../graphics/vertex_array.h"
#include "./constraint_drawer.h"
ShadowConstraintDrawer::ShadowConstraintDrawer(int width, int height)
: width(width), height(height)
{
Eigen::Affine3f pixelToNDCTransform(
Eigen::Translation3f(Eigen::Vector3f(-1, -1, 0)) *
Eigen::Scaling(Eigen::Vector3f(2.0f / width, 2.0f / height, 1)));
Eigen::Matrix4f pixelToNDC = pixelToNDCTransform.matrix();
renderData.viewMatrix = pixelToNDC;
renderData.viewProjectionMatrix = pixelToNDC;
}
ShadowConstraintDrawer::~ShadowConstraintDrawer()
{
}
void ShadowConstraintDrawer::initialize(
Graphics::Gl *gl, std::shared_ptr<Graphics::ShaderManager> shaderManager)
{
this->gl = gl;
constraintDrawer = std::make_unique<ConstraintDrawer>(
gl, shaderManager, ":/shader/line_constraint.vert",
":/shader/constraint.geom");
const int maxLabelCount = 100;
vertexArray = std::make_unique<Graphics::VertexArray>(gl, GL_POINTS, 2);
vertexArray->addStream(maxLabelCount, 2);
vertexArray->addStream(maxLabelCount, 2);
vertexArray->addStream(maxLabelCount, 2);
}
void ShadowConstraintDrawer::update(const std::vector<float> &sources,
const std::vector<float> &starts,
const std::vector<float> &ends)
{
vertexArray->updateStream(0, sources);
vertexArray->updateStream(1, starts);
vertexArray->updateStream(2, ends);
}
void ShadowConstraintDrawer::draw(float color, Eigen::Vector2f halfSize)
{
constraintDrawer->draw(vertexArray.get(), renderData, color, halfSize);
}
void ShadowConstraintDrawer::clear()
{
gl->glViewport(0, 0, width, height);
gl->glClearColor(0, 0, 0, 0);
gl->glClear(GL_COLOR_BUFFER_BIT);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "commonsettingspage.h"
#include "vcsbaseconstants.h"
#include "nicknamedialog.h"
#include "ui_commonsettingspage.h"
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <QDebug>
#include <QCoreApplication>
#include <QMessageBox>
namespace VcsBase {
namespace Internal {
// ------------------ VcsBaseSettingsWidget
CommonSettingsWidget::CommonSettingsWidget(QWidget *parent) :
QWidget(parent),
m_ui(new Ui::CommonSettingsPage)
{
m_ui->setupUi(this);
m_ui->submitMessageCheckScriptChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
m_ui->nickNameFieldsFileChooser->setExpectedKind(Utils::PathChooser::File);
m_ui->nickNameMailMapChooser->setExpectedKind(Utils::PathChooser::File);
m_ui->sshPromptChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
const QString patchToolTip = tr("Command used for reverting diff chunks");
m_ui->patchCommandLabel->setToolTip(patchToolTip);
m_ui->patchChooser->setToolTip(patchToolTip);
m_ui->patchChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
}
CommonSettingsWidget::~CommonSettingsWidget()
{
delete m_ui;
}
CommonVcsSettings CommonSettingsWidget::settings() const
{
CommonVcsSettings rc;
rc.nickNameMailMap = m_ui->nickNameMailMapChooser->path();
rc.nickNameFieldListFile = m_ui->nickNameFieldsFileChooser->path();
rc.submitMessageCheckScript = m_ui->submitMessageCheckScriptChooser->path();
rc.lineWrap= m_ui->lineWrapCheckBox->isChecked();
rc.lineWrapWidth = m_ui->lineWrapSpinBox->value();
rc.sshPasswordPrompt = m_ui->sshPromptChooser->path();
rc.patchCommand = m_ui->patchChooser->path();
return rc;
}
void CommonSettingsWidget::setSettings(const CommonVcsSettings &s)
{
m_ui->nickNameMailMapChooser->setPath(s.nickNameMailMap);
m_ui->nickNameFieldsFileChooser->setPath(s.nickNameFieldListFile);
m_ui->submitMessageCheckScriptChooser->setPath(s.submitMessageCheckScript);
m_ui->lineWrapCheckBox->setChecked(s.lineWrap);
m_ui->lineWrapSpinBox->setValue(s.lineWrapWidth);
m_ui->sshPromptChooser->setPath(s.sshPasswordPrompt);
m_ui->patchChooser->setPath(s.patchCommand);
}
QString CommonSettingsWidget::searchKeyWordMatchString() const
{
const QChar blank = QLatin1Char(' ');
QString rc = m_ui->lineWrapCheckBox->text()
+ blank + m_ui->submitMessageCheckScriptLabel->text()
+ blank + m_ui->nickNameMailMapLabel->text()
+ blank + m_ui->nickNameFieldsFileLabel->text()
+ blank + m_ui->sshPromptLabel->text()
;
rc.remove(QLatin1Char('&')); // Strip buddy markers.
return rc;
}
// --------------- VcsBaseSettingsPage
CommonOptionsPage::CommonOptionsPage(QObject *parent) :
VcsBaseOptionsPage(parent)
{
m_settings.fromSettings(Core::ICore::settings());
setId(QLatin1String(Constants::VCS_COMMON_SETTINGS_ID));
setDisplayName(QCoreApplication::translate("VcsBase", Constants::VCS_COMMON_SETTINGS_NAME));
}
QWidget *CommonOptionsPage::createPage(QWidget *parent)
{
m_widget = new CommonSettingsWidget(parent);
m_widget->setSettings(m_settings);
if (m_searchKeyWords.isEmpty())
m_searchKeyWords = m_widget->searchKeyWordMatchString();
return m_widget;
}
void CommonOptionsPage::apply()
{
if (m_widget) {
const CommonVcsSettings newSettings = m_widget->settings();
if (newSettings != m_settings) {
m_settings = newSettings;
m_settings.toSettings(Core::ICore::settings());
emit settingsChanged(m_settings);
}
}
}
bool CommonOptionsPage::matches(const QString &key) const
{
return m_searchKeyWords.contains(key, Qt::CaseInsensitive);
}
} // namespace Internal
} // namespace VcsBase
<commit_msg>VCS: Make 'Patch command' searchable<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "commonsettingspage.h"
#include "vcsbaseconstants.h"
#include "nicknamedialog.h"
#include "ui_commonsettingspage.h"
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <QDebug>
#include <QCoreApplication>
#include <QMessageBox>
namespace VcsBase {
namespace Internal {
// ------------------ VcsBaseSettingsWidget
CommonSettingsWidget::CommonSettingsWidget(QWidget *parent) :
QWidget(parent),
m_ui(new Ui::CommonSettingsPage)
{
m_ui->setupUi(this);
m_ui->submitMessageCheckScriptChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
m_ui->nickNameFieldsFileChooser->setExpectedKind(Utils::PathChooser::File);
m_ui->nickNameMailMapChooser->setExpectedKind(Utils::PathChooser::File);
m_ui->sshPromptChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
const QString patchToolTip = tr("Command used for reverting diff chunks");
m_ui->patchCommandLabel->setToolTip(patchToolTip);
m_ui->patchChooser->setToolTip(patchToolTip);
m_ui->patchChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
}
CommonSettingsWidget::~CommonSettingsWidget()
{
delete m_ui;
}
CommonVcsSettings CommonSettingsWidget::settings() const
{
CommonVcsSettings rc;
rc.nickNameMailMap = m_ui->nickNameMailMapChooser->path();
rc.nickNameFieldListFile = m_ui->nickNameFieldsFileChooser->path();
rc.submitMessageCheckScript = m_ui->submitMessageCheckScriptChooser->path();
rc.lineWrap= m_ui->lineWrapCheckBox->isChecked();
rc.lineWrapWidth = m_ui->lineWrapSpinBox->value();
rc.sshPasswordPrompt = m_ui->sshPromptChooser->path();
rc.patchCommand = m_ui->patchChooser->path();
return rc;
}
void CommonSettingsWidget::setSettings(const CommonVcsSettings &s)
{
m_ui->nickNameMailMapChooser->setPath(s.nickNameMailMap);
m_ui->nickNameFieldsFileChooser->setPath(s.nickNameFieldListFile);
m_ui->submitMessageCheckScriptChooser->setPath(s.submitMessageCheckScript);
m_ui->lineWrapCheckBox->setChecked(s.lineWrap);
m_ui->lineWrapSpinBox->setValue(s.lineWrapWidth);
m_ui->sshPromptChooser->setPath(s.sshPasswordPrompt);
m_ui->patchChooser->setPath(s.patchCommand);
}
QString CommonSettingsWidget::searchKeyWordMatchString() const
{
const QChar blank = QLatin1Char(' ');
QString rc = m_ui->lineWrapCheckBox->text()
+ blank + m_ui->submitMessageCheckScriptLabel->text()
+ blank + m_ui->nickNameMailMapLabel->text()
+ blank + m_ui->nickNameFieldsFileLabel->text()
+ blank + m_ui->sshPromptLabel->text()
+ blank + m_ui->patchCommandLabel->text()
;
rc.remove(QLatin1Char('&')); // Strip buddy markers.
return rc;
}
// --------------- VcsBaseSettingsPage
CommonOptionsPage::CommonOptionsPage(QObject *parent) :
VcsBaseOptionsPage(parent)
{
m_settings.fromSettings(Core::ICore::settings());
setId(QLatin1String(Constants::VCS_COMMON_SETTINGS_ID));
setDisplayName(QCoreApplication::translate("VcsBase", Constants::VCS_COMMON_SETTINGS_NAME));
}
QWidget *CommonOptionsPage::createPage(QWidget *parent)
{
m_widget = new CommonSettingsWidget(parent);
m_widget->setSettings(m_settings);
if (m_searchKeyWords.isEmpty())
m_searchKeyWords = m_widget->searchKeyWordMatchString();
return m_widget;
}
void CommonOptionsPage::apply()
{
if (m_widget) {
const CommonVcsSettings newSettings = m_widget->settings();
if (newSettings != m_settings) {
m_settings = newSettings;
m_settings.toSettings(Core::ICore::settings());
emit settingsChanged(m_settings);
}
}
}
bool CommonOptionsPage::matches(const QString &key) const
{
return m_searchKeyWords.contains(key, Qt::CaseInsensitive);
}
} // namespace Internal
} // namespace VcsBase
<|endoftext|> |
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Laurent Peuch <cortex@worlddomination.be>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "se_parser_blekko.h"
#include "miscutil.h"
#include <strings.h>
#include <iostream>
using sp::miscutil;
namespace seeks_plugins
{
se_parser_blekko::se_parser_blekko()
:se_parser(),_in_entry(false),_in_title(false),_in_uri(false),_in_description(false)
{
}
se_parser_blekko::~se_parser_blekko()
{
}
void se_parser_blekko::start_element(parser_context *pc,
const xmlChar *name,
const xmlChar **attributes)
{
const char *tag = (const char*)name;
if (strcasecmp(tag, "item") == 0)
{
// std::cout << "<item>" << std::endl;
_in_entry = true;
// create new snippet.
search_snippet *sp = new search_snippet(_count + 1);
_count++;
sp->_engine |= std::bitset<NSEs>(SE_BLEKKO);
pc->_current_snippet = sp;
}
else if (_in_entry && strcasecmp(tag, "title") == 0)
{
// std::cout << " <title>" << std::endl;
_in_title = true;
}
else if (_in_entry && strcasecmp(tag, "guid") == 0)
{
// std::cout << " <link>" << std::endl;
_in_uri = true;
}
else if (_in_entry && strcasecmp(tag, "description") == 0)
{
// std::cout << " <description>" << std::endl;
_in_description = true;
}
}
void se_parser_blekko::characters(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_blekko::cdata(parser_context *pc,
const xmlChar *chars,
int length)
{
//handle_characters(pc, chars, length);
}
void se_parser_blekko::handle_characters(parser_context *pc,
const xmlChar *chars,
int length)
{
if (_in_description)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
miscutil::replace_in_string(a_chars,"-"," ");
_description += a_chars;
// std::cout << " " << _description << std::endl;
}
else if (_in_title)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
miscutil::replace_in_string(a_chars,"-"," ");
_title += a_chars;
// std::cout << " " << _title << std::endl;
}
else if (_in_uri)
{
//std::string a_chars = std::string((char*)chars);
//miscutil::replace_in_string(a_chars,"\n"," ");
//miscutil::replace_in_string(a_chars,"\r"," ");
//miscutil::replace_in_string(a_chars,"-"," ");
//_uri += a_chars;
// //std::cout << " " << _uri << std::endl;
_uri.append((char*)chars, length);
// std::cout << " " << _uri << std::endl;
}
}
void se_parser_blekko::end_element(parser_context *pc,
const xmlChar *name)
{
const char *tag = (const char*) name;
if (_in_entry && strcasecmp(tag, "item") == 0)
{
// std::cout << "</item>" << std::endl;
_in_entry = false;
// assert previous snippet if any.
if (pc->_current_snippet)
{
if (pc->_current_snippet->_title.empty() // consider the parsing did fail on the snippet.
|| pc->_current_snippet->_url.empty()
|| pc->_current_snippet->_summary.empty())
{
// std::cout << "[snippet fail]" << " title: " << pc->_current_snippet->_title.empty() << " description: " << pc->_current_snippet->_summary.empty() << " url: " << pc->_current_snippet->_url.empty() << std::endl;
delete pc->_current_snippet;
pc->_current_snippet = NULL;
_count--;
}
else pc->_snippets->push_back(pc->_current_snippet);
}
}
else if (_in_entry && _in_title && strcasecmp(tag, "title") == 0)
{
// std::cout << " </title>" << std::endl;
_in_title = false;
pc->_current_snippet->set_title(_title);
_title = "";
}
else if (_in_entry && _in_description && strcasecmp(tag, "description") == 0)
{
// std::cout << " </description>" << std::endl;
// not a good solution, their is a quote/unquote problem nearby
miscutil::replace_in_string(_description, "'", "'");
_in_description = false;
pc->_current_snippet->set_summary(_description);
_description = "";
}
else if (_in_entry && _in_uri && strcasecmp(tag, "guid") ==0)
{
// std::cout << " </link>" << std::endl;
_in_uri = false;
pc->_current_snippet->set_url(_uri);
_uri = "";
}
}
} /* end of namespace. */
<commit_msg>fix the quote/unquote bug for blekko<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Laurent Peuch <cortex@worlddomination.be>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "se_parser_blekko.h"
#include "miscutil.h"
#include "encode.h"
#include <strings.h>
#include <iostream>
using sp::miscutil;
using sp::encode;
namespace seeks_plugins
{
se_parser_blekko::se_parser_blekko()
:se_parser(),_in_entry(false),_in_title(false),_in_uri(false),_in_description(false)
{
}
se_parser_blekko::~se_parser_blekko()
{
}
void se_parser_blekko::start_element(parser_context *pc,
const xmlChar *name,
const xmlChar **attributes)
{
const char *tag = (const char*)name;
if (strcasecmp(tag, "item") == 0)
{
// std::cout << "<item>" << std::endl;
_in_entry = true;
// create new snippet.
search_snippet *sp = new search_snippet(_count + 1);
_count++;
sp->_engine |= std::bitset<NSEs>(SE_BLEKKO);
pc->_current_snippet = sp;
}
else if (_in_entry && strcasecmp(tag, "title") == 0)
{
// std::cout << " <title>" << std::endl;
_in_title = true;
}
else if (_in_entry && strcasecmp(tag, "guid") == 0)
{
// std::cout << " <link>" << std::endl;
_in_uri = true;
}
else if (_in_entry && strcasecmp(tag, "description") == 0)
{
// std::cout << " <description>" << std::endl;
_in_description = true;
}
}
void se_parser_blekko::characters(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_blekko::cdata(parser_context *pc,
const xmlChar *chars,
int length)
{
//handle_characters(pc, chars, length);
}
void se_parser_blekko::handle_characters(parser_context *pc,
const xmlChar *chars,
int length)
{
if (_in_description)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
miscutil::replace_in_string(a_chars,"-"," ");
_description += a_chars;
// std::cout << " " << _description << std::endl;
}
else if (_in_title)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
miscutil::replace_in_string(a_chars,"-"," ");
_title += a_chars;
// std::cout << " " << _title << std::endl;
}
else if (_in_uri)
{
//std::string a_chars = std::string((char*)chars);
//miscutil::replace_in_string(a_chars,"\n"," ");
//miscutil::replace_in_string(a_chars,"\r"," ");
//miscutil::replace_in_string(a_chars,"-"," ");
//_uri += a_chars;
// //std::cout << " " << _uri << std::endl;
_uri.append((char*)chars, length);
// std::cout << " " << _uri << std::endl;
}
}
void se_parser_blekko::end_element(parser_context *pc,
const xmlChar *name)
{
const char *tag = (const char*) name;
if (_in_entry && strcasecmp(tag, "item") == 0)
{
// std::cout << "</item>" << std::endl;
_in_entry = false;
// assert previous snippet if any.
if (pc->_current_snippet)
{
if (pc->_current_snippet->_title.empty() // consider the parsing did fail on the snippet.
|| pc->_current_snippet->_url.empty()
|| pc->_current_snippet->_summary.empty())
{
// std::cout << "[snippet fail]" << " title: " << pc->_current_snippet->_title.empty() << " description: " << pc->_current_snippet->_summary.empty() << " url: " << pc->_current_snippet->_url.empty() << std::endl;
delete pc->_current_snippet;
pc->_current_snippet = NULL;
_count--;
}
else pc->_snippets->push_back(pc->_current_snippet);
}
}
else if (_in_entry && _in_title && strcasecmp(tag, "title") == 0)
{
// std::cout << " </title>" << std::endl;
_in_title = false;
pc->_current_snippet->set_title(_title);
_title = "";
}
else if (_in_entry && _in_description && strcasecmp(tag, "description") == 0)
{
// std::cout << " </description>" << std::endl;
char * description_str = encode::html_decode(_description);
_in_description = false;
pc->_current_snippet->set_summary(description_str);
free(description_str);
_description = "";
}
else if (_in_entry && _in_uri && strcasecmp(tag, "guid") ==0)
{
// std::cout << " </link>" << std::endl;
_in_uri = false;
pc->_current_snippet->set_url(_uri);
_uri = "";
}
}
} /* end of namespace. */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 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 "src/profiling/memory/shared_ring_buffer.h"
#include <atomic>
#include <type_traits>
#include <errno.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/base/build_config.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/temp_file.h"
#include "src/profiling/memory/scoped_spinlock.h"
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#include <linux/memfd.h>
#include <sys/syscall.h>
#endif
namespace perfetto {
namespace profiling {
namespace {
constexpr auto kMetaPageSize = base::kPageSize;
constexpr auto kAlignment = 8; // 64 bits to use aligned memcpy().
constexpr auto kHeaderSize = kAlignment;
constexpr auto kGuardSize = base::kPageSize * 1024 * 16; // 64 MB.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
constexpr auto kFDSeals = F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL;
#endif
} // namespace
SharedRingBuffer::SharedRingBuffer(CreateFlag, size_t size) {
size_t size_with_meta = size + kMetaPageSize;
base::ScopedFile fd;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
bool is_memfd = false;
fd.reset(static_cast<int>(syscall(__NR_memfd_create, "heapprofd_ringbuf",
MFD_CLOEXEC | MFD_ALLOW_SEALING)));
is_memfd = !!fd;
if (!fd) {
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
// In-tree builds should only allow mem_fd, so we can inspect the seals
// to verify the fd is appropriately sealed.
PERFETTO_ELOG("memfd_create() failed");
return;
#else
PERFETTO_DPLOG("memfd_create() failed");
#endif
}
#endif
if (!fd)
fd = base::TempFile::CreateUnlinked().ReleaseFD();
PERFETTO_CHECK(fd);
int res = ftruncate(fd.get(), static_cast<off_t>(size_with_meta));
PERFETTO_CHECK(res == 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
if (is_memfd) {
res = fcntl(*fd, F_ADD_SEALS, kFDSeals);
if (res != 0) {
PERFETTO_PLOG("Failed to seal FD.");
return;
}
}
#endif
Initialize(std::move(fd));
if (!is_valid())
return;
new (meta_) MetadataPage();
}
SharedRingBuffer::~SharedRingBuffer() {
static_assert(std::is_trivially_constructible<MetadataPage>::value,
"MetadataPage must be trivially constructible");
static_assert(std::is_trivially_destructible<MetadataPage>::value,
"MetadataPage must be trivially destructible");
if (is_valid()) {
size_t outer_size = kMetaPageSize + size_ * 2 + kGuardSize;
munmap(meta_, outer_size);
}
}
void SharedRingBuffer::Initialize(base::ScopedFile mem_fd) {
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
int seals = fcntl(*mem_fd, F_GET_SEALS);
if (seals == -1) {
PERFETTO_PLOG("Failed to get seals of FD.");
return;
}
if ((seals & kFDSeals) != kFDSeals) {
PERFETTO_ELOG("FD not properly sealed. Expected %x, got %x", kFDSeals,
seals);
return;
}
#endif
struct stat stat_buf = {};
int res = fstat(*mem_fd, &stat_buf);
if (res != 0 || stat_buf.st_size == 0) {
PERFETTO_PLOG("Could not attach to fd.");
return;
}
auto size_with_meta = static_cast<size_t>(stat_buf.st_size);
auto size = size_with_meta - kMetaPageSize;
// |size_with_meta| must be a power of two number of pages + 1 page (for
// metadata).
if (size_with_meta < 2 * base::kPageSize || size % base::kPageSize ||
(size & (size - 1))) {
PERFETTO_ELOG("SharedRingBuffer size is invalid (%zu)", size_with_meta);
return;
}
// First of all reserve the whole virtual region to fit the buffer twice
// + metadata page + red zone at the end.
size_t outer_size = kMetaPageSize + size * 2 + kGuardSize;
uint8_t* region = reinterpret_cast<uint8_t*>(
mmap(nullptr, outer_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
if (region == MAP_FAILED) {
PERFETTO_PLOG("mmap(PROT_NONE) failed");
return;
}
// Map first the whole buffer (including the initial metadata page) @ off=0.
void* reg1 = mmap(region, size_with_meta, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_FIXED, *mem_fd, 0);
// Then map again the buffer, skipping the metadata page. The final result is:
// [ METADATA ] [ RING BUFFER SHMEM ] [ RING BUFFER SHMEM ]
void* reg2 = mmap(region + size_with_meta, size, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_FIXED, *mem_fd,
/*offset=*/kMetaPageSize);
if (reg1 != region || reg2 != region + size_with_meta) {
PERFETTO_PLOG("mmap(MAP_SHARED) failed");
munmap(region, outer_size);
return;
}
size_ = size;
meta_ = reinterpret_cast<MetadataPage*>(region);
mem_ = region + kMetaPageSize;
mem_fd_ = std::move(mem_fd);
}
SharedRingBuffer::Buffer SharedRingBuffer::BeginWrite(
const ScopedSpinlock& spinlock,
size_t size) {
PERFETTO_DCHECK(spinlock.locked());
Buffer result;
base::Optional<PointerPositions> opt_pos = GetPointerPositions();
if (!opt_pos) {
meta_->stats.num_writes_corrupt++;
errno = EBADF;
return result;
}
auto pos = opt_pos.value();
const uint64_t size_with_header =
base::AlignUp<kAlignment>(size + kHeaderSize);
// size_with_header < size is for catching overflow of size_with_header.
if (PERFETTO_UNLIKELY(size_with_header < size)) {
errno = EINVAL;
return result;
}
if (size_with_header > write_avail(pos)) {
meta_->stats.num_writes_overflow++;
errno = EAGAIN;
return result;
}
uint8_t* wr_ptr = at(pos.write_pos);
result.size = size;
result.data = wr_ptr + kHeaderSize;
meta_->stats.bytes_written += size;
meta_->stats.num_writes_succeeded++;
// We can make this a relaxed store, as this gets picked up by the acquire
// load in GetPointerPositions (and the release store below).
reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store(
0, std::memory_order_relaxed);
// This needs to happen after the store above, so the reader never observes an
// incorrect byte count. This is matched by the acquire load in
// GetPointerPositions.
meta_->write_pos.fetch_add(size_with_header, std::memory_order_release);
return result;
}
void SharedRingBuffer::EndWrite(Buffer buf) {
if (!buf)
return;
uint8_t* wr_ptr = buf.data - kHeaderSize;
PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(wr_ptr) % kAlignment == 0);
// This needs to release to make sure the reader sees the payload written
// between the BeginWrite and EndWrite calls.
//
// This is matched by the acquire load in BeginRead where it reads the
// record's size.
reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store(
static_cast<uint32_t>(buf.size), std::memory_order_release);
}
SharedRingBuffer::Buffer SharedRingBuffer::BeginRead() {
base::Optional<PointerPositions> opt_pos = GetPointerPositions();
if (!opt_pos) {
meta_->stats.num_reads_corrupt++;
errno = EBADF;
return Buffer();
}
auto pos = opt_pos.value();
size_t avail_read = read_avail(pos);
if (avail_read < kHeaderSize) {
meta_->stats.num_reads_nodata++;
errno = EAGAIN;
return Buffer(); // No data
}
uint8_t* rd_ptr = at(pos.read_pos);
PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0);
const size_t size = reinterpret_cast<std::atomic<uint32_t>*>(rd_ptr)->load(
std::memory_order_acquire);
if (size == 0) {
meta_->stats.num_reads_nodata++;
errno = EAGAIN;
return Buffer();
}
const size_t size_with_header = base::AlignUp<kAlignment>(size + kHeaderSize);
if (size_with_header > avail_read) {
PERFETTO_ELOG(
"Corrupted header detected, size=%zu"
", read_avail=%zu, rd=%" PRIu64 ", wr=%" PRIu64,
size, avail_read, pos.read_pos, pos.write_pos);
meta_->stats.num_reads_corrupt++;
errno = EBADF;
return Buffer();
}
rd_ptr += kHeaderSize;
PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0);
return Buffer(rd_ptr, size);
}
void SharedRingBuffer::EndRead(Buffer buf) {
if (!buf)
return;
size_t size_with_header = base::AlignUp<kAlignment>(buf.size + kHeaderSize);
meta_->read_pos.fetch_add(size_with_header, std::memory_order_relaxed);
meta_->stats.num_reads_succeeded++;
}
bool SharedRingBuffer::IsCorrupt(const PointerPositions& pos) {
if (pos.write_pos < pos.read_pos || pos.write_pos - pos.read_pos > size_ ||
pos.write_pos % kAlignment || pos.read_pos % kAlignment) {
PERFETTO_ELOG("Ring buffer corrupted, rd=%" PRIu64 ", wr=%" PRIu64
", size=%zu",
pos.read_pos, pos.write_pos, size_);
return true;
}
return false;
}
SharedRingBuffer::SharedRingBuffer(SharedRingBuffer&& other) noexcept {
*this = std::move(other);
}
SharedRingBuffer& SharedRingBuffer::operator=(SharedRingBuffer&& other) {
mem_fd_ = std::move(other.mem_fd_);
std::tie(meta_, mem_, size_) = std::tie(other.meta_, other.mem_, other.size_);
std::tie(other.meta_, other.mem_, other.size_) =
std::make_tuple(nullptr, nullptr, 0);
return *this;
}
// static
base::Optional<SharedRingBuffer> SharedRingBuffer::Create(size_t size) {
auto buf = SharedRingBuffer(CreateFlag(), size);
if (!buf.is_valid())
return base::nullopt;
return base::make_optional(std::move(buf));
}
// static
base::Optional<SharedRingBuffer> SharedRingBuffer::Attach(
base::ScopedFile mem_fd) {
auto buf = SharedRingBuffer(AttachFlag(), std::move(mem_fd));
if (!buf.is_valid())
return base::nullopt;
return base::make_optional(std::move(buf));
}
} // namespace profiling
} // namespace perfetto
<commit_msg>Work around double-closing memfd. am: 005673df10 am: cd8409d811<commit_after>/*
* Copyright (C) 2019 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 "src/profiling/memory/shared_ring_buffer.h"
#include <atomic>
#include <type_traits>
#include <errno.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/base/build_config.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/temp_file.h"
#include "src/profiling/memory/scoped_spinlock.h"
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#include <linux/memfd.h>
#include <sys/syscall.h>
#endif
namespace perfetto {
namespace profiling {
namespace {
constexpr auto kMetaPageSize = base::kPageSize;
constexpr auto kAlignment = 8; // 64 bits to use aligned memcpy().
constexpr auto kHeaderSize = kAlignment;
constexpr auto kGuardSize = base::kPageSize * 1024 * 16; // 64 MB.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
constexpr auto kFDSeals = F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL;
#endif
} // namespace
SharedRingBuffer::SharedRingBuffer(CreateFlag, size_t size) {
size_t size_with_meta = size + kMetaPageSize;
base::ScopedFile fd;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
bool is_memfd = false;
fd.reset(static_cast<int>(syscall(__NR_memfd_create, "heapprofd_ringbuf",
MFD_CLOEXEC | MFD_ALLOW_SEALING)));
is_memfd = !!fd;
if (!fd) {
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
// In-tree builds should only allow mem_fd, so we can inspect the seals
// to verify the fd is appropriately sealed.
PERFETTO_ELOG("memfd_create() failed");
return;
#else
PERFETTO_DPLOG("memfd_create() failed");
#endif
}
#endif
if (!fd)
fd = base::TempFile::CreateUnlinked().ReleaseFD();
PERFETTO_CHECK(fd);
int res = ftruncate(fd.get(), static_cast<off_t>(size_with_meta));
PERFETTO_CHECK(res == 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
if (is_memfd) {
res = fcntl(*fd, F_ADD_SEALS, kFDSeals);
if (res != 0) {
PERFETTO_PLOG("Failed to seal FD.");
return;
}
}
#endif
Initialize(std::move(fd));
if (!is_valid())
return;
new (meta_) MetadataPage();
}
SharedRingBuffer::~SharedRingBuffer() {
static_assert(std::is_trivially_constructible<MetadataPage>::value,
"MetadataPage must be trivially constructible");
static_assert(std::is_trivially_destructible<MetadataPage>::value,
"MetadataPage must be trivially destructible");
if (is_valid()) {
size_t outer_size = kMetaPageSize + size_ * 2 + kGuardSize;
munmap(meta_, outer_size);
}
// This is work-around for code like the following:
// https://android.googlesource.com/platform/libcore/+/4ecb71f94378716f88703b9f7548b5d24839262f/ojluni/src/main/native/UNIXProcess_md.c#427
// They fork, close all fds by iterating over /proc/self/fd using opendir.
// Unfortunately closedir calls free, which detects the fork, and then tries
// to destruct the Client that holds this SharedRingBuffer.
//
// ScopedResource crashes on failure to close, so we explicitly ignore
// failures here.
int fd = mem_fd_.release();
if (fd != -1)
close(fd);
}
void SharedRingBuffer::Initialize(base::ScopedFile mem_fd) {
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
int seals = fcntl(*mem_fd, F_GET_SEALS);
if (seals == -1) {
PERFETTO_PLOG("Failed to get seals of FD.");
return;
}
if ((seals & kFDSeals) != kFDSeals) {
PERFETTO_ELOG("FD not properly sealed. Expected %x, got %x", kFDSeals,
seals);
return;
}
#endif
struct stat stat_buf = {};
int res = fstat(*mem_fd, &stat_buf);
if (res != 0 || stat_buf.st_size == 0) {
PERFETTO_PLOG("Could not attach to fd.");
return;
}
auto size_with_meta = static_cast<size_t>(stat_buf.st_size);
auto size = size_with_meta - kMetaPageSize;
// |size_with_meta| must be a power of two number of pages + 1 page (for
// metadata).
if (size_with_meta < 2 * base::kPageSize || size % base::kPageSize ||
(size & (size - 1))) {
PERFETTO_ELOG("SharedRingBuffer size is invalid (%zu)", size_with_meta);
return;
}
// First of all reserve the whole virtual region to fit the buffer twice
// + metadata page + red zone at the end.
size_t outer_size = kMetaPageSize + size * 2 + kGuardSize;
uint8_t* region = reinterpret_cast<uint8_t*>(
mmap(nullptr, outer_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
if (region == MAP_FAILED) {
PERFETTO_PLOG("mmap(PROT_NONE) failed");
return;
}
// Map first the whole buffer (including the initial metadata page) @ off=0.
void* reg1 = mmap(region, size_with_meta, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_FIXED, *mem_fd, 0);
// Then map again the buffer, skipping the metadata page. The final result is:
// [ METADATA ] [ RING BUFFER SHMEM ] [ RING BUFFER SHMEM ]
void* reg2 = mmap(region + size_with_meta, size, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_FIXED, *mem_fd,
/*offset=*/kMetaPageSize);
if (reg1 != region || reg2 != region + size_with_meta) {
PERFETTO_PLOG("mmap(MAP_SHARED) failed");
munmap(region, outer_size);
return;
}
size_ = size;
meta_ = reinterpret_cast<MetadataPage*>(region);
mem_ = region + kMetaPageSize;
mem_fd_ = std::move(mem_fd);
}
SharedRingBuffer::Buffer SharedRingBuffer::BeginWrite(
const ScopedSpinlock& spinlock,
size_t size) {
PERFETTO_DCHECK(spinlock.locked());
Buffer result;
base::Optional<PointerPositions> opt_pos = GetPointerPositions();
if (!opt_pos) {
meta_->stats.num_writes_corrupt++;
errno = EBADF;
return result;
}
auto pos = opt_pos.value();
const uint64_t size_with_header =
base::AlignUp<kAlignment>(size + kHeaderSize);
// size_with_header < size is for catching overflow of size_with_header.
if (PERFETTO_UNLIKELY(size_with_header < size)) {
errno = EINVAL;
return result;
}
if (size_with_header > write_avail(pos)) {
meta_->stats.num_writes_overflow++;
errno = EAGAIN;
return result;
}
uint8_t* wr_ptr = at(pos.write_pos);
result.size = size;
result.data = wr_ptr + kHeaderSize;
meta_->stats.bytes_written += size;
meta_->stats.num_writes_succeeded++;
// We can make this a relaxed store, as this gets picked up by the acquire
// load in GetPointerPositions (and the release store below).
reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store(
0, std::memory_order_relaxed);
// This needs to happen after the store above, so the reader never observes an
// incorrect byte count. This is matched by the acquire load in
// GetPointerPositions.
meta_->write_pos.fetch_add(size_with_header, std::memory_order_release);
return result;
}
void SharedRingBuffer::EndWrite(Buffer buf) {
if (!buf)
return;
uint8_t* wr_ptr = buf.data - kHeaderSize;
PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(wr_ptr) % kAlignment == 0);
// This needs to release to make sure the reader sees the payload written
// between the BeginWrite and EndWrite calls.
//
// This is matched by the acquire load in BeginRead where it reads the
// record's size.
reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store(
static_cast<uint32_t>(buf.size), std::memory_order_release);
}
SharedRingBuffer::Buffer SharedRingBuffer::BeginRead() {
base::Optional<PointerPositions> opt_pos = GetPointerPositions();
if (!opt_pos) {
meta_->stats.num_reads_corrupt++;
errno = EBADF;
return Buffer();
}
auto pos = opt_pos.value();
size_t avail_read = read_avail(pos);
if (avail_read < kHeaderSize) {
meta_->stats.num_reads_nodata++;
errno = EAGAIN;
return Buffer(); // No data
}
uint8_t* rd_ptr = at(pos.read_pos);
PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0);
const size_t size = reinterpret_cast<std::atomic<uint32_t>*>(rd_ptr)->load(
std::memory_order_acquire);
if (size == 0) {
meta_->stats.num_reads_nodata++;
errno = EAGAIN;
return Buffer();
}
const size_t size_with_header = base::AlignUp<kAlignment>(size + kHeaderSize);
if (size_with_header > avail_read) {
PERFETTO_ELOG(
"Corrupted header detected, size=%zu"
", read_avail=%zu, rd=%" PRIu64 ", wr=%" PRIu64,
size, avail_read, pos.read_pos, pos.write_pos);
meta_->stats.num_reads_corrupt++;
errno = EBADF;
return Buffer();
}
rd_ptr += kHeaderSize;
PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0);
return Buffer(rd_ptr, size);
}
void SharedRingBuffer::EndRead(Buffer buf) {
if (!buf)
return;
size_t size_with_header = base::AlignUp<kAlignment>(buf.size + kHeaderSize);
meta_->read_pos.fetch_add(size_with_header, std::memory_order_relaxed);
meta_->stats.num_reads_succeeded++;
}
bool SharedRingBuffer::IsCorrupt(const PointerPositions& pos) {
if (pos.write_pos < pos.read_pos || pos.write_pos - pos.read_pos > size_ ||
pos.write_pos % kAlignment || pos.read_pos % kAlignment) {
PERFETTO_ELOG("Ring buffer corrupted, rd=%" PRIu64 ", wr=%" PRIu64
", size=%zu",
pos.read_pos, pos.write_pos, size_);
return true;
}
return false;
}
SharedRingBuffer::SharedRingBuffer(SharedRingBuffer&& other) noexcept {
*this = std::move(other);
}
SharedRingBuffer& SharedRingBuffer::operator=(SharedRingBuffer&& other) {
mem_fd_ = std::move(other.mem_fd_);
std::tie(meta_, mem_, size_) = std::tie(other.meta_, other.mem_, other.size_);
std::tie(other.meta_, other.mem_, other.size_) =
std::make_tuple(nullptr, nullptr, 0);
return *this;
}
// static
base::Optional<SharedRingBuffer> SharedRingBuffer::Create(size_t size) {
auto buf = SharedRingBuffer(CreateFlag(), size);
if (!buf.is_valid())
return base::nullopt;
return base::make_optional(std::move(buf));
}
// static
base::Optional<SharedRingBuffer> SharedRingBuffer::Attach(
base::ScopedFile mem_fd) {
auto buf = SharedRingBuffer(AttachFlag(), std::move(mem_fd));
if (!buf.is_valid())
return base::nullopt;
return base::make_optional(std::move(buf));
}
} // namespace profiling
} // namespace perfetto
<|endoftext|> |
<commit_before>
#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "base58.h"
#include "protocol.h"
#include "spork.h"
#include "main.h"
#include "masternode-budget.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
class CSporkMessage;
class CSporkManager;
CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if(fLiteMode) return; //disable all masternode related functionality
if (strCommand == "spork")
{
//LogPrintf("ProcessSpork::spork\n");
CDataStream vMsg(vRecv);
CSporkMessage spork;
vRecv >> spork;
if(chainActive.Tip() == NULL) return;
uint256 hash = spork.GetHash();
if(mapSporksActive.count(spork.nSporkID)) {
if(mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned){
if(fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
return;
} else {
if(fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
}
}
LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);
if(!sporkManager.CheckSignature(spork)){
LogPrintf("spork - invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSporks[hash] = spork;
mapSporksActive[spork.nSporkID] = spork;
sporkManager.Relay(spork);
//does a task if needed
ExecuteSpork(spork.nSporkID, spork.nValue);
}
if (strCommand == "getsporks")
{
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
while(it != mapSporksActive.end()) {
pfrom->PushMessage("spork", it->second);
it++;
}
}
}
// grab the spork, otherwise say it's off
bool IsSporkActive(int nSporkID)
{
int64_t r = -1;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(nSporkID == SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT) r = SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
if(r == -1) r = 4070908800; //return 2099-1-1 by default
return r < GetTime();
}
// grab the value of the spork on the network, or the default
int64_t GetSporkValue(int nSporkID)
{
int64_t r = -1;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(nSporkID == SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT) r = SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
return r;
}
void ExecuteSpork(int nSporkID, int nValue)
{
if(nSporkID == SPORK_11_RESET_BUDGET && nValue == 1){
budget.Clear();
}
//correct fork via spork technology
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
LogPrintf("Spork::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue);
ReprocessBlocks(nValue);
}
}
void ReprocessBlocks(int nBlocks)
{
std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin();
while(it != mapRejectedBlocks.end()){
//use a window twice as large as is usual for the nBlocks we want to reset
if((*it).second > GetTime() - (nBlocks*60*5)) {
BlockMap::iterator mi = mapBlockIndex.find((*it).first);
if (mi != mapBlockIndex.end() && (*mi).second) {
LOCK(cs_main);
CBlockIndex* pindex = (*mi).second;
LogPrintf("ReprocessBlocks - %s\n", (*it).first.ToString());
CValidationState state;
ReconsiderBlock(state, pindex);
}
}
++it;
}
CValidationState state;
{
LOCK(cs_main);
DisconnectBlocksAndReprocess(nBlocks);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
}
bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
//note: need to investigate why this is failing
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CPubKey pubkey(ParseHex(Params().SporkKey()));
std::string errorMessage = "";
if(!legacySigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)){
return false;
}
return true;
}
bool CSporkManager::Sign(CSporkMessage& spork)
{
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CKey key2;
CPubKey pubkey2;
std::string errorMessage = "";
if(!legacySigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
{
LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
return false;
}
if(!legacySigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
LogPrintf("CMasternodePayments::Sign - Sign message failed");
return false;
}
if(!legacySigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePayments::Sign - Verify message failed");
return false;
}
return true;
}
bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{
CSporkMessage msg;
msg.nSporkID = nSporkID;
msg.nValue = nValue;
msg.nTimeSigned = GetTime();
if(Sign(msg)){
Relay(msg);
mapSporks[msg.GetHash()] = msg;
mapSporksActive[nSporkID] = msg;
return true;
}
return false;
}
void CSporkManager::Relay(CSporkMessage& msg)
{
CInv inv(MSG_SPORK, msg.GetHash());
RelayInv(inv);
}
bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
CSporkMessage msg;
// Test signing successful, proceed
strMasterPrivKey = strPrivKey;
Sign(msg);
if(CheckSignature(msg)){
LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
return true;
} else {
return false;
}
}
int CSporkManager::GetSporkIDByName(std::string strName)
{
if(strName == "SPORK_2_INSTANTX") return SPORK_2_INSTANTX;
if(strName == "SPORK_3_INSTANTX_BLOCK_FILTERING") return SPORK_3_INSTANTX_BLOCK_FILTERING;
if(strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
if(strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
if(strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
if(strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
if(strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
if(strName == "SPORK_11_RESET_BUDGET") return SPORK_11_RESET_BUDGET;
if(strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
if(strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;
if(strName == "SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT") return SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT;
return -1;
}
std::string CSporkManager::GetSporkNameByID(int id)
{
if(id == SPORK_2_INSTANTX) return "SPORK_2_INSTANTX";
if(id == SPORK_3_INSTANTX_BLOCK_FILTERING) return "SPORK_3_INSTANTX_BLOCK_FILTERING";
if(id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
if(id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
if(id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
if(id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
if(id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
if(id == SPORK_11_RESET_BUDGET) return "SPORK_11_RESET_BUDGET";
if(id == SPORK_12_RECONSIDER_BLOCKS) return "SPORK_12_RECONSIDER_BLOCKS";
if(id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";
if(id == SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT) return "SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT";
return "Unknown";
}
<commit_msg>update default spork value<commit_after>
#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "base58.h"
#include "protocol.h"
#include "spork.h"
#include "main.h"
#include "masternode-budget.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
class CSporkMessage;
class CSporkManager;
CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if(fLiteMode) return; //disable all masternode related functionality
if (strCommand == "spork")
{
//LogPrintf("ProcessSpork::spork\n");
CDataStream vMsg(vRecv);
CSporkMessage spork;
vRecv >> spork;
if(chainActive.Tip() == NULL) return;
uint256 hash = spork.GetHash();
if(mapSporksActive.count(spork.nSporkID)) {
if(mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned){
if(fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
return;
} else {
if(fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
}
}
LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);
if(!sporkManager.CheckSignature(spork)){
LogPrintf("spork - invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSporks[hash] = spork;
mapSporksActive[spork.nSporkID] = spork;
sporkManager.Relay(spork);
//does a task if needed
ExecuteSpork(spork.nSporkID, spork.nValue);
}
if (strCommand == "getsporks")
{
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
while(it != mapSporksActive.end()) {
pfrom->PushMessage("spork", it->second);
it++;
}
}
}
// grab the spork, otherwise say it's off
bool IsSporkActive(int nSporkID)
{
int64_t r = -1;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(nSporkID == SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT) r = SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
if(r == -1) r = 40709088000; //return 2099-1-1 by default
return r < GetTime();
}
// grab the value of the spork on the network, or the default
int64_t GetSporkValue(int nSporkID)
{
int64_t r = -1;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(nSporkID == SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT) r = SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
return r;
}
void ExecuteSpork(int nSporkID, int nValue)
{
if(nSporkID == SPORK_11_RESET_BUDGET && nValue == 1){
budget.Clear();
}
//correct fork via spork technology
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
LogPrintf("Spork::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue);
ReprocessBlocks(nValue);
}
}
void ReprocessBlocks(int nBlocks)
{
std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin();
while(it != mapRejectedBlocks.end()){
//use a window twice as large as is usual for the nBlocks we want to reset
if((*it).second > GetTime() - (nBlocks*60*5)) {
BlockMap::iterator mi = mapBlockIndex.find((*it).first);
if (mi != mapBlockIndex.end() && (*mi).second) {
LOCK(cs_main);
CBlockIndex* pindex = (*mi).second;
LogPrintf("ReprocessBlocks - %s\n", (*it).first.ToString());
CValidationState state;
ReconsiderBlock(state, pindex);
}
}
++it;
}
CValidationState state;
{
LOCK(cs_main);
DisconnectBlocksAndReprocess(nBlocks);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
}
bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
//note: need to investigate why this is failing
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CPubKey pubkey(ParseHex(Params().SporkKey()));
std::string errorMessage = "";
if(!legacySigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)){
return false;
}
return true;
}
bool CSporkManager::Sign(CSporkMessage& spork)
{
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CKey key2;
CPubKey pubkey2;
std::string errorMessage = "";
if(!legacySigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
{
LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
return false;
}
if(!legacySigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
LogPrintf("CMasternodePayments::Sign - Sign message failed");
return false;
}
if(!legacySigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePayments::Sign - Verify message failed");
return false;
}
return true;
}
bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{
CSporkMessage msg;
msg.nSporkID = nSporkID;
msg.nValue = nValue;
msg.nTimeSigned = GetTime();
if(Sign(msg)){
Relay(msg);
mapSporks[msg.GetHash()] = msg;
mapSporksActive[nSporkID] = msg;
return true;
}
return false;
}
void CSporkManager::Relay(CSporkMessage& msg)
{
CInv inv(MSG_SPORK, msg.GetHash());
RelayInv(inv);
}
bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
CSporkMessage msg;
// Test signing successful, proceed
strMasterPrivKey = strPrivKey;
Sign(msg);
if(CheckSignature(msg)){
LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
return true;
} else {
return false;
}
}
int CSporkManager::GetSporkIDByName(std::string strName)
{
if(strName == "SPORK_2_INSTANTX") return SPORK_2_INSTANTX;
if(strName == "SPORK_3_INSTANTX_BLOCK_FILTERING") return SPORK_3_INSTANTX_BLOCK_FILTERING;
if(strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
if(strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
if(strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
if(strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
if(strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
if(strName == "SPORK_11_RESET_BUDGET") return SPORK_11_RESET_BUDGET;
if(strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
if(strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;
if(strName == "SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT") return SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT;
return -1;
}
std::string CSporkManager::GetSporkNameByID(int id)
{
if(id == SPORK_2_INSTANTX) return "SPORK_2_INSTANTX";
if(id == SPORK_3_INSTANTX_BLOCK_FILTERING) return "SPORK_3_INSTANTX_BLOCK_FILTERING";
if(id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
if(id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
if(id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
if(id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
if(id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
if(id == SPORK_11_RESET_BUDGET) return "SPORK_11_RESET_BUDGET";
if(id == SPORK_12_RECONSIDER_BLOCKS) return "SPORK_12_RECONSIDER_BLOCKS";
if(id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";
if(id == SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT) return "SPORK_14_SYSTEMNODE_PAYMENT_ENFORCEMENT";
return "Unknown";
}
<|endoftext|> |
<commit_before>#include "gason2.h"
#include "gason2dump.h"
#include <stdio.h>
#include <stdlib.h>
struct Stat {
size_t objectCount;
size_t arrayCount;
size_t numberCount;
size_t stringCount;
size_t trueCount;
size_t falseCount;
size_t nullCount;
size_t memberCount; // Number of members in all objects
size_t elementCount; // Number of elements in all arrays
size_t stringLength; // Number of code units in all strings
};
static void GenStat(Stat &stat, const gason2::node &v) {
switch (v.type()) {
case gason2::type::array:
for (auto i : v.elements())
GenStat(stat, i);
stat.elementCount += v.size();
stat.arrayCount++;
break;
case gason2::type::object:
for (auto i : v.members()) {
stat.stringLength += strlen(i.name().to_string());
GenStat(stat, i.value());
}
stat.memberCount += v.size() / 2;
stat.stringCount += v.size() / 2;
stat.objectCount++;
break;
case gason2::type::string:
stat.stringCount++;
stat.stringLength += strlen(v.to_string());
break;
case gason2::type::number:
stat.numberCount++;
break;
case gason2::type::boolean:
if (v.to_bool())
stat.trueCount++;
else
stat.falseCount++;
break;
case gason2::type::null:
stat.nullCount++;
break;
default:
break;
}
}
int main(int argc, char **argv) {
for (int i = 1; i < argc; ++i) {
FILE *fp = fopen(argv[i], "r");
if (!fp) {
perror(argv[i]);
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END);
size_t size = ftell(fp);
fseek(fp, 0, SEEK_SET);
gason2::vector<char> source;
source.resize(size + 1);
source.back() = '\0';
fread(source.data(), 1, size, fp);
fclose(fp);
gason2::document doc;
if (!doc.parse(source.data())) {
gason2::dump::print_error(argv[i], source.data(), doc);
}
Stat stat = {};
GenStat(stat, doc);
printf("%s: %zd %zd %zd %zd %zd %zd %zd %zd %zd %zd\n",
argv[i],
stat.objectCount,
stat.arrayCount,
stat.numberCount,
stat.stringCount,
stat.trueCount,
stat.falseCount,
stat.nullCount,
stat.memberCount,
stat.elementCount,
stat.stringLength);
}
return 0;
}
<commit_msg>read from stdin if filename is "-" print header string normal table formatting<commit_after>#include "gason2.h"
#include "gason2dump.h"
#include <stdio.h>
#include <stdlib.h>
struct Stat {
size_t objectCount;
size_t arrayCount;
size_t numberCount;
size_t stringCount;
size_t trueCount;
size_t falseCount;
size_t nullCount;
size_t memberCount; // Number of members in all objects
size_t elementCount; // Number of elements in all arrays
size_t stringLength; // Number of code units in all strings
};
static void GenStat(Stat &stat, const gason2::node &v) {
switch (v.type()) {
case gason2::type::array:
for (auto i : v.elements())
GenStat(stat, i);
stat.elementCount += v.size();
stat.arrayCount++;
break;
case gason2::type::object:
for (auto i : v.members()) {
stat.stringLength += strlen(i.name().to_string());
GenStat(stat, i.value());
}
stat.memberCount += v.size() / 2;
stat.stringCount += v.size() / 2;
stat.objectCount++;
break;
case gason2::type::string:
stat.stringCount++;
stat.stringLength += strlen(v.to_string());
break;
case gason2::type::number:
stat.numberCount++;
break;
case gason2::type::boolean:
if (v.to_bool())
stat.trueCount++;
else
stat.falseCount++;
break;
case gason2::type::null:
stat.nullCount++;
break;
}
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s [file ...]\n", argv[0]);
exit(EXIT_FAILURE);
}
printf("%10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s\n",
"object",
"array",
"number",
"string",
"true",
"false",
"null",
"member",
"element",
"#string");
for (int i = 1; i < argc; ++i) {
FILE *fp = strcmp(argv[i], "-") ? fopen(argv[i], "rb") : stdin;
if (!fp) {
perror(argv[i]);
exit(EXIT_FAILURE);
}
gason2::vector<char> src;
while (!feof(fp)) {
char buf[BUFSIZ];
src.append(buf, fread(buf, 1, sizeof(buf), fp));
}
src.push_back('\0');
src.pop_back();
fclose(fp);
gason2::document doc;
if (!doc.parse(src.data()))
gason2::dump::print_error(argv[i], src.data(), doc);
Stat stat = {};
GenStat(stat, doc);
printf("%10zu %10zu %10zu %10zu %10zu %10zu %10zu %10zu %10zu %10zu %s\n",
stat.objectCount,
stat.arrayCount,
stat.numberCount,
stat.stringCount,
stat.trueCount,
stat.falseCount,
stat.nullCount,
stat.memberCount,
stat.elementCount,
stat.stringLength,
argv[i]);
}
return 0;
}
<|endoftext|> |
<commit_before>
#if !defined(MAX_TIMERS)
#define MAX_TIMERS MAX_WORKER_THREADS
#endif
typedef int (*taction)(void *arg);
struct timer {
double time;
double period;
taction action;
void * arg;
};
struct timers {
pthread_t threadid; /* Timer thread ID */
pthread_mutex_t mutex; /* Protects timer lists */
struct timer timers[MAX_TIMERS]; /* List of timers */
unsigned timer_count; /* Current size of timer list */
};
static int timer_add(struct mg_context * ctx, double next_time, double period, int is_relative, taction action, void * arg)
{
unsigned u, v;
int error = 0;
struct timespec now;
if (ctx->stop_flag) {
return 0;
}
if (is_relative) {
clock_gettime(CLOCK_MONOTONIC, &now);
next_time += now.tv_sec;
next_time += now.tv_nsec * 1.0E-9;
}
pthread_mutex_lock(&ctx->timers->mutex);
if (ctx->timers->timer_count == MAX_TIMERS) {
error = 1;
} else {
for (u=0; u<ctx->timers->timer_count; u++) {
if (ctx->timers->timers[u].time < next_time) {
for (v=ctx->timers->timer_count; v>u; v--) {
ctx->timers->timers[v] = ctx->timers->timers[v-1];
}
break;
}
}
ctx->timers->timers[u].time = next_time;
ctx->timers->timers[u].period = period;
ctx->timers->timers[u].action = action;
ctx->timers->timers[u].arg = arg;
ctx->timers->timer_count++;
}
pthread_mutex_unlock(&ctx->timers->mutex);
return error;
}
static void timer_thread_run(void *thread_func_param)
{
struct mg_context *ctx = (struct mg_context *) thread_func_param;
struct timespec now;
double d;
unsigned u;
int re_schedule;
struct timer t;
#if defined(HAVE_CLOCK_NANOSLEEP) /* Linux with librt */
/* TODO */
while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, &request)==EINTR) {/*nop*/;}
#else
clock_gettime(CLOCK_MONOTONIC, &now);
d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
while (ctx->stop_flag == 0) {
pthread_mutex_lock(&ctx->timers->mutex);
if (ctx->timers->timer_count > 0 && d >= ctx->timers->timers[0].time) {
t = ctx->timers->timers[0];
for (u=1; u<ctx->timers->timer_count; u++) {
ctx->timers->timers[u-1] = ctx->timers->timers[u];
}
ctx->timers->timer_count--;
pthread_mutex_unlock(&ctx->timers->mutex);
re_schedule = t.action(t.arg);
if (re_schedule && (t.period>0)) {
timer_add(ctx, t.time+t.period, t.period, 0, t.action, t.arg);
}
continue;
} else {
pthread_mutex_unlock(&ctx->timers->mutex);
}
mg_sleep(1);
clock_gettime(CLOCK_MONOTONIC, &now);
d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
}
#endif
}
#ifdef _WIN32
static unsigned __stdcall timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return 0;
}
#else
static void *timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return NULL;
}
#endif /* _WIN32 */
static int timers_init(struct mg_context * ctx)
{
ctx->timers = (struct timers*) mg_calloc(sizeof(struct timers), 1);
(void) pthread_mutex_init(&ctx->timers->mutex, NULL);
/* Start timer thread */
mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);
return 0;
}
static void timers_exit(struct mg_context * ctx)
{
(void) pthread_mutex_destroy(&ctx->timers->mutex);
mg_free(ctx->timers);
}
<commit_msg>timers_exit may be called without timers_init<commit_after>
#if !defined(MAX_TIMERS)
#define MAX_TIMERS MAX_WORKER_THREADS
#endif
typedef int (*taction)(void *arg);
struct timer {
double time;
double period;
taction action;
void * arg;
};
struct timers {
pthread_t threadid; /* Timer thread ID */
pthread_mutex_t mutex; /* Protects timer lists */
struct timer timers[MAX_TIMERS]; /* List of timers */
unsigned timer_count; /* Current size of timer list */
};
static int timer_add(struct mg_context * ctx, double next_time, double period, int is_relative, taction action, void * arg)
{
unsigned u, v;
int error = 0;
struct timespec now;
if (ctx->stop_flag) {
return 0;
}
if (is_relative) {
clock_gettime(CLOCK_MONOTONIC, &now);
next_time += now.tv_sec;
next_time += now.tv_nsec * 1.0E-9;
}
pthread_mutex_lock(&ctx->timers->mutex);
if (ctx->timers->timer_count == MAX_TIMERS) {
error = 1;
} else {
for (u=0; u<ctx->timers->timer_count; u++) {
if (ctx->timers->timers[u].time < next_time) {
for (v=ctx->timers->timer_count; v>u; v--) {
ctx->timers->timers[v] = ctx->timers->timers[v-1];
}
break;
}
}
ctx->timers->timers[u].time = next_time;
ctx->timers->timers[u].period = period;
ctx->timers->timers[u].action = action;
ctx->timers->timers[u].arg = arg;
ctx->timers->timer_count++;
}
pthread_mutex_unlock(&ctx->timers->mutex);
return error;
}
static void timer_thread_run(void *thread_func_param)
{
struct mg_context *ctx = (struct mg_context *) thread_func_param;
struct timespec now;
double d;
unsigned u;
int re_schedule;
struct timer t;
#if defined(HAVE_CLOCK_NANOSLEEP) /* Linux with librt */
/* TODO */
while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, &request)==EINTR) {/*nop*/;}
#else
clock_gettime(CLOCK_MONOTONIC, &now);
d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
while (ctx->stop_flag == 0) {
pthread_mutex_lock(&ctx->timers->mutex);
if (ctx->timers->timer_count > 0 && d >= ctx->timers->timers[0].time) {
t = ctx->timers->timers[0];
for (u=1; u<ctx->timers->timer_count; u++) {
ctx->timers->timers[u-1] = ctx->timers->timers[u];
}
ctx->timers->timer_count--;
pthread_mutex_unlock(&ctx->timers->mutex);
re_schedule = t.action(t.arg);
if (re_schedule && (t.period>0)) {
timer_add(ctx, t.time+t.period, t.period, 0, t.action, t.arg);
}
continue;
} else {
pthread_mutex_unlock(&ctx->timers->mutex);
}
mg_sleep(1);
clock_gettime(CLOCK_MONOTONIC, &now);
d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
}
#endif
}
#ifdef _WIN32
static unsigned __stdcall timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return 0;
}
#else
static void *timer_thread(void *thread_func_param)
{
timer_thread_run(thread_func_param);
return NULL;
}
#endif /* _WIN32 */
static int timers_init(struct mg_context * ctx)
{
ctx->timers = (struct timers*) mg_calloc(sizeof(struct timers), 1);
(void) pthread_mutex_init(&ctx->timers->mutex, NULL);
/* Start timer thread */
mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);
return 0;
}
static void timers_exit(struct mg_context * ctx)
{
if (ctx->timers) {
(void) pthread_mutex_destroy(&ctx->timers->mutex);
mg_free(ctx->timers);
}
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <iostream>
#include <QtUiTools>
#include <QtDebug>
#include "med/MedException.hpp"
#include "med/MedCommon.hpp"
#include "ui/Ui.hpp"
#include "ui/ProcessEventListener.hpp"
#include "ui/ScanTreeEventListener.hpp"
#include "ui/StoreTreeEventListener.hpp"
#include "ui/ComboBoxDelegate.hpp"
#include "ui/CheckBoxDelegate.hpp"
#include "ui/EncodingManager.hpp"
using namespace std;
MedUi::MedUi(QApplication* app) {
this->app = app;
med = new MemEd();
loadUiFiles();
loadProcessUi();
setupStatusBar();
setupScanTreeView();
setupStoreTreeView();
setupSignals();
setupUi();
encodingManager = new EncodingManager(this);
setScanState(UiState::Idle);
setStoreState(UiState::Idle);
// TODO: other action here
}
MedUi::~MedUi() {
delete med;
delete encodingManager;
refreshThread->join();
delete refreshThread;
}
void MedUi::loadUiFiles() {
QUiLoader loader;
QFile file("./main-qt.ui");
file.open(QFile::ReadOnly);
mainWindow = loader.load(&file);
file.close();
selectedProcessLine = mainWindow->findChild<QLineEdit*>("selectedProcess");
scanTypeCombo = mainWindow->findChild<QComboBox*>("scanType");
scanTreeView = mainWindow->findChild<QTreeView*>("scanTreeView");
storeTreeView = mainWindow->findChild<QTreeView*>("storeTreeView");
scanTreeView->installEventFilter(new ScanTreeEventListener(scanTreeView, this));
storeTreeView->installEventFilter(new StoreTreeEventListener(storeTreeView, this));
notesArea = mainWindow->findChild<QPlainTextEdit*>("notes");
// TODO: Notes
}
void MedUi::loadProcessUi() {
QUiLoader loader;
//Cannot put the followings to another method
processDialog = new QDialog(mainWindow); //If put this to another method, then I cannot set the mainWindow as the parent
QFile processFile("./process.ui");
processFile.open(QFile::ReadOnly);
processSelector = loader.load(&processFile, processDialog);
processFile.close();
processTreeWidget = processSelector->findChild<QTreeWidget*>("processTreeWidget");
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(processSelector);
processDialog->setLayout(layout);
processDialog->setModal(true);
processDialog->resize(400, 400);
//Add signal
QObject::connect(processTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onProcessItemDblClicked(QTreeWidgetItem*, int)));
processTreeWidget->installEventFilter(new ProcessDialogEventListener(this));
}
void MedUi::setupUi() {
scanTypeCombo->setCurrentIndex(1);
mainWindow->show();
qRegisterMetaType<QVector<int>>(); //For multithreading.
refreshThread = new std::thread(MedUi::refresh, this);
}
void MedUi::setupStatusBar() {
//Statusbar message
statusBar = mainWindow->findChild<QStatusBar*>("statusbar");
statusBar->showMessage("Tips: Left panel is scanned address. Right panel is stored address.");
}
void MedUi::setupSignals() {
QObject::connect(mainWindow->findChild<QWidget*>("process"),
SIGNAL(clicked()),
this,
SLOT(onProcessClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("scanButton"),
SIGNAL(clicked()),
this,
SLOT(onScanClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("filterButton"),
SIGNAL(clicked()),
this,
SLOT(onFilterClicked()));
QObject::connect(mainWindow->findChild<QPushButton*>("scanAdd"),
SIGNAL(clicked()),
this,
SLOT(onScanAddClicked()));
QObject::connect(mainWindow->findChild<QPushButton*>("scanAddAll"),
SIGNAL(clicked()),
this,
SLOT(onScanAddAllClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("scanClear"),
SIGNAL(clicked()),
this,
SLOT(onScanClearClicked()));
QObject::connect(mainWindow->findChild<QAction*>("actionSaveAs"),
SIGNAL(triggered()),
this,
SLOT(onSaveAsTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionOpen"),
SIGNAL(triggered()),
this,
SLOT(onOpenTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionSave"),
SIGNAL(triggered()),
this,
SLOT(onSaveTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionQuit"),
SIGNAL(triggered()),
this,
SLOT(onQuitTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionReload"),
SIGNAL(triggered()),
this,
SLOT(onReloadTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionShowNotes"),
SIGNAL(triggered(bool)),
this,
SLOT(onShowNotesTriggered(bool)));
QObject::connect(notesArea,
SIGNAL(textChanged()),
this,
SLOT(onNotesAreaChanged()));
}
void MedUi::setupScanTreeView() {
scanModel = new TreeModel(this, mainWindow);
scanTreeView->setModel(scanModel);
ComboBoxDelegate* delegate = new ComboBoxDelegate();
scanTreeView->setItemDelegateForColumn(SCAN_COL_TYPE, delegate);
QObject::connect(scanTreeView,
SIGNAL(clicked(QModelIndex)),
this,
SLOT(onScanTreeViewClicked(QModelIndex)));
QObject::connect(scanTreeView,
SIGNAL(doubleClicked(QModelIndex)),
this,
SLOT(onScanTreeViewDoubleClicked(QModelIndex)));
QObject::connect(scanModel,
SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)),
this,
SLOT(onScanTreeViewDataChanged(QModelIndex, QModelIndex, QVector<int>)));
scanTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
void MedUi::setupStoreTreeView() {
storeModel = new StoreTreeModel(this, mainWindow);
storeTreeView->setModel(storeModel);
ComboBoxDelegate* storeDelegate = new ComboBoxDelegate();
storeTreeView->setItemDelegateForColumn(STORE_COL_TYPE, storeDelegate);
CheckBoxDelegate* storeLockDelegate = new CheckBoxDelegate();
storeTreeView->setItemDelegateForColumn(STORE_COL_LOCK, storeLockDelegate);
QObject::connect(storeTreeView,
SIGNAL(clicked(QModelIndex)),
this,
SLOT(onStoreTreeViewClicked(QModelIndex)));
QObject::connect(storeTreeView,
SIGNAL(doubleClicked(QModelIndex)),
this,
SLOT(onStoreTreeViewDoubleClicked(QModelIndex)));
QObject::connect(storeModel,
SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)),
this,
SLOT(onStoreTreeViewDataChanged(QModelIndex, QModelIndex, QVector<int>)));
auto* header = storeTreeView->header();
header->setSectionsClickable(true);
QObject::connect(header,
SIGNAL(sectionClicked(int)),
this,
SLOT(onStoreHeaderClicked(int)));
storeTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
void MedUi::onProcessClicked() {
med->listProcesses();
processDialog->show();
processTreeWidget->clear();
for (int i = med->processes.size() - 1; i >= 0; i--) {
QTreeWidgetItem* item = new QTreeWidgetItem(processTreeWidget);
item->setText(0, med->processes[i].pid.c_str());
item->setText(1, med->processes[i].cmdline.c_str());
}
}
void MedUi::onProcessItemDblClicked(QTreeWidgetItem* item, int) {
int index = item->treeWidget()->indexOfTopLevelItem(item); //Get the current row index
Process process = med->selectProcessByIndex(med->processes.size() - 1 - index);
selectedProcessLine->setText(QString::fromLatin1((process.pid + " " + process.cmdline).c_str())); //Do not use fromStdString(), it will append with some unknown characters
processDialog->hide();
}
void MedUi::onScanClicked() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if (QString(scanValue.c_str()).trimmed() == "") {
return;
}
string scanType = scanTypeCombo->currentText().toStdString();
if (scanType == SCAN_TYPE_STRING) {
scanValue = encodingManager->encode(scanValue);
}
try {
med->scan(scanValue, scanType);
} catch(MedException &ex) {
cerr << "scan: "<< ex.what() << endl;
}
scanModel->clearAll();
if(med->getScans().size() <= SCAN_ADDRESS_VISIBLE_SIZE) {
scanModel->addScan(scanType);
}
if (QString(scanValue.c_str()).trimmed() == "?") {
statusBar->showMessage("Snapshot saved");
}
else {
updateNumberOfAddresses();
}
}
void MedUi::onFilterClicked() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if (QString(scanValue.c_str()).trimmed() == "") {
return;
}
string scanType = scanTypeCombo->currentText().toStdString();
if (scanType == SCAN_TYPE_STRING) {
scanValue = encodingManager->encode(scanValue);
}
med->filter(scanValue, scanType);
if(med->getScans().size() <= SCAN_ADDRESS_VISIBLE_SIZE) {
scanModel->addScan(scanType);
}
updateNumberOfAddresses();
}
void MedUi::onScanTreeViewClicked(const QModelIndex &index) {
if(index.column() == SCAN_COL_TYPE) {
scanTreeView->edit(index); //Trigger edit by 1 click
}
}
void MedUi::onScanTreeViewDoubleClicked(const QModelIndex &index) {
if (index.column() == SCAN_COL_VALUE) {
scanUpdateMutex.lock();
setScanState(UiState::Editing);
}
}
void MedUi::onScanTreeViewDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles) {
// qDebug() << topLeft << bottomRight << roles;
if (topLeft.column() == SCAN_COL_VALUE) {
tryUnlock(scanUpdateMutex);
setScanState(UiState::Idle);
}
}
void MedUi::onStoreTreeViewDoubleClicked(const QModelIndex &index) {
if (index.column() == STORE_COL_VALUE) {
storeUpdateMutex.lock();
storeState = UiState::Editing;
}
}
void MedUi::onStoreTreeViewClicked(const QModelIndex &index) {
if (index.column() == STORE_COL_TYPE) {
storeTreeView->edit(index);
}
else if (index.column() == STORE_COL_LOCK) {
storeTreeView->edit(index);
}
}
void MedUi::onStoreTreeViewDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles) {
// qDebug() << topLeft << bottomRight << roles;
if (topLeft.column() == STORE_COL_VALUE) {
tryUnlock(storeUpdateMutex);
storeState = UiState::Idle;
}
}
void MedUi::onScanAddClicked() {
auto indexes = scanTreeView
->selectionModel()
->selectedRows(SCAN_COL_ADDRESS);
scanUpdateMutex.lock();
for (int i = 0; i < indexes.size(); i++) {
med->addToStoreByIndex(indexes[i].row());
}
storeModel->refresh();
scanUpdateMutex.unlock();
}
void MedUi::onScanAddAllClicked() {
scanUpdateMutex.lock();
for (size_t i = 0; i < med->getScans().size(); i++) {
med->addToStoreByIndex(i);
}
storeModel->refresh();
scanUpdateMutex.unlock();
}
void MedUi::onScanClearClicked() {
scanUpdateMutex.lock();
scanModel->empty();
statusBar->showMessage("Scan cleared");
scanUpdateMutex.unlock();
}
void MedUi::onStoreHeaderClicked(int logicalIndex) {
if (logicalIndex == STORE_COL_DESCRIPTION) {
storeModel->sortByDescription();
}
else if (logicalIndex == STORE_COL_ADDRESS) {
storeModel->sortByAddress();
}
}
///////////////////
// Menu items //
///////////////////
void MedUi::onSaveAsTriggered() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
QString filename = QFileDialog::getSaveFileName(mainWindow,
QString("Save JSON"),
"./",
QString("Save JSON (*.json)"));
if (filename == "") {
return;
}
this->filename = filename;
setWindowTitle();
med->saveFile(filename.toStdString().c_str());
}
void MedUi::onOpenTriggered() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
QString filename = QFileDialog::getOpenFileName(mainWindow,
QString("Open JSON"),
"./",
QString("Open JSON (*.json)"));
if (filename == "") {
return;
}
openFile(filename);
}
void MedUi::onReloadTriggered() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
if (filename == "") {
return;
}
openFile(filename);
}
void MedUi::openFile(QString filename) {
this->filename = filename;
setWindowTitle();
med->openFile(filename.toStdString().c_str());
storeUpdateMutex.lock();
storeModel->clearAll();
storeModel->refresh();
storeUpdateMutex.unlock();
notesArea->setPlainText(QString::fromStdString(med->getNotes()));
}
void MedUi::setWindowTitle() {
if (filename.length() > 0) {
mainWindow->setWindowTitle(MAIN_TITLE + ": " + filename);
}
else {
mainWindow->setWindowTitle(MAIN_TITLE);
}
}
void MedUi::onSaveTriggered() {
if (filename == "") {
return;
}
med->saveFile(filename.toStdString().c_str());
statusBar->showMessage("Saved");
}
////// End Menu > File ////////////
void MedUi::onShowNotesTriggered(bool checked) {
if (checked) {
notesArea->show();
}
else {
notesArea->hide();
}
}
void MedUi::onNotesAreaChanged() {
med->setNotes(notesArea->toPlainText().toStdString());
}
void MedUi::onQuitTriggered() {
app->quit();
}
void MedUi::updateNumberOfAddresses() {
char message[128];
sprintf(message, "%ld", med->getScans().size());
mainWindow->findChild<QLabel*>("found")->setText(message);
}
void MedUi::refresh(MedUi* mainUi) {
// TODO: Store refresh if closing
while (1) {
mainUi->refreshScanTreeView();
mainUi->refreshStoreTreeView();
std::this_thread::sleep_for(chrono::milliseconds(REFRESH_RATE));
}
}
void MedUi::refreshScanTreeView() {
scanUpdateMutex.lock();
scanModel->refreshValues();
scanUpdateMutex.unlock();
}
void MedUi::refreshStoreTreeView() {
storeUpdateMutex.lock();
storeModel->refreshValues();
storeUpdateMutex.unlock();
}
UiState MedUi::getScanState() {
return scanState;
}
UiState MedUi::getStoreState() {
return storeState;
}
void MedUi::setScanState(UiState state) {
scanState = state;
}
void MedUi::setStoreState(UiState state) {
storeState = state;
}
<commit_msg>Hide notes area by default<commit_after>#include <cstdio>
#include <iostream>
#include <QtUiTools>
#include <QtDebug>
#include "med/MedException.hpp"
#include "med/MedCommon.hpp"
#include "ui/Ui.hpp"
#include "ui/ProcessEventListener.hpp"
#include "ui/ScanTreeEventListener.hpp"
#include "ui/StoreTreeEventListener.hpp"
#include "ui/ComboBoxDelegate.hpp"
#include "ui/CheckBoxDelegate.hpp"
#include "ui/EncodingManager.hpp"
using namespace std;
MedUi::MedUi(QApplication* app) {
this->app = app;
med = new MemEd();
loadUiFiles();
loadProcessUi();
setupStatusBar();
setupScanTreeView();
setupStoreTreeView();
setupSignals();
setupUi();
encodingManager = new EncodingManager(this);
setScanState(UiState::Idle);
setStoreState(UiState::Idle);
// TODO: other action here
}
MedUi::~MedUi() {
delete med;
delete encodingManager;
refreshThread->join();
delete refreshThread;
}
void MedUi::loadUiFiles() {
QUiLoader loader;
QFile file("./main-qt.ui");
file.open(QFile::ReadOnly);
mainWindow = loader.load(&file);
file.close();
selectedProcessLine = mainWindow->findChild<QLineEdit*>("selectedProcess");
scanTypeCombo = mainWindow->findChild<QComboBox*>("scanType");
scanTreeView = mainWindow->findChild<QTreeView*>("scanTreeView");
storeTreeView = mainWindow->findChild<QTreeView*>("storeTreeView");
scanTreeView->installEventFilter(new ScanTreeEventListener(scanTreeView, this));
storeTreeView->installEventFilter(new StoreTreeEventListener(storeTreeView, this));
notesArea = mainWindow->findChild<QPlainTextEdit*>("notes");
// TODO: Notes
}
void MedUi::loadProcessUi() {
QUiLoader loader;
//Cannot put the followings to another method
processDialog = new QDialog(mainWindow); //If put this to another method, then I cannot set the mainWindow as the parent
QFile processFile("./process.ui");
processFile.open(QFile::ReadOnly);
processSelector = loader.load(&processFile, processDialog);
processFile.close();
processTreeWidget = processSelector->findChild<QTreeWidget*>("processTreeWidget");
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(processSelector);
processDialog->setLayout(layout);
processDialog->setModal(true);
processDialog->resize(400, 400);
//Add signal
QObject::connect(processTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onProcessItemDblClicked(QTreeWidgetItem*, int)));
processTreeWidget->installEventFilter(new ProcessDialogEventListener(this));
}
void MedUi::setupUi() {
scanTypeCombo->setCurrentIndex(1);
mainWindow->show();
qRegisterMetaType<QVector<int>>(); //For multithreading.
refreshThread = new std::thread(MedUi::refresh, this);
QAction* showNotesAction = mainWindow->findChild<QAction*>("actionShowNotes");
if (showNotesAction->isChecked()) {
notesArea->show();
}
else {
notesArea->hide();
}
}
void MedUi::setupStatusBar() {
//Statusbar message
statusBar = mainWindow->findChild<QStatusBar*>("statusbar");
statusBar->showMessage("Tips: Left panel is scanned address. Right panel is stored address.");
}
void MedUi::setupSignals() {
QObject::connect(mainWindow->findChild<QWidget*>("process"),
SIGNAL(clicked()),
this,
SLOT(onProcessClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("scanButton"),
SIGNAL(clicked()),
this,
SLOT(onScanClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("filterButton"),
SIGNAL(clicked()),
this,
SLOT(onFilterClicked()));
QObject::connect(mainWindow->findChild<QPushButton*>("scanAdd"),
SIGNAL(clicked()),
this,
SLOT(onScanAddClicked()));
QObject::connect(mainWindow->findChild<QPushButton*>("scanAddAll"),
SIGNAL(clicked()),
this,
SLOT(onScanAddAllClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("scanClear"),
SIGNAL(clicked()),
this,
SLOT(onScanClearClicked()));
QObject::connect(mainWindow->findChild<QAction*>("actionSaveAs"),
SIGNAL(triggered()),
this,
SLOT(onSaveAsTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionOpen"),
SIGNAL(triggered()),
this,
SLOT(onOpenTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionSave"),
SIGNAL(triggered()),
this,
SLOT(onSaveTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionQuit"),
SIGNAL(triggered()),
this,
SLOT(onQuitTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionReload"),
SIGNAL(triggered()),
this,
SLOT(onReloadTriggered()));
QObject::connect(mainWindow->findChild<QAction*>("actionShowNotes"),
SIGNAL(triggered(bool)),
this,
SLOT(onShowNotesTriggered(bool)));
QObject::connect(notesArea,
SIGNAL(textChanged()),
this,
SLOT(onNotesAreaChanged()));
}
void MedUi::setupScanTreeView() {
scanModel = new TreeModel(this, mainWindow);
scanTreeView->setModel(scanModel);
ComboBoxDelegate* delegate = new ComboBoxDelegate();
scanTreeView->setItemDelegateForColumn(SCAN_COL_TYPE, delegate);
QObject::connect(scanTreeView,
SIGNAL(clicked(QModelIndex)),
this,
SLOT(onScanTreeViewClicked(QModelIndex)));
QObject::connect(scanTreeView,
SIGNAL(doubleClicked(QModelIndex)),
this,
SLOT(onScanTreeViewDoubleClicked(QModelIndex)));
QObject::connect(scanModel,
SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)),
this,
SLOT(onScanTreeViewDataChanged(QModelIndex, QModelIndex, QVector<int>)));
scanTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
void MedUi::setupStoreTreeView() {
storeModel = new StoreTreeModel(this, mainWindow);
storeTreeView->setModel(storeModel);
ComboBoxDelegate* storeDelegate = new ComboBoxDelegate();
storeTreeView->setItemDelegateForColumn(STORE_COL_TYPE, storeDelegate);
CheckBoxDelegate* storeLockDelegate = new CheckBoxDelegate();
storeTreeView->setItemDelegateForColumn(STORE_COL_LOCK, storeLockDelegate);
QObject::connect(storeTreeView,
SIGNAL(clicked(QModelIndex)),
this,
SLOT(onStoreTreeViewClicked(QModelIndex)));
QObject::connect(storeTreeView,
SIGNAL(doubleClicked(QModelIndex)),
this,
SLOT(onStoreTreeViewDoubleClicked(QModelIndex)));
QObject::connect(storeModel,
SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)),
this,
SLOT(onStoreTreeViewDataChanged(QModelIndex, QModelIndex, QVector<int>)));
auto* header = storeTreeView->header();
header->setSectionsClickable(true);
QObject::connect(header,
SIGNAL(sectionClicked(int)),
this,
SLOT(onStoreHeaderClicked(int)));
storeTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
void MedUi::onProcessClicked() {
med->listProcesses();
processDialog->show();
processTreeWidget->clear();
for (int i = med->processes.size() - 1; i >= 0; i--) {
QTreeWidgetItem* item = new QTreeWidgetItem(processTreeWidget);
item->setText(0, med->processes[i].pid.c_str());
item->setText(1, med->processes[i].cmdline.c_str());
}
}
void MedUi::onProcessItemDblClicked(QTreeWidgetItem* item, int) {
int index = item->treeWidget()->indexOfTopLevelItem(item); //Get the current row index
Process process = med->selectProcessByIndex(med->processes.size() - 1 - index);
selectedProcessLine->setText(QString::fromLatin1((process.pid + " " + process.cmdline).c_str())); //Do not use fromStdString(), it will append with some unknown characters
processDialog->hide();
}
void MedUi::onScanClicked() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if (QString(scanValue.c_str()).trimmed() == "") {
return;
}
string scanType = scanTypeCombo->currentText().toStdString();
if (scanType == SCAN_TYPE_STRING) {
scanValue = encodingManager->encode(scanValue);
}
try {
med->scan(scanValue, scanType);
} catch(MedException &ex) {
cerr << "scan: "<< ex.what() << endl;
}
scanModel->clearAll();
if(med->getScans().size() <= SCAN_ADDRESS_VISIBLE_SIZE) {
scanModel->addScan(scanType);
}
if (QString(scanValue.c_str()).trimmed() == "?") {
statusBar->showMessage("Snapshot saved");
}
else {
updateNumberOfAddresses();
}
}
void MedUi::onFilterClicked() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if (QString(scanValue.c_str()).trimmed() == "") {
return;
}
string scanType = scanTypeCombo->currentText().toStdString();
if (scanType == SCAN_TYPE_STRING) {
scanValue = encodingManager->encode(scanValue);
}
med->filter(scanValue, scanType);
if(med->getScans().size() <= SCAN_ADDRESS_VISIBLE_SIZE) {
scanModel->addScan(scanType);
}
updateNumberOfAddresses();
}
void MedUi::onScanTreeViewClicked(const QModelIndex &index) {
if(index.column() == SCAN_COL_TYPE) {
scanTreeView->edit(index); //Trigger edit by 1 click
}
}
void MedUi::onScanTreeViewDoubleClicked(const QModelIndex &index) {
if (index.column() == SCAN_COL_VALUE) {
scanUpdateMutex.lock();
setScanState(UiState::Editing);
}
}
void MedUi::onScanTreeViewDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles) {
// qDebug() << topLeft << bottomRight << roles;
if (topLeft.column() == SCAN_COL_VALUE) {
tryUnlock(scanUpdateMutex);
setScanState(UiState::Idle);
}
}
void MedUi::onStoreTreeViewDoubleClicked(const QModelIndex &index) {
if (index.column() == STORE_COL_VALUE) {
storeUpdateMutex.lock();
storeState = UiState::Editing;
}
}
void MedUi::onStoreTreeViewClicked(const QModelIndex &index) {
if (index.column() == STORE_COL_TYPE) {
storeTreeView->edit(index);
}
else if (index.column() == STORE_COL_LOCK) {
storeTreeView->edit(index);
}
}
void MedUi::onStoreTreeViewDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles) {
// qDebug() << topLeft << bottomRight << roles;
if (topLeft.column() == STORE_COL_VALUE) {
tryUnlock(storeUpdateMutex);
storeState = UiState::Idle;
}
}
void MedUi::onScanAddClicked() {
auto indexes = scanTreeView
->selectionModel()
->selectedRows(SCAN_COL_ADDRESS);
scanUpdateMutex.lock();
for (int i = 0; i < indexes.size(); i++) {
med->addToStoreByIndex(indexes[i].row());
}
storeModel->refresh();
scanUpdateMutex.unlock();
}
void MedUi::onScanAddAllClicked() {
scanUpdateMutex.lock();
for (size_t i = 0; i < med->getScans().size(); i++) {
med->addToStoreByIndex(i);
}
storeModel->refresh();
scanUpdateMutex.unlock();
}
void MedUi::onScanClearClicked() {
scanUpdateMutex.lock();
scanModel->empty();
statusBar->showMessage("Scan cleared");
scanUpdateMutex.unlock();
}
void MedUi::onStoreHeaderClicked(int logicalIndex) {
if (logicalIndex == STORE_COL_DESCRIPTION) {
storeModel->sortByDescription();
}
else if (logicalIndex == STORE_COL_ADDRESS) {
storeModel->sortByAddress();
}
}
///////////////////
// Menu items //
///////////////////
void MedUi::onSaveAsTriggered() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
QString filename = QFileDialog::getSaveFileName(mainWindow,
QString("Save JSON"),
"./",
QString("Save JSON (*.json)"));
if (filename == "") {
return;
}
this->filename = filename;
setWindowTitle();
med->saveFile(filename.toStdString().c_str());
}
void MedUi::onOpenTriggered() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
QString filename = QFileDialog::getOpenFileName(mainWindow,
QString("Open JSON"),
"./",
QString("Open JSON (*.json)"));
if (filename == "") {
return;
}
openFile(filename);
}
void MedUi::onReloadTriggered() {
if(med->selectedProcess.pid == "") {
statusBar->showMessage("No process selected");
return;
}
if (filename == "") {
return;
}
openFile(filename);
}
void MedUi::openFile(QString filename) {
this->filename = filename;
setWindowTitle();
med->openFile(filename.toStdString().c_str());
storeUpdateMutex.lock();
storeModel->clearAll();
storeModel->refresh();
storeUpdateMutex.unlock();
notesArea->setPlainText(QString::fromStdString(med->getNotes()));
}
void MedUi::setWindowTitle() {
if (filename.length() > 0) {
mainWindow->setWindowTitle(MAIN_TITLE + ": " + filename);
}
else {
mainWindow->setWindowTitle(MAIN_TITLE);
}
}
void MedUi::onSaveTriggered() {
if (filename == "") {
return;
}
med->saveFile(filename.toStdString().c_str());
statusBar->showMessage("Saved");
}
////// End Menu > File ////////////
void MedUi::onShowNotesTriggered(bool checked) {
if (checked) {
notesArea->show();
}
else {
notesArea->hide();
}
}
void MedUi::onNotesAreaChanged() {
med->setNotes(notesArea->toPlainText().toStdString());
}
void MedUi::onQuitTriggered() {
app->quit();
}
void MedUi::updateNumberOfAddresses() {
char message[128];
sprintf(message, "%ld", med->getScans().size());
mainWindow->findChild<QLabel*>("found")->setText(message);
}
void MedUi::refresh(MedUi* mainUi) {
// TODO: Store refresh if closing
while (1) {
mainUi->refreshScanTreeView();
mainUi->refreshStoreTreeView();
std::this_thread::sleep_for(chrono::milliseconds(REFRESH_RATE));
}
}
void MedUi::refreshScanTreeView() {
scanUpdateMutex.lock();
scanModel->refreshValues();
scanUpdateMutex.unlock();
}
void MedUi::refreshStoreTreeView() {
storeUpdateMutex.lock();
storeModel->refreshValues();
storeUpdateMutex.unlock();
}
UiState MedUi::getScanState() {
return scanState;
}
UiState MedUi::getStoreState() {
return storeState;
}
void MedUi::setScanState(UiState state) {
scanState = state;
}
void MedUi::setStoreState(UiState state) {
storeState = state;
}
<|endoftext|> |
<commit_before>/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
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 <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <QTemporaryFile>
#include "consts.h"
#include "terminal.h"
#include "utils.h"
QTemporaryFile* Utils::m_tempHarness = 0;
QTemporaryFile* Utils::m_tempWrapper = 0;
bool Utils::printDebugMessages = false;
void Utils::messageHandler(QtMsgType type, const char *msg)
{
QDateTime now = QDateTime::currentDateTime();
switch (type) {
case QtDebugMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [DEBUG] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
}
break;
case QtWarningMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [WARNING] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
}
break;
case QtCriticalMsg:
fprintf(stderr, "%s [CRITICAL] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
break;
case QtFatalMsg:
fprintf(stderr, "%s [FATAL] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
abort();
}
}
#ifdef Q_OS_WIN32
bool Utils::exceptionHandler(const TCHAR* dump_path, const TCHAR* minidump_id,
void* context, EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo *assertion, bool succeeded)
{
Q_UNUSED(exinfo);
Q_UNUSED(assertion);
Q_UNUSED(context);
fprintf(stderr, "PhantomJS has crashed. Please read the crash reporting guide at " \
"https://code.google.com/p/phantomjs/wiki/CrashReporting and file a " \
"bug report at https://code.google.com/p/phantomjs/issues/entry with the " \
"crash dump file attached: %ls\\%ls.dmp\n",
dump_path, minidump_id);
return succeeded;
}
#else
bool Utils::exceptionHandler(const char* dump_path, const char* minidump_id, void* context, bool succeeded)
{
Q_UNUSED(context);
fprintf(stderr, "PhantomJS has crashed. Please read the crash reporting guide at " \
"https://code.google.com/p/phantomjs/wiki/CrashReporting and file a " \
"bug report at https://code.google.com/p/phantomjs/issues/entry with the " \
"crash dump file attached: %s/%s.dmp\n",
dump_path, minidump_id);
return succeeded;
}
#endif
QVariant Utils::coffee2js(const QString &script)
{
return CSConverter::instance()->convert(script);
}
bool Utils::injectJsInFrame(const QString &jsFilePath, const QString &libraryPath, QWebFrame *targetFrame, const bool startingScript)
{
return injectJsInFrame(jsFilePath, Encoding::UTF8, libraryPath, targetFrame, startingScript);
}
bool Utils::injectJsInFrame(const QString &jsFilePath, const Encoding &jsFileEnc, const QString &libraryPath, QWebFrame *targetFrame, const bool startingScript)
{
// Don't do anything if an empty string is passed
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileEnc);
if (scriptBody.isEmpty())
{
if (startingScript) {
Terminal::instance()->cerr(QString("Can't open '%1'").arg(jsFilePath));
} else {
qWarning("Can't open '%s'", qPrintable(jsFilePath));
}
return false;
}
// Execute JS code in the context of the document
targetFrame->evaluateJavaScript(scriptBody, jsFilePath);
return true;
}
bool Utils::loadJSForDebug(const QString& jsFilePath, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
return loadJSForDebug(jsFilePath, Encoding::UTF8, libraryPath, targetFrame, autorun);
}
bool Utils::loadJSForDebug(const QString& jsFilePath, const Encoding& jsFileEnc, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileEnc);
QString remoteDebuggerHarnessSrc = Utils::readResourceFileUtf8(":/remote_debugger_harness.html");
remoteDebuggerHarnessSrc = remoteDebuggerHarnessSrc.arg(scriptBody);
targetFrame->setHtml(remoteDebuggerHarnessSrc);
if (autorun) {
targetFrame->evaluateJavaScript("__run()", QString());
}
return true;
}
QString Utils::findScript(const QString& jsFilePath, const QString &libraryPath)
{
QString filePath = jsFilePath;
if (!jsFilePath.isEmpty()) {
QFile jsFile;
// Is file in the PWD?
jsFile.setFileName(QDir::fromNativeSeparators(jsFilePath)); //< Normalise User-provided path
if (!jsFile.exists()) {
// File is not in the PWD. Is it in the lookup directory?
jsFile.setFileName(libraryPath + '/' + QDir::fromNativeSeparators(jsFilePath));
}
return jsFile.fileName();
}
return QString();
}
QString Utils::jsFromScriptFile(const QString& scriptPath, const Encoding& enc)
{
QFile jsFile(scriptPath);
if (jsFile.exists() && jsFile.open(QFile::ReadOnly)) {
QString scriptBody = enc.decode(jsFile.readAll());
// Remove CLI script heading
if (scriptBody.startsWith("#!") && !jsFile.fileName().endsWith(COFFEE_SCRIPT_EXTENSION)) {
scriptBody.prepend("//");
}
if (jsFile.fileName().endsWith(COFFEE_SCRIPT_EXTENSION)) {
QVariant result = Utils::coffee2js(scriptBody);
if (result.toStringList().at(0) == "false") {
return QString();
} else {
scriptBody = result.toStringList().at(1);
}
}
jsFile.close();
return scriptBody;
} else {
return QString();
}
}
void
Utils::cleanupFromDebug()
{
if (m_tempHarness) {
// Will erase the temp file on disk
delete m_tempHarness;
m_tempHarness = 0;
}
if (m_tempWrapper) {
delete m_tempWrapper;
m_tempWrapper = 0;
}
}
QString Utils::readResourceFileUtf8(const QString &resourceFilePath)
{
QFile f(resourceFilePath);
f.open(QFile::ReadOnly); //< It's OK to assume this succeed. If it doesn't, we have a bigger problem.
return QString::fromUtf8(f.readAll());
}
// private:
Utils::Utils()
{
// Nothing to do here
}
<commit_msg>Update the link to the crash reporting guide.<commit_after>/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
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 <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <QTemporaryFile>
#include "consts.h"
#include "terminal.h"
#include "utils.h"
QTemporaryFile* Utils::m_tempHarness = 0;
QTemporaryFile* Utils::m_tempWrapper = 0;
bool Utils::printDebugMessages = false;
void Utils::messageHandler(QtMsgType type, const char *msg)
{
QDateTime now = QDateTime::currentDateTime();
switch (type) {
case QtDebugMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [DEBUG] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
}
break;
case QtWarningMsg:
if (printDebugMessages) {
fprintf(stderr, "%s [WARNING] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
}
break;
case QtCriticalMsg:
fprintf(stderr, "%s [CRITICAL] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
break;
case QtFatalMsg:
fprintf(stderr, "%s [FATAL] %s\n", qPrintable(now.toString(Qt::ISODate)), msg);
abort();
}
}
#ifdef Q_OS_WIN32
bool Utils::exceptionHandler(const TCHAR* dump_path, const TCHAR* minidump_id,
void* context, EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo *assertion, bool succeeded)
{
Q_UNUSED(exinfo);
Q_UNUSED(assertion);
Q_UNUSED(context);
fprintf(stderr, "PhantomJS has crashed. Please read the crash reporting guide at " \
"https://github.com/ariya/phantomjs/wiki/Crash-Reporting and file a " \
"bug report at https://code.google.com/p/phantomjs/issues/entry with the " \
"crash dump file attached: %ls\\%ls.dmp\n",
dump_path, minidump_id);
return succeeded;
}
#else
bool Utils::exceptionHandler(const char* dump_path, const char* minidump_id, void* context, bool succeeded)
{
Q_UNUSED(context);
fprintf(stderr, "PhantomJS has crashed. Please read the crash reporting guide at " \
"https://github.com/ariya/phantomjs/wiki/Crash-Reporting and file a " \
"bug report at https://code.google.com/p/phantomjs/issues/entry with the " \
"crash dump file attached: %s/%s.dmp\n",
dump_path, minidump_id);
return succeeded;
}
#endif
QVariant Utils::coffee2js(const QString &script)
{
return CSConverter::instance()->convert(script);
}
bool Utils::injectJsInFrame(const QString &jsFilePath, const QString &libraryPath, QWebFrame *targetFrame, const bool startingScript)
{
return injectJsInFrame(jsFilePath, Encoding::UTF8, libraryPath, targetFrame, startingScript);
}
bool Utils::injectJsInFrame(const QString &jsFilePath, const Encoding &jsFileEnc, const QString &libraryPath, QWebFrame *targetFrame, const bool startingScript)
{
// Don't do anything if an empty string is passed
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileEnc);
if (scriptBody.isEmpty())
{
if (startingScript) {
Terminal::instance()->cerr(QString("Can't open '%1'").arg(jsFilePath));
} else {
qWarning("Can't open '%s'", qPrintable(jsFilePath));
}
return false;
}
// Execute JS code in the context of the document
targetFrame->evaluateJavaScript(scriptBody, jsFilePath);
return true;
}
bool Utils::loadJSForDebug(const QString& jsFilePath, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
return loadJSForDebug(jsFilePath, Encoding::UTF8, libraryPath, targetFrame, autorun);
}
bool Utils::loadJSForDebug(const QString& jsFilePath, const Encoding& jsFileEnc, const QString& libraryPath, QWebFrame* targetFrame, const bool autorun)
{
QString scriptPath = findScript(jsFilePath, libraryPath);
QString scriptBody = jsFromScriptFile(scriptPath, jsFileEnc);
QString remoteDebuggerHarnessSrc = Utils::readResourceFileUtf8(":/remote_debugger_harness.html");
remoteDebuggerHarnessSrc = remoteDebuggerHarnessSrc.arg(scriptBody);
targetFrame->setHtml(remoteDebuggerHarnessSrc);
if (autorun) {
targetFrame->evaluateJavaScript("__run()", QString());
}
return true;
}
QString Utils::findScript(const QString& jsFilePath, const QString &libraryPath)
{
QString filePath = jsFilePath;
if (!jsFilePath.isEmpty()) {
QFile jsFile;
// Is file in the PWD?
jsFile.setFileName(QDir::fromNativeSeparators(jsFilePath)); //< Normalise User-provided path
if (!jsFile.exists()) {
// File is not in the PWD. Is it in the lookup directory?
jsFile.setFileName(libraryPath + '/' + QDir::fromNativeSeparators(jsFilePath));
}
return jsFile.fileName();
}
return QString();
}
QString Utils::jsFromScriptFile(const QString& scriptPath, const Encoding& enc)
{
QFile jsFile(scriptPath);
if (jsFile.exists() && jsFile.open(QFile::ReadOnly)) {
QString scriptBody = enc.decode(jsFile.readAll());
// Remove CLI script heading
if (scriptBody.startsWith("#!") && !jsFile.fileName().endsWith(COFFEE_SCRIPT_EXTENSION)) {
scriptBody.prepend("//");
}
if (jsFile.fileName().endsWith(COFFEE_SCRIPT_EXTENSION)) {
QVariant result = Utils::coffee2js(scriptBody);
if (result.toStringList().at(0) == "false") {
return QString();
} else {
scriptBody = result.toStringList().at(1);
}
}
jsFile.close();
return scriptBody;
} else {
return QString();
}
}
void
Utils::cleanupFromDebug()
{
if (m_tempHarness) {
// Will erase the temp file on disk
delete m_tempHarness;
m_tempHarness = 0;
}
if (m_tempWrapper) {
delete m_tempWrapper;
m_tempWrapper = 0;
}
}
QString Utils::readResourceFileUtf8(const QString &resourceFilePath)
{
QFile f(resourceFilePath);
f.open(QFile::ReadOnly); //< It's OK to assume this succeed. If it doesn't, we have a bigger problem.
return QString::fromUtf8(f.readAll());
}
// private:
Utils::Utils()
{
// Nothing to do here
}
<|endoftext|> |
<commit_before>#ifndef window_hh_INCLUDED
#define window_hh_INCLUDED
#include "editor.hh"
#include "display_buffer.hh"
#include "completion.hh"
#include "highlighter.hh"
#include "highlighter.hh"
#include "hook_manager.hh"
#include "option_manager.hh"
namespace Kakoune
{
// A Window is an editing view onto a Buffer
//
// The Window class is an interactive Editor adding display functionalities
// to the editing ones already provided by the Editor class.
// Display can be customized through the use of highlighters handled by
// the window's HighlighterGroup
class Window : public Editor, public OptionManagerWatcher
{
public:
Window(Buffer& buffer);
~Window();
const DisplayCoord& position() const { return m_position; }
void set_position(const DisplayCoord& position);
const DisplayCoord& dimensions() const { return m_dimensions; }
void set_dimensions(const DisplayCoord& dimensions);
const DisplayBuffer& display_buffer() const { return m_display_buffer; }
void center_selection();
void update_display_buffer();
DisplayCoord display_position(const BufferIterator& it);
HighlighterGroup& highlighters() { return m_highlighters; }
OptionManager& options() { return m_options; }
const OptionManager& options() const { return m_options; }
HookManager& hooks() { return m_hooks; }
const HookManager& hooks() const { return m_hooks; }
size_t timestamp() const { return m_timestamp; }
void forget_timestamp() { m_timestamp = -1; }
private:
Window(const Window&) = delete;
void on_option_changed(const Option& option) override;
void scroll_to_keep_cursor_visible_ifn();
DisplayCoord m_position;
DisplayCoord m_dimensions;
DisplayBuffer m_display_buffer;
HighlighterGroup m_highlighters;
HighlighterGroup m_builtin_highlighters;
HookManager m_hooks;
OptionManager m_options;
size_t m_timestamp = -1;
};
}
#endif // window_hh_INCLUDED
<commit_msg>Window: move highlighters after options so that they can reference it<commit_after>#ifndef window_hh_INCLUDED
#define window_hh_INCLUDED
#include "editor.hh"
#include "display_buffer.hh"
#include "completion.hh"
#include "highlighter.hh"
#include "highlighter.hh"
#include "hook_manager.hh"
#include "option_manager.hh"
namespace Kakoune
{
// A Window is an editing view onto a Buffer
//
// The Window class is an interactive Editor adding display functionalities
// to the editing ones already provided by the Editor class.
// Display can be customized through the use of highlighters handled by
// the window's HighlighterGroup
class Window : public Editor, public OptionManagerWatcher
{
public:
Window(Buffer& buffer);
~Window();
const DisplayCoord& position() const { return m_position; }
void set_position(const DisplayCoord& position);
const DisplayCoord& dimensions() const { return m_dimensions; }
void set_dimensions(const DisplayCoord& dimensions);
const DisplayBuffer& display_buffer() const { return m_display_buffer; }
void center_selection();
void update_display_buffer();
DisplayCoord display_position(const BufferIterator& it);
HighlighterGroup& highlighters() { return m_highlighters; }
OptionManager& options() { return m_options; }
const OptionManager& options() const { return m_options; }
HookManager& hooks() { return m_hooks; }
const HookManager& hooks() const { return m_hooks; }
size_t timestamp() const { return m_timestamp; }
void forget_timestamp() { m_timestamp = -1; }
private:
Window(const Window&) = delete;
void on_option_changed(const Option& option) override;
void scroll_to_keep_cursor_visible_ifn();
DisplayCoord m_position;
DisplayCoord m_dimensions;
DisplayBuffer m_display_buffer;
HookManager m_hooks;
OptionManager m_options;
HighlighterGroup m_highlighters;
HighlighterGroup m_builtin_highlighters;
size_t m_timestamp = -1;
};
}
#endif // window_hh_INCLUDED
<|endoftext|> |
<commit_before>/**********************************
** Tsunagari Tile Engine **
** world.cpp **
** Copyright 2014 PariahSoft LLC **
**********************************/
// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********
#include <iostream>
#include "../TsunagariC/src/log.h"
#include "areas/grove01.cpp"
#include "world.h"
static TestingDataWorld globalTestingDataWorld;
DataWorld& DataWorld::instance()
{
return globalTestingDataWorld;
}
TestingDataWorld::TestingDataWorld()
{
areas["grove01"] = DataAreaRef(new grove01());
}
TestingDataWorld::~TestingDataWorld()
{
}
bool TestingDataWorld::init()
{
Log::info("TestingDataWorld", "Hello!");
return true;
}
<commit_msg>world: use full TMX filename and path for DataAreas index<commit_after>/**********************************
** Tsunagari Tile Engine **
** world.cpp **
** Copyright 2014 PariahSoft LLC **
**********************************/
// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********
#include <iostream>
#include "../TsunagariC/src/log.h"
#include "areas/grove01.cpp"
#include "world.h"
static TestingDataWorld globalTestingDataWorld;
DataWorld& DataWorld::instance()
{
return globalTestingDataWorld;
}
TestingDataWorld::TestingDataWorld()
{
areas["areas/grove01.tmx"] = DataAreaRef(new grove01());
}
TestingDataWorld::~TestingDataWorld()
{
}
bool TestingDataWorld::init()
{
Log::info("TestingDataWorld", "Hello!");
return true;
}
<|endoftext|> |
<commit_before>/*
* Jamoma DSP Soundfile Recorder
* Copyright © 2010, Tim Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTSoundfileRecorder.h"
#define thisTTClass TTSoundfileRecorder
#define thisTTClassName "soundfile.recorder"
#define thisTTClassTags "audio, soundfile, record"
TT_AUDIO_CONSTRUCTOR,
mFilePath(kTTSymEmpty),
mFormat(kTTSymEmpty),
mSoundFile(NULL),
mRecord(false),
mNumChannels(0),
mNumBufferFrames(0),
mLength(0),
mLengthInSamples(0),
mTimedRecord(false)
{
addAttribute( FilePath, kTypeSymbol);
addAttribute( Format, kTypeSymbol);
addAttributeWithSetter( Record, kTypeBoolean);
addAttribute( NumChannels, kTypeUInt16);
addAttribute( Length, kTypeFloat64);
addAttributeProperty( NumChannels, readOnly, kTTBoolYes);
setProcessMethod(processAudio);
}
TTSoundfileRecorder::~TTSoundfileRecorder()
{
setAttributeValue(TT("record"), kTTBoolNo);
if (mSoundFile)
sf_close(mSoundFile);
}
/*TTErr TTSoundfileRecorder::setLength(const TTValue& newValue)
{
mLength = newValue;
return kTTErrNone;
}*/
TTErr TTSoundfileRecorder::setRecord(const TTValue& newValue)
{
TTBoolean newRecordState = newValue;
TTErr err = kTTErrNone;
if (mRecord != newRecordState) {
mRecord = newRecordState;
if (mRecord) { // start recording
mLengthInSamples = mLength * sr * 0.001; // reset the Sample counter
if (mLengthInSamples > 0)
mTimedRecord = true;
else
mTimedRecord = false;
mNumChannels = 0; // set to zero so that the process method will set the num channels and trigger an open
}
else { // stop recording -- close the file
if (mSoundFile)
sf_close(mSoundFile);
mSoundFile = NULL;
}
}
return err;
}
// "FLAC-24bit" -> SF_FORMAT_FLAC | SF_FORMAT_PCM_24
int TTSoundfileRecorder::translateFormatFromName(TTSymbolPtr name)
{
int format = 0;
char cname[64];
char* s;
if (name)
strncpy(cname, name->getCString(), 64);
else
strncpy(cname, "CAF", 64);
s = strrchr(cname, '-'); // look for subtype
if (s) {
*s = 0;
s++;
if (s) {
if (strstr(s, "16bit"))
format |= SF_FORMAT_PCM_16;
else if (strstr(s, "24bit"))
format |= SF_FORMAT_PCM_24;
else if (strstr(s, "32bit"))
format |= SF_FORMAT_PCM_32;
else
format |= SF_FORMAT_PCM_24;
}
}
else { // no subtype, set default
format |= SF_FORMAT_PCM_24;
}
// now look at the primary type
if (strstr(cname, "FLAC"))
format |= SF_FORMAT_FLAC;
else if (strstr(cname, "AIFF"))
format |= SF_FORMAT_AIFF;
else if (strstr(cname, "WAV"))
format |= SF_FORMAT_WAV;
else if (strstr(cname, "Matlab"))
format |= SF_FORMAT_MAT5;
else
format |= SF_FORMAT_CAF;
return format;
}
TTErr TTSoundfileRecorder::openFile()
{
memset(&mSoundFileInfo, 0, sizeof(mSoundFileInfo));
mSoundFileInfo.channels = mNumChannels;
mSoundFileInfo.format = translateFormatFromName(mFormat);
mSoundFileInfo.samplerate = sr;
mSoundFile = sf_open(mFilePath->getCString(), SFM_WRITE, &mSoundFileInfo);
if (!mSoundFile) {
return kTTErrGeneric;
}
return kTTErrNone;
}
TTErr TTSoundfileRecorder::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTUInt16 channelCount = in.getNumChannelsAsInt();
TTUInt16 numFrames = in.getVectorSizeAsInt();
TTBoolean bufferNeedsResize = NO;
TTUInt16 n;
TTSampleValuePtr inSample;
sf_count_t numSamplesWritten;
if (!mRecord) // not recording
return kTTErrNone;
if (!mNumChannels) { // this is the first frame to record, we need to set up the file
mNumChannels = channelCount;
bufferNeedsResize = YES;
openFile();
}
if (mNumBufferFrames != numFrames) {
mNumBufferFrames = numFrames;
bufferNeedsResize = YES;
}
if (bufferNeedsResize)
mBuffer.resize(mNumBufferFrames * mNumChannels);
for (TTUInt16 channel=0; channel<channelCount; channel++) {
inSample = in.mSampleVectors[channel];
for (n=0; n<numFrames; n++)
mBuffer[n * channelCount + channel] = inSample[n];
}
numSamplesWritten = sf_write_double(mSoundFile, &mBuffer[0], numFrames*channelCount);
if (mTimedRecord){
mLengthInSamples = mLengthInSamples - numFrames; // decreasing the samplecounter by a vs if we want to record with a duration
if (mLengthInSamples <= 0) //TODO: we might want to chop of the samples that were recorded too long
return setRecord(0);
}
return kTTErrNone;
}
<commit_msg>since we need to have a pulling module after the soundfile recorder, it makes sense to have also actual audio data available at the output of the recorder<commit_after>/*
* Jamoma DSP Soundfile Recorder
* Copyright © 2010, Tim Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTSoundfileRecorder.h"
#define thisTTClass TTSoundfileRecorder
#define thisTTClassName "soundfile.recorder"
#define thisTTClassTags "audio, soundfile, record"
TT_AUDIO_CONSTRUCTOR,
mFilePath(kTTSymEmpty),
mFormat(kTTSymEmpty),
mSoundFile(NULL),
mRecord(false),
mNumChannels(0),
mNumBufferFrames(0),
mLength(0),
mLengthInSamples(0),
mTimedRecord(false)
{
addAttribute( FilePath, kTypeSymbol);
addAttribute( Format, kTypeSymbol);
addAttributeWithSetter( Record, kTypeBoolean);
addAttribute( NumChannels, kTypeUInt16);
addAttribute( Length, kTypeFloat64);
addAttributeProperty( NumChannels, readOnly, kTTBoolYes);
setProcessMethod(processAudio);
}
TTSoundfileRecorder::~TTSoundfileRecorder()
{
setAttributeValue(TT("record"), kTTBoolNo);
if (mSoundFile)
sf_close(mSoundFile);
}
/*TTErr TTSoundfileRecorder::setLength(const TTValue& newValue)
{
mLength = newValue;
return kTTErrNone;
}*/
TTErr TTSoundfileRecorder::setRecord(const TTValue& newValue)
{
TTBoolean newRecordState = newValue;
TTErr err = kTTErrNone;
if (mRecord != newRecordState) {
mRecord = newRecordState;
if (mRecord) { // start recording
mLengthInSamples = mLength * sr * 0.001; // reset the Sample counter
if (mLengthInSamples > 0)
mTimedRecord = true;
else
mTimedRecord = false;
mNumChannels = 0; // set to zero so that the process method will set the num channels and trigger an open
}
else { // stop recording -- close the file
if (mSoundFile)
sf_close(mSoundFile);
mSoundFile = NULL;
}
}
return err;
}
// "FLAC-24bit" -> SF_FORMAT_FLAC | SF_FORMAT_PCM_24
int TTSoundfileRecorder::translateFormatFromName(TTSymbolPtr name)
{
int format = 0;
char cname[64];
char* s;
if (name)
strncpy(cname, name->getCString(), 64);
else
strncpy(cname, "CAF", 64);
s = strrchr(cname, '-'); // look for subtype
if (s) {
*s = 0;
s++;
if (s) {
if (strstr(s, "16bit"))
format |= SF_FORMAT_PCM_16;
else if (strstr(s, "24bit"))
format |= SF_FORMAT_PCM_24;
else if (strstr(s, "32bit"))
format |= SF_FORMAT_PCM_32;
else
format |= SF_FORMAT_PCM_24;
}
}
else { // no subtype, set default
format |= SF_FORMAT_PCM_24;
}
// now look at the primary type
if (strstr(cname, "FLAC"))
format |= SF_FORMAT_FLAC;
else if (strstr(cname, "AIFF"))
format |= SF_FORMAT_AIFF;
else if (strstr(cname, "WAV"))
format |= SF_FORMAT_WAV;
else if (strstr(cname, "Matlab"))
format |= SF_FORMAT_MAT5;
else
format |= SF_FORMAT_CAF;
return format;
}
TTErr TTSoundfileRecorder::openFile()
{
memset(&mSoundFileInfo, 0, sizeof(mSoundFileInfo));
mSoundFileInfo.channels = mNumChannels;
mSoundFileInfo.format = translateFormatFromName(mFormat);
mSoundFileInfo.samplerate = sr;
mSoundFile = sf_open(mFilePath->getCString(), SFM_WRITE, &mSoundFileInfo);
if (!mSoundFile) {
return kTTErrGeneric;
}
return kTTErrNone;
}
TTErr TTSoundfileRecorder::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& out = outputs->getSignal(0);
TTAudioSignal& in = inputs->getSignal(0);
TTSampleValuePtr outSample;
TTUInt16 channelCount = in.getNumChannelsAsInt();
TTUInt16 numFrames = in.getVectorSizeAsInt();
TTBoolean bufferNeedsResize = NO;
TTUInt16 n, channel;
TTSampleValuePtr inSample;
sf_count_t numSamplesWritten;
if (!mRecord){ // not recording, just bypassing audio and return
for (channel=0; channel<channelCount; channel++) {
inSample = in.mSampleVectors[channel];
outSample = out.mSampleVectors[channel]; // sending audio out
for (n=0; n<numFrames; n++)
outSample[n] = inSample[n]; // sending audio out
}
return kTTErrNone;
}
if (!mNumChannels) { // this is the first frame to record, we need to set up the file
mNumChannels = channelCount;
bufferNeedsResize = YES;
openFile();
}
if (mNumBufferFrames != numFrames) {
mNumBufferFrames = numFrames;
bufferNeedsResize = YES;
}
if (bufferNeedsResize)
mBuffer.resize(mNumBufferFrames * mNumChannels);
for (channel=0; channel<channelCount; channel++) {
inSample = in.mSampleVectors[channel];
outSample = out.mSampleVectors[channel]; // sending audio out
for (n=0; n<numFrames; n++){
mBuffer[n * channelCount + channel] = inSample[n]; //sending audio to recording buffer
outSample[n] = inSample[n]; // sending audio out
}
}
numSamplesWritten = sf_write_double(mSoundFile, &mBuffer[0], numFrames*channelCount);
if (mTimedRecord){
mLengthInSamples = mLengthInSamples - numFrames; // decreasing the samplecounter by a vs if we want to record with a duration
if (mLengthInSamples <= 0) //TODO: we might want to chop of the samples that were recorded too long
return setRecord(0);
}
return kTTErrNone;
}
<|endoftext|> |
<commit_before>/*
************************************************************************
* HardwareSerial.cpp
*
* Arduino core files for MSP430
* Copyright (c) 2012 Robert Wessels. All right reserved.
*
*
***********************************************************************
Derived from:
HardwareSerial.cpp - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 23 November 2006 by David A. Mellis
Modified 28 September 2010 by Mark Sproul
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Energia.h"
#include "wiring_private.h"
#if defined(__MSP430_HAS_USCI__)
#include "HardwareSerial.h"
HardwareSerial *SerialPtr;
/**
* Receive Data (RXD) at P1.1
*/
#define RXD BIT1
/**
* Receive Data (TXD) at P1.2
*/
#define TXD BIT2
#define SERIAL_BUFFER_SIZE 16
struct ring_buffer
{
unsigned char buffer[SERIAL_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
ring_buffer rx_buffer = { { 0 }, 0, 0 };
ring_buffer tx_buffer = { { 0 }, 0, 0 };
inline void store_char(unsigned char c, ring_buffer *buffer)
{
unsigned int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
// Constructors ////////////////////////////////////////////////////////////////
HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer)
{
_rx_buffer = rx_buffer;
_tx_buffer = tx_buffer;
}
// Public Methods //////////////////////////////////////////////////////////////
#define SMCLK 1000000
void HardwareSerial::begin(unsigned long baud)
{
unsigned int divider;
unsigned char mod, oversampling;
if (SMCLK/baud>=48) { // requires SMCLK for oversampling
oversampling = 1;
}
else {
oversampling= 0;
}
divider=(SMCLK<<4)/baud;
if(!oversampling) {
mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3)
divider >>=4;
} else {
mod = ((divider&0xf8)+0x8)&0xf0; // UCBRFx (bit 4-7)
divider>>=8;
}
SerialPtr = this;
P1SEL = RXD + TXD;
P1SEL2 = RXD + TXD;
UCA0CTL1 = UCSWRST;
UCA0CTL1 = UCSSEL_2; //SMCLK
UCA0CTL0 = 0;
UCA0ABCTL = 0;
UCA0BR0 = divider;
UCA0BR1 = divider>>8;
UCA0MCTL = (oversampling ? UCOS16:0) | mod;
UCA0CTL1 &= ~UCSWRST;
UC0IE = UCA0RXIE;
}
void HardwareSerial::end()
{
// wait for transmission of outgoing data
while (_tx_buffer->head != _tx_buffer->tail);
_rx_buffer->head = _rx_buffer->tail;
}
int HardwareSerial::available(void)
{
return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE;
}
int HardwareSerial::peek(void)
{
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
return _rx_buffer->buffer[_rx_buffer->tail];
}
}
int HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
_rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE;
return c;
}
}
void HardwareSerial::flush()
{
while (_tx_buffer->head != _tx_buffer->tail);
}
size_t HardwareSerial::write(uint8_t c)
{
unsigned int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE;
// If the output buffer is full, there's nothing for it other than to
// wait for the interrupt handler to empty it a bit
// ???: return 0 here instead?
while (i == _tx_buffer->tail);
_tx_buffer->buffer[_tx_buffer->head] = c;
_tx_buffer->head = i;
IE2 |= UCA0TXIE;
return 1;
}
void HardwareSerial::ProcessRXInt(void)
{
unsigned char c = UCA0RXBUF;
store_char(c, &rx_buffer);
}
interrupt(USCIAB0RX_VECTOR) HardwareSerial::USCI0RX_ISR(void)
{
SerialPtr->ProcessRXInt();
}
void HardwareSerial::ProcessTXInt(void)
{
if (tx_buffer.head == tx_buffer.tail) {
// Buffer empty, so disable interrupts
IE2 &= ~UCA0TXIE;
return;
}
unsigned char c = tx_buffer.buffer[tx_buffer.tail];
tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
UCA0TXBUF = c;
}
interrupt(USCIAB0TX_VECTOR) HardwareSerial::USCI0TX_ISR(void)
{
SerialPtr->ProcessTXInt();
}
// Preinstantiate Objects //////////////////////////////////////////////////////
HardwareSerial Serial(&rx_buffer, &tx_buffer);
#endif
<commit_msg>Fix hardcoded SMCLK<commit_after>/*
************************************************************************
* HardwareSerial.cpp
*
* Arduino core files for MSP430
* Copyright (c) 2012 Robert Wessels. All right reserved.
*
*
***********************************************************************
Derived from:
HardwareSerial.cpp - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 23 November 2006 by David A. Mellis
Modified 28 September 2010 by Mark Sproul
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Energia.h"
#include "wiring_private.h"
#if defined(__MSP430_HAS_USCI__)
#include "HardwareSerial.h"
HardwareSerial *SerialPtr;
/**
* Receive Data (RXD) at P1.1
*/
#define RXD BIT1
/**
* Receive Data (TXD) at P1.2
*/
#define TXD BIT2
#define SERIAL_BUFFER_SIZE 16
struct ring_buffer
{
unsigned char buffer[SERIAL_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
ring_buffer rx_buffer = { { 0 }, 0, 0 };
ring_buffer tx_buffer = { { 0 }, 0, 0 };
inline void store_char(unsigned char c, ring_buffer *buffer)
{
unsigned int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
// Constructors ////////////////////////////////////////////////////////////////
HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer)
{
_rx_buffer = rx_buffer;
_tx_buffer = tx_buffer;
}
// Public Methods //////////////////////////////////////////////////////////////
#define SMCLK F_CPU //SMCLK = F_CPU for now
void HardwareSerial::begin(unsigned long baud)
{
unsigned int divider;
unsigned char mod, oversampling;
if (SMCLK/baud>=48) { // requires SMCLK for oversampling
oversampling = 1;
}
else {
oversampling= 0;
}
divider=(SMCLK<<4)/baud;
if(!oversampling) {
mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3)
divider >>=4;
} else {
mod = ((divider&0xf8)+0x8)&0xf0; // UCBRFx (bit 4-7)
divider>>=8;
}
SerialPtr = this;
P1SEL = RXD + TXD;
P1SEL2 = RXD + TXD;
UCA0CTL1 = UCSWRST;
UCA0CTL1 = UCSSEL_2; //SMCLK
UCA0CTL0 = 0;
UCA0ABCTL = 0;
UCA0BR0 = divider;
UCA0BR1 = divider>>8;
UCA0MCTL = (oversampling ? UCOS16:0) | mod;
UCA0CTL1 &= ~UCSWRST;
UC0IE = UCA0RXIE;
}
void HardwareSerial::end()
{
// wait for transmission of outgoing data
while (_tx_buffer->head != _tx_buffer->tail);
_rx_buffer->head = _rx_buffer->tail;
}
int HardwareSerial::available(void)
{
return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE;
}
int HardwareSerial::peek(void)
{
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
return _rx_buffer->buffer[_rx_buffer->tail];
}
}
int HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
_rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE;
return c;
}
}
void HardwareSerial::flush()
{
while (_tx_buffer->head != _tx_buffer->tail);
}
size_t HardwareSerial::write(uint8_t c)
{
unsigned int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE;
// If the output buffer is full, there's nothing for it other than to
// wait for the interrupt handler to empty it a bit
// ???: return 0 here instead?
while (i == _tx_buffer->tail);
_tx_buffer->buffer[_tx_buffer->head] = c;
_tx_buffer->head = i;
IE2 |= UCA0TXIE;
return 1;
}
void HardwareSerial::ProcessRXInt(void)
{
unsigned char c = UCA0RXBUF;
store_char(c, &rx_buffer);
}
interrupt(USCIAB0RX_VECTOR) HardwareSerial::USCI0RX_ISR(void)
{
SerialPtr->ProcessRXInt();
}
void HardwareSerial::ProcessTXInt(void)
{
if (tx_buffer.head == tx_buffer.tail) {
// Buffer empty, so disable interrupts
IE2 &= ~UCA0TXIE;
return;
}
unsigned char c = tx_buffer.buffer[tx_buffer.tail];
tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
UCA0TXBUF = c;
}
interrupt(USCIAB0TX_VECTOR) HardwareSerial::USCI0TX_ISR(void)
{
SerialPtr->ProcessTXInt();
}
// Preinstantiate Objects //////////////////////////////////////////////////////
HardwareSerial Serial(&rx_buffer, &tx_buffer);
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_utils/platform/semaphore.hpp"
#include "iceoryx_utils/platform/time.hpp"
#include <chrono>
#include <cstdarg>
#include <cstdlib>
#include <iostream>
#include <thread>
static void deleteValue(std::atomic<int>*& value) noexcept
{
if (value != nullptr)
{
delete value;
value = nullptr;
}
}
iox_sem_t::iox_sem_t() noexcept
: m_value{new std::atomic<int>}
{
}
iox_sem_t::iox_sem_t(iox_sem_t&& rhs) noexcept
{
*this = std::move(rhs);
}
iox_sem_t::~iox_sem_t()
{
deleteValue(m_value);
}
iox_sem_t& iox_sem_t::operator=(iox_sem_t&& rhs) noexcept
{
if (this != &rhs)
{
deleteValue(m_value);
m_handle = rhs.m_handle;
m_hasPosixHandle = rhs.m_hasPosixHandle;
m_value = rhs.m_value;
rhs.m_value = nullptr;
}
return *this;
}
int iox_sem_getvalue(iox_sem_t* sem, int* sval)
{
*sval = sem->m_value->load(std::memory_order_relaxed);
return 0;
}
int iox_sem_post(iox_sem_t* sem)
{
int retVal{0};
if (sem->m_hasPosixHandle)
{
retVal = sem_post(sem->m_handle.posix);
if (retVal == 0)
{
(*sem->m_value)++;
}
}
else
{
// dispatch semaphore always succeed
dispatch_semaphore_signal(sem->m_handle.dispatch);
(*sem->m_value)++;
}
return retVal;
}
int iox_sem_wait(iox_sem_t* sem)
{
int retVal{0};
if (sem->m_hasPosixHandle)
{
retVal = sem_wait(sem->m_handle.posix);
if (retVal == 0)
{
(*sem->m_value)--;
}
}
else
{
// dispatch semaphore always succeed
dispatch_semaphore_wait(sem->m_handle.dispatch, DISPATCH_TIME_FOREVER);
(*sem->m_value)--;
}
return retVal;
}
int iox_sem_trywait(iox_sem_t* sem)
{
int retVal{0};
if (sem->m_hasPosixHandle)
{
retVal = sem_trywait(sem->m_handle.posix);
if (retVal == 0)
{
(*sem->m_value)--;
}
}
else
{
if (dispatch_semaphore_wait(sem->m_handle.dispatch, 0) != 0)
{
errno = EAGAIN;
retVal = -1;
}
else
{
(*sem->m_value)--;
}
}
return retVal;
}
int iox_sem_timedwait(iox_sem_t* sem, const struct timespec* abs_timeout)
{
struct timeval tv;
gettimeofday(&tv, nullptr);
static constexpr int64_t NANOSECONDS_PER_SECOND = 1000000000;
static constexpr int64_t NANOSECONDS_PER_MICROSECOND = 1000;
int64_t timeoutInNanoSeconds = std::max(0ll,
(abs_timeout->tv_sec - tv.tv_sec) * NANOSECONDS_PER_SECOND
+ abs_timeout->tv_nsec - tv.tv_usec * NANOSECONDS_PER_MICROSECOND);
if (sem->m_hasPosixHandle)
{
int tryWaitCall = sem_trywait(sem->m_handle.posix);
if (tryWaitCall == -1 && errno != EAGAIN)
{
return -1;
}
else if (tryWaitCall == -1 && errno == EAGAIN && timeoutInNanoSeconds == 0)
{
errno = ETIMEDOUT;
return -1;
}
else if (tryWaitCall == 0)
{
(*sem->m_value)--;
return 0;
}
std::this_thread::sleep_for(std::chrono::nanoseconds(timeoutInNanoSeconds));
tryWaitCall = sem_trywait(sem->m_handle.posix);
if (tryWaitCall == -1 && errno == EAGAIN)
{
errno = ETIMEDOUT;
return -1;
}
else if (tryWaitCall == -1 && errno != EAGAIN)
{
return -1;
}
else if (tryWaitCall == 0)
{
(*sem->m_value)--;
return 0;
}
}
else
{
dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeoutInNanoSeconds);
if (dispatch_semaphore_wait(sem->m_handle.dispatch, timeout) != 0)
{
errno = ETIMEDOUT;
return -1;
}
else
{
(*sem->m_value)--;
return 0;
}
}
return -1;
}
int iox_sem_close(iox_sem_t* sem)
{
// will only be called by named semaphores which are in our case
// posix semaphores
int retVal = sem_close(sem->m_handle.posix);
delete sem;
return retVal;
}
int iox_sem_destroy(iox_sem_t* sem)
{
// will only be called by unnamed semaphores which are in our
// case dispatch semaphores
dispatch_release(sem->m_handle.dispatch);
return 0;
}
int iox_sem_init(iox_sem_t* sem, int pshared, unsigned int value)
{
sem->m_hasPosixHandle = false;
sem->m_handle.dispatch = dispatch_semaphore_create(value);
sem->m_value->store(value, std::memory_order_relaxed);
if (sem->m_handle.dispatch == nullptr)
{
delete sem;
return -1;
}
return 0;
}
int iox_sem_unlink(const char* name)
{
return sem_unlink(name);
}
iox_sem_t* iox_sem_open_impl(const char* name, int oflag, ...)
{
iox_sem_t* sem = new iox_sem_t;
if (oflag & (O_CREAT | O_EXCL))
{
va_list va;
va_start(va, oflag);
mode_t mode = va_arg(va, mode_t);
unsigned int value = va_arg(va, unsigned int);
va_end(va);
sem->m_handle.posix = sem_open(name, oflag, mode, value);
sem->m_value->store(value, std::memory_order_relaxed);
}
else
{
sem->m_handle.posix = sem_open(name, oflag);
}
if (sem->m_handle.posix == SEM_FAILED)
{
delete sem;
return reinterpret_cast<iox_sem_t*>(SEM_FAILED);
}
return sem;
}
<commit_msg>iox-#32 get value atomic of semaphore has relaxed memory order<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_utils/platform/semaphore.hpp"
#include "iceoryx_utils/platform/time.hpp"
#include <chrono>
#include <cstdarg>
#include <cstdlib>
#include <iostream>
#include <thread>
static void deleteValue(std::atomic<int>*& value) noexcept
{
if (value != nullptr)
{
delete value;
value = nullptr;
}
}
iox_sem_t::iox_sem_t() noexcept
: m_value{new std::atomic<int>}
{
}
iox_sem_t::iox_sem_t(iox_sem_t&& rhs) noexcept
{
*this = std::move(rhs);
}
iox_sem_t::~iox_sem_t()
{
deleteValue(m_value);
}
iox_sem_t& iox_sem_t::operator=(iox_sem_t&& rhs) noexcept
{
if (this != &rhs)
{
deleteValue(m_value);
m_handle = rhs.m_handle;
m_hasPosixHandle = rhs.m_hasPosixHandle;
m_value = rhs.m_value;
rhs.m_value = nullptr;
}
return *this;
}
int iox_sem_getvalue(iox_sem_t* sem, int* sval)
{
*sval = sem->m_value->load(std::memory_order_relaxed);
return 0;
}
int iox_sem_post(iox_sem_t* sem)
{
int retVal{0};
if (sem->m_hasPosixHandle)
{
retVal = sem_post(sem->m_handle.posix);
if (retVal == 0)
{
sem->m_value->fetch_add(1, std::memory_order_relaxed);
}
}
else
{
// dispatch semaphore always succeed
dispatch_semaphore_signal(sem->m_handle.dispatch);
sem->m_value->fetch_add(1, std::memory_order_relaxed);
}
return retVal;
}
int iox_sem_wait(iox_sem_t* sem)
{
int retVal{0};
if (sem->m_hasPosixHandle)
{
retVal = sem_wait(sem->m_handle.posix);
if (retVal == 0)
{
sem->m_value->fetch_sub(1, std::memory_order_relaxed);
}
}
else
{
// dispatch semaphore always succeed
dispatch_semaphore_wait(sem->m_handle.dispatch, DISPATCH_TIME_FOREVER);
sem->m_value->fetch_sub(1, std::memory_order_relaxed);
}
return retVal;
}
int iox_sem_trywait(iox_sem_t* sem)
{
int retVal{0};
if (sem->m_hasPosixHandle)
{
retVal = sem_trywait(sem->m_handle.posix);
if (retVal == 0)
{
sem->m_value->fetch_sub(1, std::memory_order_relaxed);
}
}
else
{
if (dispatch_semaphore_wait(sem->m_handle.dispatch, 0) != 0)
{
errno = EAGAIN;
retVal = -1;
}
else
{
sem->m_value->fetch_sub(1, std::memory_order_relaxed);
}
}
return retVal;
}
int iox_sem_timedwait(iox_sem_t* sem, const struct timespec* abs_timeout)
{
struct timeval tv;
gettimeofday(&tv, nullptr);
static constexpr int64_t NANOSECONDS_PER_SECOND = 1000000000;
static constexpr int64_t NANOSECONDS_PER_MICROSECOND = 1000;
int64_t timeoutInNanoSeconds = std::max(0ll,
(abs_timeout->tv_sec - tv.tv_sec) * NANOSECONDS_PER_SECOND
+ abs_timeout->tv_nsec - tv.tv_usec * NANOSECONDS_PER_MICROSECOND);
if (sem->m_hasPosixHandle)
{
int tryWaitCall = sem_trywait(sem->m_handle.posix);
if (tryWaitCall == -1 && errno != EAGAIN)
{
return -1;
}
else if (tryWaitCall == -1 && errno == EAGAIN && timeoutInNanoSeconds == 0)
{
errno = ETIMEDOUT;
return -1;
}
else if (tryWaitCall == 0)
{
sem->m_value->fetch_sub(1, std::memory_order_relaxed);
return 0;
}
std::this_thread::sleep_for(std::chrono::nanoseconds(timeoutInNanoSeconds));
tryWaitCall = sem_trywait(sem->m_handle.posix);
if (tryWaitCall == -1 && errno == EAGAIN)
{
errno = ETIMEDOUT;
return -1;
}
else if (tryWaitCall == -1 && errno != EAGAIN)
{
return -1;
}
else if (tryWaitCall == 0)
{
sem->m_value->fetch_sub(1, std::memory_order_relaxed);
return 0;
}
}
else
{
dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeoutInNanoSeconds);
if (dispatch_semaphore_wait(sem->m_handle.dispatch, timeout) != 0)
{
errno = ETIMEDOUT;
return -1;
}
else
{
sem->m_value->fetch_sub(1, std::memory_order_relaxed);
return 0;
}
}
return -1;
}
int iox_sem_close(iox_sem_t* sem)
{
// will only be called by named semaphores which are in our case
// posix semaphores
int retVal = sem_close(sem->m_handle.posix);
delete sem;
return retVal;
}
int iox_sem_destroy(iox_sem_t* sem)
{
// will only be called by unnamed semaphores which are in our
// case dispatch semaphores
dispatch_release(sem->m_handle.dispatch);
return 0;
}
int iox_sem_init(iox_sem_t* sem, int pshared, unsigned int value)
{
sem->m_hasPosixHandle = false;
sem->m_handle.dispatch = dispatch_semaphore_create(value);
sem->m_value->store(value, std::memory_order_relaxed);
if (sem->m_handle.dispatch == nullptr)
{
delete sem;
return -1;
}
return 0;
}
int iox_sem_unlink(const char* name)
{
return sem_unlink(name);
}
iox_sem_t* iox_sem_open_impl(const char* name, int oflag, ...)
{
iox_sem_t* sem = new iox_sem_t;
if (oflag & (O_CREAT | O_EXCL))
{
va_list va;
va_start(va, oflag);
mode_t mode = va_arg(va, mode_t);
unsigned int value = va_arg(va, unsigned int);
va_end(va);
sem->m_handle.posix = sem_open(name, oflag, mode, value);
sem->m_value->store(value, std::memory_order_relaxed);
}
else
{
sem->m_handle.posix = sem_open(name, oflag);
}
if (sem->m_handle.posix == SEM_FAILED)
{
delete sem;
return reinterpret_cast<iox_sem_t*>(SEM_FAILED);
}
return sem;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "imaging/oskar_get_image_baseline_coords.h"
#include "imaging/oskar_image_evaluate_ranges.h"
#include "utility/oskar_mem_init.h"
#include "utility/oskar_mem_type_check.h"
#include "utility/oskar_mem_get_pointer.h"
#include "utility/oskar_mem_free.h"
#include "utility/oskar_mem_element_size.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
int oskar_get_image_baseline_coords(oskar_Mem* uu, oskar_Mem* vv, oskar_Mem* ww,
const oskar_Mem* vis_uu, const oskar_Mem* vis_vv, const oskar_Mem* vis_ww,
int num_times, int num_baselines, int num_channels,
double freq_start_hz, double freq_inc_hz,int vis_time, double im_freq,
const oskar_SettingsImage* settings)
{
int err = OSKAR_SUCCESS;
int location = OSKAR_LOCATION_CPU;
int num_vis_coords = num_baselines;
// Data ranges for frequency and time synthesis.
int vis_time_range[2];
err = oskar_evaluate_image_data_range(vis_time_range, settings->time_range,
num_times);
if (err) return err;
int vis_chan_range[2];
err = oskar_evaluate_image_data_range(vis_chan_range, settings->channel_range,
num_channels);
if (err) return err;
// Declare temporary pointers into visibility coordinate arrays.
int type = vis_uu->type;
oskar_Mem uu_ptr(type, location, num_baselines, OSKAR_FALSE);
oskar_Mem vv_ptr(type, location, num_baselines, OSKAR_FALSE);
oskar_Mem ww_ptr(type, location, num_baselines, OSKAR_FALSE);
/* ========================================= TIME SNAPSHOTS, FREQ SNAPSHOTS */
if (settings->time_snapshots && settings->channel_snapshots)
{
int coord_offset = vis_time * num_baselines;
size_t element_size = oskar_mem_element_size(type);
printf("coord_offset = %i\n", coord_offset);
memcpy(uu->data, (void*)((char*)vis_uu->data + element_size * coord_offset), element_size * num_baselines);
memcpy(vv->data, (void*)((char*)vis_vv->data + element_size * coord_offset), element_size * num_baselines);
memcpy(ww->data, (void*)((char*)vis_ww->data + element_size * coord_offset), element_size * num_baselines);
}
/* ======================================== TIME SNAPSHOTS, FREQ SYNTHESIS */
else if (settings->time_snapshots && !settings->channel_snapshots)
{
int coord_offset = vis_time * num_baselines;
oskar_mem_get_pointer(&uu_ptr, vis_uu, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&vv_ptr, vis_vv, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&ww_ptr, vis_ww, coord_offset, num_vis_coords, &err);
if (err) return err;
for (int i = 0, c = vis_chan_range[0]; c <= vis_chan_range[1]; ++c)
{
double freq = freq_start_hz + c * freq_inc_hz;
double scaling = freq/im_freq;
for (int b = 0; b < num_baselines; ++b, ++i)
{
if (type == OSKAR_DOUBLE)
{
((double*)uu->data)[i] = ((double*)uu_ptr.data)[b] * scaling;
((double*)vv->data)[i] = ((double*)vv_ptr.data)[b] * scaling;
((double*)ww->data)[i] = ((double*)ww_ptr.data)[b] * scaling;
}
else
{
((float*)uu->data)[i] = ((float*)uu_ptr.data)[b] * scaling;
((float*)vv->data)[i] = ((float*)vv_ptr.data)[b] * scaling;
((float*)ww->data)[i] = ((float*)ww_ptr.data)[b] * scaling;
}
}
}
}
/* ======================================== TIME SYNTHESIS, FREQ SNAPSHOTS */
else if (!settings->time_snapshots && settings->channel_snapshots)
{
for (int i = 0, t = vis_time_range[0]; t <= vis_time_range[1]; ++t)
{
int coord_offset = t * num_baselines;
oskar_mem_get_pointer(&uu_ptr, vis_uu, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&vv_ptr, vis_vv, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&ww_ptr, vis_ww, coord_offset, num_vis_coords, &err);
if (err) return err;
for (int b = 0; b < num_baselines; ++b, ++i)
{
if (type == OSKAR_DOUBLE)
{
((double*)uu->data)[i] = ((double*)uu_ptr.data)[b];
((double*)vv->data)[i] = ((double*)vv_ptr.data)[b];
((double*)ww->data)[i] = ((double*)ww_ptr.data)[b];
}
else
{
((float*)uu->data)[i] = ((float*)uu_ptr.data)[b];
((float*)vv->data)[i] = ((float*)vv_ptr.data)[b];
((float*)ww->data)[i] = ((float*)ww_ptr.data)[b];
}
}
}
}
/* ======================================== TIME SYNTHESIS, FREQ SYNTHESIS */
else
{
for (int i = 0, c = vis_chan_range[0]; c <= vis_chan_range[1]; ++c)
{
double freq = freq_start_hz + c * freq_inc_hz;
double scaling = freq/im_freq;
for (int t = vis_time_range[0]; t <= vis_time_range[1]; ++t)
{
int coord_offset = t * num_baselines;
oskar_mem_get_pointer(&uu_ptr, vis_uu, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&vv_ptr, vis_vv, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&ww_ptr, vis_ww, coord_offset, num_vis_coords, &err);
if (err) return err;
for (int b = 0; b < num_baselines; ++b, ++i)
{
if (type == OSKAR_DOUBLE)
{
((double*)uu->data)[i] = ((double*)uu_ptr.data)[b] * scaling;
((double*)vv->data)[i] = ((double*)vv_ptr.data)[b] * scaling;
((double*)ww->data)[i] = ((double*)ww_ptr.data)[b] * scaling;
}
else
{
((float*)uu->data)[i] = ((float*)uu_ptr.data)[b] * scaling;
((float*)vv->data)[i] = ((float*)vv_ptr.data)[b] * scaling;
((float*)ww->data)[i] = ((float*)ww_ptr.data)[b] * scaling;
}
}
}
}
}
return err;
}
#ifdef __cplusplus
}
#endif
<commit_msg>removed debug printing<commit_after>/*
* Copyright (c) 2012, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "imaging/oskar_get_image_baseline_coords.h"
#include "imaging/oskar_image_evaluate_ranges.h"
#include "utility/oskar_mem_init.h"
#include "utility/oskar_mem_type_check.h"
#include "utility/oskar_mem_get_pointer.h"
#include "utility/oskar_mem_free.h"
#include "utility/oskar_mem_element_size.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
int oskar_get_image_baseline_coords(oskar_Mem* uu, oskar_Mem* vv, oskar_Mem* ww,
const oskar_Mem* vis_uu, const oskar_Mem* vis_vv, const oskar_Mem* vis_ww,
int num_times, int num_baselines, int num_channels,
double freq_start_hz, double freq_inc_hz,int vis_time, double im_freq,
const oskar_SettingsImage* settings)
{
int err = OSKAR_SUCCESS;
int location = OSKAR_LOCATION_CPU;
int num_vis_coords = num_baselines;
// Data ranges for frequency and time synthesis.
int vis_time_range[2];
err = oskar_evaluate_image_data_range(vis_time_range, settings->time_range,
num_times);
if (err) return err;
int vis_chan_range[2];
err = oskar_evaluate_image_data_range(vis_chan_range, settings->channel_range,
num_channels);
if (err) return err;
// Declare temporary pointers into visibility coordinate arrays.
int type = vis_uu->type;
oskar_Mem uu_ptr(type, location, num_baselines, OSKAR_FALSE);
oskar_Mem vv_ptr(type, location, num_baselines, OSKAR_FALSE);
oskar_Mem ww_ptr(type, location, num_baselines, OSKAR_FALSE);
/* ========================================= TIME SNAPSHOTS, FREQ SNAPSHOTS */
if (settings->time_snapshots && settings->channel_snapshots)
{
int coord_offset = vis_time * num_baselines;
size_t element_size = oskar_mem_element_size(type);
memcpy(uu->data, (void*)((char*)vis_uu->data + element_size * coord_offset), element_size * num_baselines);
memcpy(vv->data, (void*)((char*)vis_vv->data + element_size * coord_offset), element_size * num_baselines);
memcpy(ww->data, (void*)((char*)vis_ww->data + element_size * coord_offset), element_size * num_baselines);
}
/* ======================================== TIME SNAPSHOTS, FREQ SYNTHESIS */
else if (settings->time_snapshots && !settings->channel_snapshots)
{
int coord_offset = vis_time * num_baselines;
oskar_mem_get_pointer(&uu_ptr, vis_uu, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&vv_ptr, vis_vv, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&ww_ptr, vis_ww, coord_offset, num_vis_coords, &err);
if (err) return err;
for (int i = 0, c = vis_chan_range[0]; c <= vis_chan_range[1]; ++c)
{
double freq = freq_start_hz + c * freq_inc_hz;
double scaling = freq/im_freq;
for (int b = 0; b < num_baselines; ++b, ++i)
{
if (type == OSKAR_DOUBLE)
{
((double*)uu->data)[i] = ((double*)uu_ptr.data)[b] * scaling;
((double*)vv->data)[i] = ((double*)vv_ptr.data)[b] * scaling;
((double*)ww->data)[i] = ((double*)ww_ptr.data)[b] * scaling;
}
else
{
((float*)uu->data)[i] = ((float*)uu_ptr.data)[b] * scaling;
((float*)vv->data)[i] = ((float*)vv_ptr.data)[b] * scaling;
((float*)ww->data)[i] = ((float*)ww_ptr.data)[b] * scaling;
}
}
}
}
/* ======================================== TIME SYNTHESIS, FREQ SNAPSHOTS */
else if (!settings->time_snapshots && settings->channel_snapshots)
{
for (int i = 0, t = vis_time_range[0]; t <= vis_time_range[1]; ++t)
{
int coord_offset = t * num_baselines;
oskar_mem_get_pointer(&uu_ptr, vis_uu, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&vv_ptr, vis_vv, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&ww_ptr, vis_ww, coord_offset, num_vis_coords, &err);
if (err) return err;
for (int b = 0; b < num_baselines; ++b, ++i)
{
if (type == OSKAR_DOUBLE)
{
((double*)uu->data)[i] = ((double*)uu_ptr.data)[b];
((double*)vv->data)[i] = ((double*)vv_ptr.data)[b];
((double*)ww->data)[i] = ((double*)ww_ptr.data)[b];
}
else
{
((float*)uu->data)[i] = ((float*)uu_ptr.data)[b];
((float*)vv->data)[i] = ((float*)vv_ptr.data)[b];
((float*)ww->data)[i] = ((float*)ww_ptr.data)[b];
}
}
}
}
/* ======================================== TIME SYNTHESIS, FREQ SYNTHESIS */
else
{
for (int i = 0, c = vis_chan_range[0]; c <= vis_chan_range[1]; ++c)
{
double freq = freq_start_hz + c * freq_inc_hz;
double scaling = freq/im_freq;
for (int t = vis_time_range[0]; t <= vis_time_range[1]; ++t)
{
int coord_offset = t * num_baselines;
oskar_mem_get_pointer(&uu_ptr, vis_uu, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&vv_ptr, vis_vv, coord_offset, num_vis_coords, &err);
if (err) return err;
oskar_mem_get_pointer(&ww_ptr, vis_ww, coord_offset, num_vis_coords, &err);
if (err) return err;
for (int b = 0; b < num_baselines; ++b, ++i)
{
if (type == OSKAR_DOUBLE)
{
((double*)uu->data)[i] = ((double*)uu_ptr.data)[b] * scaling;
((double*)vv->data)[i] = ((double*)vv_ptr.data)[b] * scaling;
((double*)ww->data)[i] = ((double*)ww_ptr.data)[b] * scaling;
}
else
{
((float*)uu->data)[i] = ((float*)uu_ptr.data)[b] * scaling;
((float*)vv->data)[i] = ((float*)vv_ptr.data)[b] * scaling;
((float*)ww->data)[i] = ((float*)ww_ptr.data)[b] * scaling;
}
}
}
}
}
return err;
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>#pragma once
#ifndef OPENGM_GRIDSEARCH_LEARNER_HXX
#define OPENGM_GRIDSEARCH_LEARNER_HXX
#include <vector>
#include <opengm/functions/learnablefunction.hxx>
namespace opengm {
namespace learning {
template<class DATASET>
class GridSearchLearner
{
public:
typedef typename DATASET::GMType GMType;
typedef typename DATASET::LossType LossType;
typedef typename GMType::ValueType ValueType;
typedef typename GMType::IndexType IndexType;
typedef typename GMType::LabelType LabelType;
class Parameter{
public:
std::vector<double> parameterUpperbound_;
std::vector<double> parameterLowerbound_;
std::vector<size_t> testingPoints_;
Parameter(){;}
};
GridSearchLearner(DATASET&, Parameter& );
template<class INF>
void learn(typename INF::Parameter& para);
//template<class INF, class VISITOR>
//void learn(typename INF::Parameter para, VITITOR vis);
const opengm::learning::Weights<double>& getWeights(){return weights_;}
Parameter& getLerningParameters(){return para_;}
private:
DATASET& dataset_;
opengm::learning::Weights<double> weights_;
Parameter para_;
};
template<class DATASET>
GridSearchLearner<DATASET>::GridSearchLearner(DATASET& ds, Parameter& p )
: dataset_(ds), para_(p)
{
weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());
if(para_.parameterUpperbound_.size() != ds.getNumberOfWeights())
para_.parameterUpperbound_.resize(ds.getNumberOfWeights(),10.0);
if(para_.parameterLowerbound_.size() != ds.getNumberOfWeights())
para_.parameterLowerbound_.resize(ds.getNumberOfWeights(),0.0);
if(para_.testingPoints_.size() != ds.getNumberOfWeights())
para_.testingPoints_.resize(ds.getNumberOfWeights(),10);
}
template<class DATASET>
template<class INF>
void GridSearchLearner<DATASET>::learn(typename INF::Parameter& para){
// generate model Parameters
opengm::learning::Weights<double> modelPara( dataset_.getNumberOfWeights() );
opengm::learning::Weights<double> bestModelPara( dataset_.getNumberOfWeights() );
double bestLoss = 100000000.0;
std::vector<size_t> itC(dataset_.getNumberOfWeights(),0);
LossType lossFunction;
bool search=true;
while(search){
// Get Parameter
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
modelPara.setWeight(p, para_.parameterLowerbound_[p] + double(itC[p])/double(para_.testingPoints_[p]-1)*(para_.parameterUpperbound_[p]-para_.parameterLowerbound_[p]) );
}
// Evaluate Loss
opengm::learning::Weights<double>& mp = dataset_.getWeights();
mp = modelPara;
std::vector< std::vector<typename INF::LabelType> > confs( dataset_.getNumberOfModels() );
double loss = 0;
for(size_t m=0; m<dataset_.getNumberOfModels(); ++m){
INF inf( dataset_.getModel(m),para);
inf.infer();
inf.arg(confs[m]);
const std::vector<typename INF::LabelType>& gt = dataset_.getGT(m);
loss += lossFunction.loss(confs[m].begin(), confs[m].end(), gt.begin(), gt.end());
}
// *call visitor*
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
std::cout << modelPara[p] <<" ";
}
std::cout << " ==> ";
std::cout << loss << std::endl;
// **************
if(loss<bestLoss){
bestLoss=loss;
bestModelPara=modelPara;
}
//Increment Parameter
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
if(itC[p]<para_.testingPoints_[p]-1){
++itC[p];
break;
}
else{
itC[p]=0;
if (p==dataset_.getNumberOfWeights()-1)
search = false;
}
}
}
std::cout << "Best"<<std::endl;
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
std::cout << bestModelPara[p] <<" ";
}
std::cout << " ==> ";
std::cout << bestLoss << std::endl;
weights_ = bestModelPara;
};
}
}
#endif
<commit_msg>added const to param ref in grid search learner<commit_after>#pragma once
#ifndef OPENGM_GRIDSEARCH_LEARNER_HXX
#define OPENGM_GRIDSEARCH_LEARNER_HXX
#include <vector>
#include <opengm/functions/learnablefunction.hxx>
namespace opengm {
namespace learning {
template<class DATASET>
class GridSearchLearner
{
public:
typedef typename DATASET::GMType GMType;
typedef typename DATASET::LossType LossType;
typedef typename GMType::ValueType ValueType;
typedef typename GMType::IndexType IndexType;
typedef typename GMType::LabelType LabelType;
class Parameter{
public:
std::vector<double> parameterUpperbound_;
std::vector<double> parameterLowerbound_;
std::vector<size_t> testingPoints_;
Parameter(){;}
};
GridSearchLearner(DATASET&, const Parameter& );
template<class INF>
void learn(typename INF::Parameter& para);
//template<class INF, class VISITOR>
//void learn(typename INF::Parameter para, VITITOR vis);
const opengm::learning::Weights<double>& getWeights(){return weights_;}
Parameter& getLerningParameters(){return para_;}
private:
DATASET& dataset_;
opengm::learning::Weights<double> weights_;
Parameter para_;
};
template<class DATASET>
GridSearchLearner<DATASET>::GridSearchLearner(DATASET& ds, const Parameter& p )
: dataset_(ds), para_(p)
{
weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());
if(para_.parameterUpperbound_.size() != ds.getNumberOfWeights())
para_.parameterUpperbound_.resize(ds.getNumberOfWeights(),10.0);
if(para_.parameterLowerbound_.size() != ds.getNumberOfWeights())
para_.parameterLowerbound_.resize(ds.getNumberOfWeights(),0.0);
if(para_.testingPoints_.size() != ds.getNumberOfWeights())
para_.testingPoints_.resize(ds.getNumberOfWeights(),10);
}
template<class DATASET>
template<class INF>
void GridSearchLearner<DATASET>::learn(typename INF::Parameter& para){
// generate model Parameters
opengm::learning::Weights<double> modelPara( dataset_.getNumberOfWeights() );
opengm::learning::Weights<double> bestModelPara( dataset_.getNumberOfWeights() );
double bestLoss = 100000000.0;
std::vector<size_t> itC(dataset_.getNumberOfWeights(),0);
LossType lossFunction;
bool search=true;
while(search){
// Get Parameter
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
modelPara.setWeight(p, para_.parameterLowerbound_[p] + double(itC[p])/double(para_.testingPoints_[p]-1)*(para_.parameterUpperbound_[p]-para_.parameterLowerbound_[p]) );
}
// Evaluate Loss
opengm::learning::Weights<double>& mp = dataset_.getWeights();
mp = modelPara;
std::vector< std::vector<typename INF::LabelType> > confs( dataset_.getNumberOfModels() );
double loss = 0;
for(size_t m=0; m<dataset_.getNumberOfModels(); ++m){
INF inf( dataset_.getModel(m),para);
inf.infer();
inf.arg(confs[m]);
const std::vector<typename INF::LabelType>& gt = dataset_.getGT(m);
loss += lossFunction.loss(confs[m].begin(), confs[m].end(), gt.begin(), gt.end());
}
// *call visitor*
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
std::cout << modelPara[p] <<" ";
}
std::cout << " ==> ";
std::cout << loss << std::endl;
// **************
if(loss<bestLoss){
bestLoss=loss;
bestModelPara=modelPara;
}
//Increment Parameter
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
if(itC[p]<para_.testingPoints_[p]-1){
++itC[p];
break;
}
else{
itC[p]=0;
if (p==dataset_.getNumberOfWeights()-1)
search = false;
}
}
}
std::cout << "Best"<<std::endl;
for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
std::cout << bestModelPara[p] <<" ";
}
std::cout << " ==> ";
std::cout << bestLoss << std::endl;
weights_ = bestModelPara;
};
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef TWISTEDCPP_BYTE_RECEIVER_PARSER
#define TWISTEDCPP_BYTE_RECEIVER_PARSER
#include "../byte_receiver.hpp"
#include <vector>
#include <cstddef>
#include <boost/range/iterator_range.hpp>
#include <boost/container/vector.hpp>
#include <boost/container/container_fwd.hpp>
namespace twisted {
namespace byte {
template <typename Protocol>
void core_loop(std::size_t& _current_count, std::size_t& _current_begin,
boost::container::vector<char>& _read_buffer,
std::size_t _next_bytes_size, Protocol& protocol) {
/* protocol user can change package size in between calls
-> we need to cache the old package-size for the _current_* updates
*/
std::size_t old_package_size = _next_bytes_size;
protocol.bytes_received(
std::next(_read_buffer.begin(), _current_begin),
std::next(_read_buffer.begin(), _current_begin + _next_bytes_size));
_current_count -= old_package_size;
_current_begin += old_package_size;
}
inline bool loop_condition(std::size_t _current_count,
std::size_t _next_bytes_size) {
return _current_count >= _next_bytes_size;
}
inline void prepare_buffers(std::size_t _current_count,
std::size_t& _current_begin,
boost::container::vector<char>& _read_buffer) {
// un-fragmented data
if (_current_count == 0) {
_current_begin = 0;
}
/* fragmented data and buffer is full
-> we need to copy the existing data to the beginning
to make space for a full packet size */
else if (_current_begin + _current_count == _read_buffer.size()) {
std::copy(std::next(_read_buffer.begin(), _current_begin),
_read_buffer.end(), _read_buffer.begin());
_current_begin = 0;
}
}
template <typename Protocol, typename Iter>
void parse(Iter begin, Iter end, std::size_t& _current_begin,
std::size_t& _current_count, std::size_t& _next_bytes_size,
boost::container::vector<char>& _read_buffer, Protocol& protocol) {
_current_count += std::distance(begin, end);
while (loop_condition(_current_count, _next_bytes_size)) {
core_loop(_current_count, _current_begin, _read_buffer, _next_bytes_size, protocol);
}
prepare_buffers(_current_count, _current_begin, _read_buffer);
}
constexpr std::size_t calculate_buffer_size(std::size_t new_min_size) {
return 3 * new_min_size;
}
inline void set_package_size(std::size_t package_size, std::size_t& _next_bytes_size,
boost::container::vector<char>& _read_buffer) {
if (_next_bytes_size < package_size) {
_read_buffer.resize(calculate_buffer_size(package_size));
}
_next_bytes_size = package_size;
// evaluate different kinds of copying existing data + buffer size here
}
}
}
#endif
<commit_msg>buffer now only gets expanded on setting package size<commit_after>#ifndef TWISTEDCPP_BYTE_RECEIVER_PARSER
#define TWISTEDCPP_BYTE_RECEIVER_PARSER
#include "../byte_receiver.hpp"
#include <vector>
#include <cstddef>
#include <boost/range/iterator_range.hpp>
#include <boost/container/vector.hpp>
#include <boost/container/container_fwd.hpp>
namespace twisted {
namespace byte {
template <typename Protocol>
void core_loop(std::size_t& _current_count, std::size_t& _current_begin,
boost::container::vector<char>& _read_buffer,
std::size_t _next_bytes_size, Protocol& protocol) {
/* protocol user can change package size in between calls
-> we need to cache the old package-size for the _current_* updates
*/
std::size_t old_package_size = _next_bytes_size;
protocol.bytes_received(
std::next(_read_buffer.begin(), _current_begin),
std::next(_read_buffer.begin(), _current_begin + _next_bytes_size));
_current_count -= old_package_size;
_current_begin += old_package_size;
}
inline bool loop_condition(std::size_t _current_count,
std::size_t _next_bytes_size) {
return _current_count >= _next_bytes_size;
}
inline void prepare_buffers(std::size_t _current_count,
std::size_t& _current_begin,
boost::container::vector<char>& _read_buffer) {
// un-fragmented data
if (_current_count == 0) {
_current_begin = 0;
}
/* fragmented data and buffer is full
-> we need to copy the existing data to the beginning
to make space for a full packet size */
else if (_current_begin + _current_count == _read_buffer.size()) {
std::copy(std::next(_read_buffer.begin(), _current_begin),
_read_buffer.end(), _read_buffer.begin());
_current_begin = 0;
}
}
template <typename Protocol, typename Iter>
void parse(Iter begin, Iter end, std::size_t& _current_begin,
std::size_t& _current_count, std::size_t& _next_bytes_size,
boost::container::vector<char>& _read_buffer, Protocol& protocol) {
_current_count += std::distance(begin, end);
while (loop_condition(_current_count, _next_bytes_size)) {
core_loop(_current_count, _current_begin, _read_buffer, _next_bytes_size, protocol);
}
prepare_buffers(_current_count, _current_begin, _read_buffer);
}
constexpr std::size_t calculate_buffer_size(std::size_t new_min_size) {
return 3 * new_min_size;
}
inline void set_package_size(std::size_t package_size, std::size_t& _next_bytes_size,
boost::container::vector<char>& _read_buffer) {
if (_next_bytes_size < package_size) {
auto new_buffer_size = calculate_buffer_size(package_size);
if(new_buffer_size > _read_buffer.size()) {
_read_buffer.resize(new_buffer_size);
}
}
_next_bytes_size = package_size;
// evaluate different kinds of copying existing data + buffer size here
}
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>implementado y aplicado método CLAHE a las texturas del iris segmentadas #closed 21<commit_after><|endoftext|> |
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/PendingChannel>
#include "TelepathyQt4/Client/_gen/pending-channel.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Client/Channel>
#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/FileTransfer>
#include <TelepathyQt4/Client/RoomList>
#include <TelepathyQt4/Client/StreamedMediaChannel>
#include <TelepathyQt4/Client/TextChannel>
#include <TelepathyQt4/Constants>
/**
* \addtogroup clientsideproxies Client-side proxies
*
* Proxy objects representing remote service objects accessed via D-Bus.
*
* In addition to providing direct access to methods, signals and properties
* exported by the remote objects, some of these proxies offer features like
* automatic inspection of remote object capabilities, property tracking,
* backwards compatibility helpers for older services and other utilities.
*/
namespace Telepathy
{
namespace Client
{
struct PendingChannel::Private
{
bool yours;
QString channelType;
uint handleType;
uint handle;
QDBusObjectPath objectPath;
QVariantMap immutableProperties;
};
/**
* \class PendingChannel
* \ingroup clientconn
* \headerfile <TelepathyQt4/Client/pending-channel.h> <TelepathyQt4/Client/PendingChannel>
*
* Class containing the parameters of and the reply to an asynchronous channel
* request. Instances of this class cannot be constructed directly; the only way
* to get one is trough Connection.
*/
/**
* Construct a new PendingChannel object that will fail.
*
* \param connection Connection to use.
* \param errorName The error name.
* \param errorMessage The error message.
*/
PendingChannel::PendingChannel(Connection *connection, const QString &errorName,
const QString &errorMessage)
: PendingOperation(connection),
mPriv(new Private)
{
mPriv->yours = false;
mPriv->handleType = 0;
mPriv->handle = 0;
setFinishedWithError(errorName, errorMessage);
}
/**
* Construct a new PendingChannel object.
*
* \param connection Connection to use.
* \param request A dictionary containing the desirable properties.
* \param create Whether createChannel or ensureChannel should be called.
*/
PendingChannel::PendingChannel(Connection *connection,
const QVariantMap &request, bool create)
: PendingOperation(connection),
mPriv(new Private)
{
mPriv->yours = create;
mPriv->channelType = request.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
mPriv->handleType = request.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")).toUInt();
mPriv->handle = request.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")).toUInt();
if (create) {
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
connection->requestsInterface()->CreateChannel(request), this);
connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(onCallCreateChannelFinished(QDBusPendingCallWatcher *)));
}
else {
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
connection->requestsInterface()->EnsureChannel(request), this);
connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(onCallEnsureChannelFinished(QDBusPendingCallWatcher *)));
}
}
/**
* Class destructor.
*/
PendingChannel::~PendingChannel()
{
delete mPriv;
}
/**
* Return the Connection object through which the channel request was made.
*
* \return Pointer to the Connection.
*/
Connection *PendingChannel::connection() const
{
return qobject_cast<Connection *>(parent());
}
/**
* Return whether this channel belongs to this process.
*
* If false, the caller MUST assume that some other process is
* handling this channel; if true, the caller SHOULD handle it
* themselves or delegate it to another client.
*
* Note that the value is undefined until the operation finishes.
*
* \return Boolean indicating whether this channel belongs to this process.
*/
bool PendingChannel::yours() const
{
if (!isFinished()) {
warning() << "PendingChannel::yours called before finished, returning undefined value";
}
else if (!isValid()) {
warning() << "PendingChannel::yours called when not valid, returning undefined value";
}
return mPriv->yours;
}
/**
* Return the channel type specified in the channel request.
*
* \return The D-Bus interface name of the interface specific to the
* requested channel type.
*/
const QString &PendingChannel::channelType() const
{
return mPriv->channelType;
}
/**
* Return the handle type specified in the channel request.
*
* \return The handle type, as specified in #HandleType.
*/
uint PendingChannel::handleType() const
{
return mPriv->handleType;
}
/**
* Return the handle specified in the channel request.
*
* \return The handle.
*/
uint PendingChannel::handle() const
{
return mPriv->handle;
}
/**
* Returns a newly constructed Channel high-level proxy object associated
* with the remote channel resulting from the channel request. If isValid()
* returns <code>false</code>, the request has not (at least yet) completed
* successfully, and 0 will be returned.
*
* \param parent Passed to the Channel constructor.
* \return Pointer to the new Channel object, 0 if an error occurred.
*/
Channel *PendingChannel::channel(QObject *parent) const
{
if (!isFinished()) {
warning() << "PendingChannel::channel called before finished, returning 0";
return 0;
}
else if (!isValid()) {
warning() << "PendingChannel::channel called when not valid, returning 0";
return 0;
}
Channel *channel;
if (channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT) {
channel = new TextChannel(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
else if (channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA) {
channel = new StreamedMediaChannel(connection(),
mPriv->objectPath.path(), mPriv->immutableProperties, parent);
}
else if (channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_ROOM_LIST) {
channel = new RoomList(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
else if (channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER) {
channel = new FileTransfer(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
else {
// ContactList, old-style Tubes, or a future channel type
channel = new Channel(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
return channel;
}
void PendingChannel::onCallCreateChannelFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QDBusObjectPath, QVariantMap> reply = *watcher;
if (!reply.isError()) {
mPriv->objectPath = reply.argumentAt<0>();
debug() << "Got reply to Connection.CreateChannel - object path:" <<
mPriv->objectPath.path();
QVariantMap map = reply.argumentAt<1>();
mPriv->immutableProperties = map;
mPriv->channelType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
mPriv->handleType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")).toUInt();
mPriv->handle = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")).toUInt();
setFinished();
} else {
debug().nospace() << "CreateChannel failed:" <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
}
watcher->deleteLater();
}
void PendingChannel::onCallEnsureChannelFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<bool, QDBusObjectPath, QVariantMap> reply = *watcher;
if (!reply.isError()) {
mPriv->yours = reply.argumentAt<0>();
mPriv->objectPath = reply.argumentAt<1>();
debug() << "Got reply to Connection.EnsureChannel - object path:" <<
mPriv->objectPath.path();
QVariantMap map = reply.argumentAt<2>();
mPriv->immutableProperties = map;
mPriv->channelType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
mPriv->handleType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")).toUInt();
mPriv->handle = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")).toUInt();
setFinished();
} else {
debug().nospace() << "EnsureChannel failed:" <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
}
watcher->deleteLater();
}
} // Telepathy::Client
} // Telepathy
<commit_msg>PendingChannel: we don't officially know about FileTransfer yet<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/PendingChannel>
#include "TelepathyQt4/Client/_gen/pending-channel.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Client/Channel>
#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/FileTransfer>
#include <TelepathyQt4/Client/RoomList>
#include <TelepathyQt4/Client/StreamedMediaChannel>
#include <TelepathyQt4/Client/TextChannel>
#include <TelepathyQt4/Constants>
/**
* \addtogroup clientsideproxies Client-side proxies
*
* Proxy objects representing remote service objects accessed via D-Bus.
*
* In addition to providing direct access to methods, signals and properties
* exported by the remote objects, some of these proxies offer features like
* automatic inspection of remote object capabilities, property tracking,
* backwards compatibility helpers for older services and other utilities.
*/
namespace Telepathy
{
namespace Client
{
struct PendingChannel::Private
{
bool yours;
QString channelType;
uint handleType;
uint handle;
QDBusObjectPath objectPath;
QVariantMap immutableProperties;
};
/**
* \class PendingChannel
* \ingroup clientconn
* \headerfile <TelepathyQt4/Client/pending-channel.h> <TelepathyQt4/Client/PendingChannel>
*
* Class containing the parameters of and the reply to an asynchronous channel
* request. Instances of this class cannot be constructed directly; the only way
* to get one is trough Connection.
*/
/**
* Construct a new PendingChannel object that will fail.
*
* \param connection Connection to use.
* \param errorName The error name.
* \param errorMessage The error message.
*/
PendingChannel::PendingChannel(Connection *connection, const QString &errorName,
const QString &errorMessage)
: PendingOperation(connection),
mPriv(new Private)
{
mPriv->yours = false;
mPriv->handleType = 0;
mPriv->handle = 0;
setFinishedWithError(errorName, errorMessage);
}
/**
* Construct a new PendingChannel object.
*
* \param connection Connection to use.
* \param request A dictionary containing the desirable properties.
* \param create Whether createChannel or ensureChannel should be called.
*/
PendingChannel::PendingChannel(Connection *connection,
const QVariantMap &request, bool create)
: PendingOperation(connection),
mPriv(new Private)
{
mPriv->yours = create;
mPriv->channelType = request.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
mPriv->handleType = request.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")).toUInt();
mPriv->handle = request.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")).toUInt();
if (create) {
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
connection->requestsInterface()->CreateChannel(request), this);
connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(onCallCreateChannelFinished(QDBusPendingCallWatcher *)));
}
else {
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
connection->requestsInterface()->EnsureChannel(request), this);
connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(onCallEnsureChannelFinished(QDBusPendingCallWatcher *)));
}
}
/**
* Class destructor.
*/
PendingChannel::~PendingChannel()
{
delete mPriv;
}
/**
* Return the Connection object through which the channel request was made.
*
* \return Pointer to the Connection.
*/
Connection *PendingChannel::connection() const
{
return qobject_cast<Connection *>(parent());
}
/**
* Return whether this channel belongs to this process.
*
* If false, the caller MUST assume that some other process is
* handling this channel; if true, the caller SHOULD handle it
* themselves or delegate it to another client.
*
* Note that the value is undefined until the operation finishes.
*
* \return Boolean indicating whether this channel belongs to this process.
*/
bool PendingChannel::yours() const
{
if (!isFinished()) {
warning() << "PendingChannel::yours called before finished, returning undefined value";
}
else if (!isValid()) {
warning() << "PendingChannel::yours called when not valid, returning undefined value";
}
return mPriv->yours;
}
/**
* Return the channel type specified in the channel request.
*
* \return The D-Bus interface name of the interface specific to the
* requested channel type.
*/
const QString &PendingChannel::channelType() const
{
return mPriv->channelType;
}
/**
* Return the handle type specified in the channel request.
*
* \return The handle type, as specified in #HandleType.
*/
uint PendingChannel::handleType() const
{
return mPriv->handleType;
}
/**
* Return the handle specified in the channel request.
*
* \return The handle.
*/
uint PendingChannel::handle() const
{
return mPriv->handle;
}
/**
* Returns a newly constructed Channel high-level proxy object associated
* with the remote channel resulting from the channel request. If isValid()
* returns <code>false</code>, the request has not (at least yet) completed
* successfully, and 0 will be returned.
*
* \param parent Passed to the Channel constructor.
* \return Pointer to the new Channel object, 0 if an error occurred.
*/
Channel *PendingChannel::channel(QObject *parent) const
{
if (!isFinished()) {
warning() << "PendingChannel::channel called before finished, returning 0";
return 0;
}
else if (!isValid()) {
warning() << "PendingChannel::channel called when not valid, returning 0";
return 0;
}
Channel *channel;
if (channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT) {
channel = new TextChannel(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
else if (channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA) {
channel = new StreamedMediaChannel(connection(),
mPriv->objectPath.path(), mPriv->immutableProperties, parent);
}
else if (channelType() == TELEPATHY_INTERFACE_CHANNEL_TYPE_ROOM_LIST) {
channel = new RoomList(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
// FIXME: update spec so we can do this properly
else if (channelType() == "org.freedesktop.Telepathy.Channel.Type.FileTransfer") {
channel = new FileTransfer(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
else {
// ContactList, old-style Tubes, or a future channel type
channel = new Channel(connection(), mPriv->objectPath.path(),
mPriv->immutableProperties, parent);
}
return channel;
}
void PendingChannel::onCallCreateChannelFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QDBusObjectPath, QVariantMap> reply = *watcher;
if (!reply.isError()) {
mPriv->objectPath = reply.argumentAt<0>();
debug() << "Got reply to Connection.CreateChannel - object path:" <<
mPriv->objectPath.path();
QVariantMap map = reply.argumentAt<1>();
mPriv->immutableProperties = map;
mPriv->channelType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
mPriv->handleType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")).toUInt();
mPriv->handle = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")).toUInt();
setFinished();
} else {
debug().nospace() << "CreateChannel failed:" <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
}
watcher->deleteLater();
}
void PendingChannel::onCallEnsureChannelFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<bool, QDBusObjectPath, QVariantMap> reply = *watcher;
if (!reply.isError()) {
mPriv->yours = reply.argumentAt<0>();
mPriv->objectPath = reply.argumentAt<1>();
debug() << "Got reply to Connection.EnsureChannel - object path:" <<
mPriv->objectPath.path();
QVariantMap map = reply.argumentAt<2>();
mPriv->immutableProperties = map;
mPriv->channelType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
mPriv->handleType = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")).toUInt();
mPriv->handle = map.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")).toUInt();
setFinished();
} else {
debug().nospace() << "EnsureChannel failed:" <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
}
watcher->deleteLater();
}
} // Telepathy::Client
} // Telepathy
<|endoftext|> |
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2010 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/ContactSearchChannel>
#include "TelepathyQt4/_gen/contact-search-channel.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/Types>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT ContactSearchChannel::Private
{
Private(ContactSearchChannel *parent,
const QVariantMap &immutableProperties);
~Private();
static void introspectMain(Private *self);
void extractImmutableProperties(const QVariantMap &props);
// Public object
ContactSearchChannel *parent;
QVariantMap immutableProperties;
Client::ChannelTypeContactSearchInterface *contactSearchInterface;
Client::DBus::PropertiesInterface *properties;
ReadinessHelper *readinessHelper;
// Introspection
uint searchState;
uint limit;
QStringList availableSearchKeys;
QString server;
};
ContactSearchChannel::Private::Private(ContactSearchChannel *parent,
const QVariantMap &immutableProperties)
: parent(parent),
immutableProperties(immutableProperties),
contactSearchInterface(parent->contactSearchInterface(BypassInterfaceCheck)),
properties(0),
readinessHelper(parent->readinessHelper())
{
ReadinessHelper::Introspectables introspectables;
ReadinessHelper::Introspectable introspectableCore(
QSet<uint>() << 0, // makesSenseForStatuses
Features() << Channel::FeatureCore, // dependsOnFeatures (core)
QStringList(), // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &Private::introspectMain,
this);
introspectables[FeatureCore] = introspectableCore;
readinessHelper->addIntrospectables(introspectables);
}
ContactSearchChannel::Private::~Private()
{
}
void ContactSearchChannel::Private::introspectMain(ContactSearchChannel::Private *self)
{
if (!self->properties) {
self->properties = self->parent->propertiesInterface();
Q_ASSERT(self->properties != 0);
}
/* we need to at least introspect SearchState here as it's not immutable */
self->parent->connect(self->contactSearchInterface,
SIGNAL(SearchStateChanged(uint,QString,QVariantMap)),
SLOT(onSearchStateChanged(uint,QString,QVariantMap)));
QVariantMap props;
bool needIntrospectMainProps = false;
const unsigned numNames = 3;
const static QString names[numNames] = {
QLatin1String("Limit"),
QLatin1String("AvailableSearchKeys"),
QLatin1String("Server")
};
const static QString qualifiedNames[numNames] = {
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Limit"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".AvailableSearchKeys"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Server")
};
for (unsigned i = 0; i < numNames; ++i) {
const QString &qualified = qualifiedNames[i];
if (!self->immutableProperties.contains(qualified)) {
needIntrospectMainProps = true;
break;
}
props.insert(names[i], self->immutableProperties.value(qualified));
}
if (needIntrospectMainProps) {
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(
self->properties->GetAll(
QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_SEARCH)),
self->parent);
self->parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotProperties(QDBusPendingCallWatcher*)));
} else {
self->extractImmutableProperties(props);
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(
self->properties->Get(
QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_SEARCH),
QLatin1String("SearchState")),
self->parent);
self->parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotSearchState(QDBusPendingCallWatcher*)));
}
}
void ContactSearchChannel::Private::extractImmutableProperties(const QVariantMap &props)
{
limit = qdbus_cast<uint>(props[QLatin1String("Limit")]);
availableSearchKeys = qdbus_cast<QStringList>(props[QLatin1String("AvailableSearchKeys")]);
server = qdbus_cast<QString>(props[QLatin1String("Server")]);
}
struct TELEPATHY_QT4_NO_EXPORT ContactSearchChannel::SearchStateChangeDetails::Private : public QSharedData
{
Private(const QVariantMap &details)
: details(details) {}
QVariantMap details;
};
ContactSearchChannel::SearchStateChangeDetails::SearchStateChangeDetails(const QVariantMap &details)
: mPriv(new Private(details))
{
}
ContactSearchChannel::SearchStateChangeDetails::SearchStateChangeDetails()
{
}
ContactSearchChannel::SearchStateChangeDetails::SearchStateChangeDetails(
const ContactSearchChannel::SearchStateChangeDetails &other)
: mPriv(other.mPriv)
{
}
ContactSearchChannel::SearchStateChangeDetails::~SearchStateChangeDetails()
{
}
ContactSearchChannel::SearchStateChangeDetails &ContactSearchChannel::SearchStateChangeDetails::operator=(
const ContactSearchChannel::SearchStateChangeDetails &other)
{
this->mPriv = other.mPriv;
return *this;
}
QVariantMap ContactSearchChannel::SearchStateChangeDetails::allDetails() const
{
return isValid() ? mPriv->details : QVariantMap();
}
/**
* \class ContactSearchChannel
* \ingroup clientchannel
* \headerfile TelepathyQt4/contact-search-channel.h <TelepathyQt4/ContactSearchChannel>
*
* \brief The ContactSearchChannel class provides an object representing a
* Telepathy channel of type ContactSearch.
*/
/**
* Feature representing the core that needs to become ready to make the
* ContactSearchChannel object usable.
*
* Note that this feature must be enabled in order to use most
* ContactSearchChannel methods.
* See specific methods documentation for more details.
*
* When calling isReady(), becomeReady(), this feature is implicitly added
* to the requested features.
*/
const Feature ContactSearchChannel::FeatureCore = Feature(QLatin1String(ContactSearchChannel::staticMetaObject.className()), 0);
/**
* Create a new ContactSearchChannel object.
*
* \param connection Connection owning this channel, and specifying the
* service.
* \param objectPath The object path of this channel.
* \param immutableProperties The immutable properties of this channel.
* \return A ContactSearchChannelPtr object pointing to the newly created
* ContactSearchChannel object.
*/
ContactSearchChannelPtr ContactSearchChannel::create(const ConnectionPtr &connection,
const QString &objectPath, const QVariantMap &immutableProperties)
{
return ContactSearchChannelPtr(new ContactSearchChannel(connection, objectPath,
immutableProperties));
}
/**
* Construct a new contact search channel associated with the given \a objectPath
* on the same service as the given \a connection.
*
* \param connection Connection owning this channel, and specifying the service.
* \param objectPath Path to the object on the service.
* \param immutableProperties The immutable properties of the channel.
*/
ContactSearchChannel::ContactSearchChannel(const ConnectionPtr &connection,
const QString &objectPath,
const QVariantMap &immutableProperties)
: Channel(connection, objectPath, immutableProperties),
mPriv(new Private(this, immutableProperties))
{
}
/**
* Class destructor.
*/
ContactSearchChannel::~ContactSearchChannel()
{
delete mPriv;
}
/**
* Return the current search state of this channel.
*
* Change notification is via searchStateChanged().
*
* \return The current search state of this channel.
*/
ChannelContactSearchState ContactSearchChannel::searchState() const
{
return static_cast<ChannelContactSearchState>(mPriv->searchState);
}
/**
* Return the maximum number of results that should be returned by calling search(), where
* 0 represents no limit.
*
* For example, if the terms passed to search() match Antonius, Bridget and Charles and
* this property is 2, the search service will only return Antonius and Bridget.
*
* This method requires ContactSearchChannel::FeatureCore to be enabled.
*
* \return The maximum number of results that should be returned by calling search().
*/
uint ContactSearchChannel::limit() const
{
return mPriv->limit;
}
/**
* Return the set of search keys supported by this channel.
*
* Example values include [""] (for protocols where several address fields are implicitly searched)
* or ["x-n-given", "x-n-family", "nickname", "email"] (for XMPP XEP-0055, without extensibility via
* Data Forms).
*
* This method requires ContactSearchChannel::FeatureCore to be enabled.
*
* \return The search keys supported by this channel.
*/
QStringList ContactSearchChannel::availableSearchKeys() const
{
return mPriv->availableSearchKeys;
}
/**
* Return the DNS name of the server being searched by this channel.
*
* This method requires ContactSearchChannel::FeatureCore to be enabled.
*
* \return For protocols which support searching for contacts on multiple servers with different DNS
* names (like XMPP), the DNS name of the server being searched by this channel, e.g.
* "characters.shakespeare.lit". Otherwise, an empty string.
*/
QString ContactSearchChannel::server() const
{
return mPriv->server;
}
void ContactSearchChannel::gotProperties(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariantMap> reply = *watcher;
if (!reply.isError()) {
QVariantMap props = reply.value();
mPriv->extractImmutableProperties(props);
mPriv->searchState = qdbus_cast<uint>(props[QLatin1String("SearchState")]);
debug() << "Got reply to Properties::GetAll(ContactSearchChannel)";
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
} else {
warning().nospace() << "Properties::GetAll(ContactSearchChannel) failed "
"with " << reply.error().name() << ": " << reply.error().message();
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false,
reply.error());
}
watcher->deleteLater();
}
void ContactSearchChannel::gotSearchState(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariant> reply = *watcher;
if (!reply.isError()) {
mPriv->searchState = qdbus_cast<uint>(reply.value());
debug() << "Got reply to Properties::Get(SearchState)";
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
} else {
warning().nospace() << "Properties::GetAll(ContactSearchChannel) failed "
"with " << reply.error().name() << ": " << reply.error().message();
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false,
reply.error());
}
watcher->deleteLater();
}
void ContactSearchChannel::onSearchStateChanged(uint state, const QString &error,
const QVariantMap &details)
{
mPriv->searchState = state;
emit searchStateChanged(static_cast<ChannelContactSearchState>(state), error,
SearchStateChangeDetails(details));
}
} // Tp
<commit_msg>ContactSearchChannel: Fixed copy/paste debug message.<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2010 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/ContactSearchChannel>
#include "TelepathyQt4/_gen/contact-search-channel.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/Types>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT ContactSearchChannel::Private
{
Private(ContactSearchChannel *parent,
const QVariantMap &immutableProperties);
~Private();
static void introspectMain(Private *self);
void extractImmutableProperties(const QVariantMap &props);
// Public object
ContactSearchChannel *parent;
QVariantMap immutableProperties;
Client::ChannelTypeContactSearchInterface *contactSearchInterface;
Client::DBus::PropertiesInterface *properties;
ReadinessHelper *readinessHelper;
// Introspection
uint searchState;
uint limit;
QStringList availableSearchKeys;
QString server;
};
ContactSearchChannel::Private::Private(ContactSearchChannel *parent,
const QVariantMap &immutableProperties)
: parent(parent),
immutableProperties(immutableProperties),
contactSearchInterface(parent->contactSearchInterface(BypassInterfaceCheck)),
properties(0),
readinessHelper(parent->readinessHelper())
{
ReadinessHelper::Introspectables introspectables;
ReadinessHelper::Introspectable introspectableCore(
QSet<uint>() << 0, // makesSenseForStatuses
Features() << Channel::FeatureCore, // dependsOnFeatures (core)
QStringList(), // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &Private::introspectMain,
this);
introspectables[FeatureCore] = introspectableCore;
readinessHelper->addIntrospectables(introspectables);
}
ContactSearchChannel::Private::~Private()
{
}
void ContactSearchChannel::Private::introspectMain(ContactSearchChannel::Private *self)
{
if (!self->properties) {
self->properties = self->parent->propertiesInterface();
Q_ASSERT(self->properties != 0);
}
/* we need to at least introspect SearchState here as it's not immutable */
self->parent->connect(self->contactSearchInterface,
SIGNAL(SearchStateChanged(uint,QString,QVariantMap)),
SLOT(onSearchStateChanged(uint,QString,QVariantMap)));
QVariantMap props;
bool needIntrospectMainProps = false;
const unsigned numNames = 3;
const static QString names[numNames] = {
QLatin1String("Limit"),
QLatin1String("AvailableSearchKeys"),
QLatin1String("Server")
};
const static QString qualifiedNames[numNames] = {
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Limit"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".AvailableSearchKeys"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Server")
};
for (unsigned i = 0; i < numNames; ++i) {
const QString &qualified = qualifiedNames[i];
if (!self->immutableProperties.contains(qualified)) {
needIntrospectMainProps = true;
break;
}
props.insert(names[i], self->immutableProperties.value(qualified));
}
if (needIntrospectMainProps) {
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(
self->properties->GetAll(
QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_SEARCH)),
self->parent);
self->parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotProperties(QDBusPendingCallWatcher*)));
} else {
self->extractImmutableProperties(props);
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(
self->properties->Get(
QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_SEARCH),
QLatin1String("SearchState")),
self->parent);
self->parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotSearchState(QDBusPendingCallWatcher*)));
}
}
void ContactSearchChannel::Private::extractImmutableProperties(const QVariantMap &props)
{
limit = qdbus_cast<uint>(props[QLatin1String("Limit")]);
availableSearchKeys = qdbus_cast<QStringList>(props[QLatin1String("AvailableSearchKeys")]);
server = qdbus_cast<QString>(props[QLatin1String("Server")]);
}
struct TELEPATHY_QT4_NO_EXPORT ContactSearchChannel::SearchStateChangeDetails::Private : public QSharedData
{
Private(const QVariantMap &details)
: details(details) {}
QVariantMap details;
};
ContactSearchChannel::SearchStateChangeDetails::SearchStateChangeDetails(const QVariantMap &details)
: mPriv(new Private(details))
{
}
ContactSearchChannel::SearchStateChangeDetails::SearchStateChangeDetails()
{
}
ContactSearchChannel::SearchStateChangeDetails::SearchStateChangeDetails(
const ContactSearchChannel::SearchStateChangeDetails &other)
: mPriv(other.mPriv)
{
}
ContactSearchChannel::SearchStateChangeDetails::~SearchStateChangeDetails()
{
}
ContactSearchChannel::SearchStateChangeDetails &ContactSearchChannel::SearchStateChangeDetails::operator=(
const ContactSearchChannel::SearchStateChangeDetails &other)
{
this->mPriv = other.mPriv;
return *this;
}
QVariantMap ContactSearchChannel::SearchStateChangeDetails::allDetails() const
{
return isValid() ? mPriv->details : QVariantMap();
}
/**
* \class ContactSearchChannel
* \ingroup clientchannel
* \headerfile TelepathyQt4/contact-search-channel.h <TelepathyQt4/ContactSearchChannel>
*
* \brief The ContactSearchChannel class provides an object representing a
* Telepathy channel of type ContactSearch.
*/
/**
* Feature representing the core that needs to become ready to make the
* ContactSearchChannel object usable.
*
* Note that this feature must be enabled in order to use most
* ContactSearchChannel methods.
* See specific methods documentation for more details.
*
* When calling isReady(), becomeReady(), this feature is implicitly added
* to the requested features.
*/
const Feature ContactSearchChannel::FeatureCore = Feature(QLatin1String(ContactSearchChannel::staticMetaObject.className()), 0);
/**
* Create a new ContactSearchChannel object.
*
* \param connection Connection owning this channel, and specifying the
* service.
* \param objectPath The object path of this channel.
* \param immutableProperties The immutable properties of this channel.
* \return A ContactSearchChannelPtr object pointing to the newly created
* ContactSearchChannel object.
*/
ContactSearchChannelPtr ContactSearchChannel::create(const ConnectionPtr &connection,
const QString &objectPath, const QVariantMap &immutableProperties)
{
return ContactSearchChannelPtr(new ContactSearchChannel(connection, objectPath,
immutableProperties));
}
/**
* Construct a new contact search channel associated with the given \a objectPath
* on the same service as the given \a connection.
*
* \param connection Connection owning this channel, and specifying the service.
* \param objectPath Path to the object on the service.
* \param immutableProperties The immutable properties of the channel.
*/
ContactSearchChannel::ContactSearchChannel(const ConnectionPtr &connection,
const QString &objectPath,
const QVariantMap &immutableProperties)
: Channel(connection, objectPath, immutableProperties),
mPriv(new Private(this, immutableProperties))
{
}
/**
* Class destructor.
*/
ContactSearchChannel::~ContactSearchChannel()
{
delete mPriv;
}
/**
* Return the current search state of this channel.
*
* Change notification is via searchStateChanged().
*
* \return The current search state of this channel.
*/
ChannelContactSearchState ContactSearchChannel::searchState() const
{
return static_cast<ChannelContactSearchState>(mPriv->searchState);
}
/**
* Return the maximum number of results that should be returned by calling search(), where
* 0 represents no limit.
*
* For example, if the terms passed to search() match Antonius, Bridget and Charles and
* this property is 2, the search service will only return Antonius and Bridget.
*
* This method requires ContactSearchChannel::FeatureCore to be enabled.
*
* \return The maximum number of results that should be returned by calling search().
*/
uint ContactSearchChannel::limit() const
{
return mPriv->limit;
}
/**
* Return the set of search keys supported by this channel.
*
* Example values include [""] (for protocols where several address fields are implicitly searched)
* or ["x-n-given", "x-n-family", "nickname", "email"] (for XMPP XEP-0055, without extensibility via
* Data Forms).
*
* This method requires ContactSearchChannel::FeatureCore to be enabled.
*
* \return The search keys supported by this channel.
*/
QStringList ContactSearchChannel::availableSearchKeys() const
{
return mPriv->availableSearchKeys;
}
/**
* Return the DNS name of the server being searched by this channel.
*
* This method requires ContactSearchChannel::FeatureCore to be enabled.
*
* \return For protocols which support searching for contacts on multiple servers with different DNS
* names (like XMPP), the DNS name of the server being searched by this channel, e.g.
* "characters.shakespeare.lit". Otherwise, an empty string.
*/
QString ContactSearchChannel::server() const
{
return mPriv->server;
}
void ContactSearchChannel::gotProperties(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariantMap> reply = *watcher;
if (!reply.isError()) {
QVariantMap props = reply.value();
mPriv->extractImmutableProperties(props);
mPriv->searchState = qdbus_cast<uint>(props[QLatin1String("SearchState")]);
debug() << "Got reply to Properties::GetAll(ContactSearchChannel)";
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
} else {
warning().nospace() << "Properties::GetAll(ContactSearchChannel) failed "
"with " << reply.error().name() << ": " << reply.error().message();
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false,
reply.error());
}
watcher->deleteLater();
}
void ContactSearchChannel::gotSearchState(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariant> reply = *watcher;
if (!reply.isError()) {
mPriv->searchState = qdbus_cast<uint>(reply.value());
debug() << "Got reply to Properties::Get(SearchState)";
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
} else {
warning().nospace() << "Properties::Get(SearchState) failed "
"with " << reply.error().name() << ": " << reply.error().message();
mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false,
reply.error());
}
watcher->deleteLater();
}
void ContactSearchChannel::onSearchStateChanged(uint state, const QString &error,
const QVariantMap &details)
{
mPriv->searchState = state;
emit searchStateChanged(static_cast<ChannelContactSearchState>(state), error,
SearchStateChangeDetails(details));
}
} // Tp
<|endoftext|> |
<commit_before>/*
* Radio device interface with sample rate conversion
* Written by Thomas Tsou <tom@tsou.cc>
*
* Copyright 2011, 2012, 2013 Free Software Foundation, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* See the COPYING file in the main directory for details.
*/
#include <radioInterface.h>
#include <Logger.h>
#include "Resampler.h"
extern "C" {
#include "convert.h"
}
/* New chunk sizes for resampled rate */
#ifdef INCHUNK
#undef INCHUNK
#endif
#ifdef OUTCHUNK
#undef OUTCHUNK
#endif
/* Resampling parameters for 100 MHz clocking */
#define RESAMP_INRATE 52
#define RESAMP_OUTRATE 75
#define RESAMP_FILT_LEN 16
#define INCHUNK (RESAMP_INRATE * 4)
#define OUTCHUNK (RESAMP_OUTRATE * 4)
static Resampler *upsampler = NULL;
static Resampler *dnsampler = NULL;
short *convertRecvBuffer = NULL;
short *convertSendBuffer = NULL;
RadioInterfaceResamp::RadioInterfaceResamp(RadioDevice *wRadio,
int wReceiveOffset,
int wSPS,
GSM::Time wStartTime)
: RadioInterface(wRadio, wReceiveOffset, wSPS, wStartTime),
innerSendBuffer(NULL), outerSendBuffer(NULL),
innerRecvBuffer(NULL), outerRecvBuffer(NULL)
{
}
RadioInterfaceResamp::~RadioInterfaceResamp()
{
close();
}
void RadioInterfaceResamp::close()
{
RadioInterface::close();
delete innerSendBuffer;
delete outerSendBuffer;
delete innerRecvBuffer;
delete outerRecvBuffer;
delete upsampler;
delete dnsampler;
innerSendBuffer = NULL;
outerSendBuffer = NULL;
innerRecvBuffer = NULL;
outerRecvBuffer = NULL;
upsampler = NULL;
dnsampler = NULL;
}
/* Initialize I/O specific objects */
bool RadioInterfaceResamp::init()
{
float cutoff = 1.0f;
close();
/*
* With oversampling, restrict bandwidth to 150% of base rate. This also
* provides last ditch bandwith limiting if the pulse shaping filter is
* insufficient.
*/
if (sps > 1)
cutoff = 1.5 / sps;
dnsampler = new Resampler(RESAMP_INRATE, RESAMP_OUTRATE);
if (!dnsampler->init(cutoff)) {
LOG(ALERT) << "Rx resampler failed to initialize";
return false;
}
upsampler = new Resampler(RESAMP_OUTRATE, RESAMP_INRATE);
if (!upsampler->init(cutoff)) {
LOG(ALERT) << "Tx resampler failed to initialize";
return false;
}
/*
* Allocate high and low rate buffers. The high rate receive
* buffer and low rate transmit vectors feed into the resampler
* and requires headroom equivalent to the filter length. Low
* rate buffers are allocated in the main radio interface code.
*/
innerSendBuffer = new signalVector(INCHUNK * 20, RESAMP_FILT_LEN);
outerSendBuffer = new signalVector(OUTCHUNK * 20);
outerRecvBuffer = new signalVector(OUTCHUNK * 2, RESAMP_FILT_LEN);
innerRecvBuffer = new signalVector(INCHUNK * 20);
convertSendBuffer = new short[OUTCHUNK * 2 * 20];
convertRecvBuffer = new short[OUTCHUNK * 2 * 2];
sendBuffer = innerSendBuffer;
recvBuffer = innerRecvBuffer;
return true;
}
/* Receive a timestamped chunk from the device */
void RadioInterfaceResamp::pullBuffer()
{
bool local_underrun;
int rc, num_recv;
int inner_len = INCHUNK;
int outer_len = OUTCHUNK;
/* Outer buffer access size is fixed */
num_recv = mRadio->readSamples(convertRecvBuffer,
outer_len,
&overrun,
readTimestamp,
&local_underrun);
if (num_recv != outer_len) {
LOG(ALERT) << "Receive error " << num_recv;
return;
}
convert_short_float((float *) outerRecvBuffer->begin(),
convertRecvBuffer, 2 * outer_len);
underrun |= local_underrun;
readTimestamp += (TIMESTAMP) num_recv;
/* Write to the end of the inner receive buffer */
rc = dnsampler->rotate((float *) outerRecvBuffer->begin(), outer_len,
(float *) (innerRecvBuffer->begin() + recvCursor),
inner_len);
if (rc < 0) {
LOG(ALERT) << "Sample rate upsampling error";
}
recvCursor += inner_len;
}
/* Send a timestamped chunk to the device */
void RadioInterfaceResamp::pushBuffer()
{
int rc, chunks, num_sent;
int inner_len, outer_len;
if (sendCursor < INCHUNK)
return;
chunks = sendCursor / INCHUNK;
if (chunks > 8)
chunks = 8;
inner_len = chunks * INCHUNK;
outer_len = chunks * OUTCHUNK;
/* Always send from the beginning of the buffer */
rc = upsampler->rotate((float *) innerSendBuffer->begin(), inner_len,
(float *) outerSendBuffer->begin(), outer_len);
if (rc < 0) {
LOG(ALERT) << "Sample rate downsampling error";
}
convert_float_short(convertSendBuffer,
(float *) outerSendBuffer->begin(),
powerScaling, 2 * outer_len);
num_sent = mRadio->writeSamples(convertSendBuffer,
outer_len,
&underrun,
writeTimestamp);
if (num_sent != outer_len) {
LOG(ALERT) << "Transmit error " << num_sent;
}
/* Shift remaining samples to beginning of buffer */
memmove(innerSendBuffer->begin(),
innerSendBuffer->begin() + inner_len,
(sendCursor - inner_len) * 2 * sizeof(float));
writeTimestamp += outer_len;
sendCursor -= inner_len;
assert(sendCursor >= 0);
}
<commit_msg>Transceiver52M: Narrow resampling filter bandwidth<commit_after>/*
* Radio device interface with sample rate conversion
* Written by Thomas Tsou <tom@tsou.cc>
*
* Copyright 2011, 2012, 2013 Free Software Foundation, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* See the COPYING file in the main directory for details.
*/
#include <radioInterface.h>
#include <Logger.h>
#include "Resampler.h"
extern "C" {
#include "convert.h"
}
/* New chunk sizes for resampled rate */
#ifdef INCHUNK
#undef INCHUNK
#endif
#ifdef OUTCHUNK
#undef OUTCHUNK
#endif
/* Resampling parameters for 100 MHz clocking */
#define RESAMP_INRATE 52
#define RESAMP_OUTRATE 75
/*
* Resampling filter bandwidth scaling factor
* This narrows the filter cutoff relative to the output bandwidth
* of the polyphase resampler. At 4 samples-per-symbol using the
* 2 pulse Laurent GMSK approximation gives us below 0.5 degrees
* RMS phase error at the resampler output.
*/
#define RESAMP_TX4_FILTER 0.45
#define INCHUNK (RESAMP_INRATE * 4)
#define OUTCHUNK (RESAMP_OUTRATE * 4)
static Resampler *upsampler = NULL;
static Resampler *dnsampler = NULL;
short *convertRecvBuffer = NULL;
short *convertSendBuffer = NULL;
RadioInterfaceResamp::RadioInterfaceResamp(RadioDevice *wRadio,
int wReceiveOffset,
int wSPS,
GSM::Time wStartTime)
: RadioInterface(wRadio, wReceiveOffset, wSPS, wStartTime),
innerSendBuffer(NULL), outerSendBuffer(NULL),
innerRecvBuffer(NULL), outerRecvBuffer(NULL)
{
}
RadioInterfaceResamp::~RadioInterfaceResamp()
{
close();
}
void RadioInterfaceResamp::close()
{
RadioInterface::close();
delete innerSendBuffer;
delete outerSendBuffer;
delete innerRecvBuffer;
delete outerRecvBuffer;
delete upsampler;
delete dnsampler;
innerSendBuffer = NULL;
outerSendBuffer = NULL;
innerRecvBuffer = NULL;
outerRecvBuffer = NULL;
upsampler = NULL;
dnsampler = NULL;
}
/* Initialize I/O specific objects */
bool RadioInterfaceResamp::init()
{
float cutoff = 1.0f;
close();
if (mSPSTx == 4)
cutoff = RESAMP_TX4_FILTER;
dnsampler = new Resampler(RESAMP_INRATE, RESAMP_OUTRATE);
if (!dnsampler->init(cutoff)) {
LOG(ALERT) << "Rx resampler failed to initialize";
return false;
}
upsampler = new Resampler(RESAMP_OUTRATE, RESAMP_INRATE);
if (!upsampler->init(cutoff)) {
LOG(ALERT) << "Tx resampler failed to initialize";
return false;
}
/*
* Allocate high and low rate buffers. The high rate receive
* buffer and low rate transmit vectors feed into the resampler
* and requires headroom equivalent to the filter length. Low
* rate buffers are allocated in the main radio interface code.
*/
innerSendBuffer = new signalVector(INCHUNK * 20, RESAMP_FILT_LEN);
outerSendBuffer = new signalVector(OUTCHUNK * 20);
outerRecvBuffer = new signalVector(OUTCHUNK * 2, RESAMP_FILT_LEN);
innerRecvBuffer = new signalVector(INCHUNK * 20);
convertSendBuffer = new short[OUTCHUNK * 2 * 20];
convertRecvBuffer = new short[OUTCHUNK * 2 * 2];
sendBuffer = innerSendBuffer;
recvBuffer = innerRecvBuffer;
return true;
}
/* Receive a timestamped chunk from the device */
void RadioInterfaceResamp::pullBuffer()
{
bool local_underrun;
int rc, num_recv;
int inner_len = INCHUNK;
int outer_len = OUTCHUNK;
/* Outer buffer access size is fixed */
num_recv = mRadio->readSamples(convertRecvBuffer,
outer_len,
&overrun,
readTimestamp,
&local_underrun);
if (num_recv != outer_len) {
LOG(ALERT) << "Receive error " << num_recv;
return;
}
convert_short_float((float *) outerRecvBuffer->begin(),
convertRecvBuffer, 2 * outer_len);
underrun |= local_underrun;
readTimestamp += (TIMESTAMP) num_recv;
/* Write to the end of the inner receive buffer */
rc = dnsampler->rotate((float *) outerRecvBuffer->begin(), outer_len,
(float *) (innerRecvBuffer->begin() + recvCursor),
inner_len);
if (rc < 0) {
LOG(ALERT) << "Sample rate upsampling error";
}
recvCursor += inner_len;
}
/* Send a timestamped chunk to the device */
void RadioInterfaceResamp::pushBuffer()
{
int rc, chunks, num_sent;
int inner_len, outer_len;
if (sendCursor < INCHUNK)
return;
chunks = sendCursor / INCHUNK;
if (chunks > 8)
chunks = 8;
inner_len = chunks * INCHUNK;
outer_len = chunks * OUTCHUNK;
/* Always send from the beginning of the buffer */
rc = upsampler->rotate((float *) innerSendBuffer->begin(), inner_len,
(float *) outerSendBuffer->begin(), outer_len);
if (rc < 0) {
LOG(ALERT) << "Sample rate downsampling error";
}
convert_float_short(convertSendBuffer,
(float *) outerSendBuffer->begin(),
powerScaling, 2 * outer_len);
num_sent = mRadio->writeSamples(convertSendBuffer,
outer_len,
&underrun,
writeTimestamp);
if (num_sent != outer_len) {
LOG(ALERT) << "Transmit error " << num_sent;
}
/* Shift remaining samples to beginning of buffer */
memmove(innerSendBuffer->begin(),
innerSendBuffer->begin() + inner_len,
(sendCursor - inner_len) * 2 * sizeof(float));
writeTimestamp += outer_len;
sendCursor -= inner_len;
assert(sendCursor >= 0);
}
<|endoftext|> |
<commit_before>#include "CodeGen_PTX_Dev.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "Debug.h"
#include "Target.h"
#include "LLVM_Headers.h"
// This is declared in NVPTX.h, which is not exported. Ugly, but seems better than
// hardcoding a path to the .h file.
#if WITH_PTX
namespace llvm { ModulePass *createNVVMReflectPass(const StringMap<int>& Mapping); }
#endif
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using namespace llvm;
CodeGen_PTX_Dev::CodeGen_PTX_Dev() : CodeGen() {
#if !(WITH_PTX)
assert(false && "ptx not enabled for this build of Halide.");
#endif
assert(llvm_NVPTX_enabled && "llvm build not configured with nvptx target enabled.");
}
void CodeGen_PTX_Dev::add_kernel(Stmt stmt, std::string name, const std::vector<Argument> &args) {
debug(2) << "In CodeGen_PTX_Dev::add_kernel\n";
// Now deduce the types of the arguments to our function
vector<llvm::Type *> arg_types(args.size());
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
arg_types[i] = llvm_type_of(UInt(8))->getPointerTo();
} else {
arg_types[i] = llvm_type_of(args[i].type);
}
}
// Make our function
function_name = name;
FunctionType *func_t = FunctionType::get(void_t, arg_types, false);
function = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, name, module);
// Mark the buffer args as no alias
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
function->setDoesNotAlias(i+1);
}
}
// Make the initial basic block
entry_block = BasicBlock::Create(*context, "entry", function);
builder->SetInsertPoint(entry_block);
// Put the arguments in the symbol table
vector<string> arg_sym_names;
{
size_t i = 0;
for (llvm::Function::arg_iterator iter = function->arg_begin();
iter != function->arg_end();
iter++) {
string arg_sym_name = args[i].name;
if (args[i].is_buffer) {
// HACK: codegen expects a load from foo to use base
// address 'foo.host', so we store the device pointer
// as foo.host in this scope.
arg_sym_name += ".host";
}
sym_push(arg_sym_name, iter);
iter->setName(arg_sym_name);
arg_sym_names.push_back(arg_sym_name);
i++;
}
}
// We won't end the entry block yet, because we'll want to add
// some allocas to it later if there are local allocations. Start
// a new block to put all the code.
BasicBlock *body_block = BasicBlock::Create(*context, "body", function);
builder->SetInsertPoint(body_block);
debug(1) << "Generating llvm bitcode for kernel...\n";
// Ok, we have a module, function, context, and a builder
// pointing at a brand new basic block. We're good to go.
stmt.accept(this);
// Now we need to end the function
builder->CreateRetVoid();
// Make the entry block point to the body block
builder->SetInsertPoint(entry_block);
builder->CreateBr(body_block);
// Add the nvvm annotation that it is a kernel function.
MDNode *mdNode = MDNode::get(*context, vec<Value *>(function,
MDString::get(*context, "kernel"),
ConstantInt::get(i32, 1)));
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(mdNode);
// Now verify the function is ok
verifyFunction(*function);
// Finally, verify the module is ok
verifyModule(*module);
debug(2) << "Done generating llvm bitcode for PTX\n";
// Clear the symbol table
for (size_t i = 0; i < arg_sym_names.size(); i++) {
sym_pop(arg_sym_names[i]);
}
}
void CodeGen_PTX_Dev::init_module() {
CodeGen::init_module();
#if WITH_PTX
module = get_initial_module_for_ptx_device(context);
#endif
owns_module = true;
}
string CodeGen_PTX_Dev::simt_intrinsic(const string &name) {
if (ends_with(name, ".threadidx")) {
return "llvm.nvvm.read.ptx.sreg.tid.x";
} else if (ends_with(name, ".threadidy")) {
return "llvm.nvvm.read.ptx.sreg.tid.y";
} else if (ends_with(name, ".threadidz")) {
return "llvm.nvvm.read.ptx.sreg.tid.z";
} else if (ends_with(name, ".threadidw")) {
return "llvm.nvvm.read.ptx.sreg.tid.w";
} else if (ends_with(name, ".blockidx")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.x";
} else if (ends_with(name, ".blockidy")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.y";
} else if (ends_with(name, ".blockidz")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.z";
} else if (ends_with(name, ".blockidw")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.w";
}
assert(false && "simt_intrinsic called on bad variable name");
return "";
}
void CodeGen_PTX_Dev::visit(const For *loop) {
if (is_gpu_var(loop->name)) {
debug(2) << "Dropping loop " << loop->name << " (" << loop->min << ", " << loop->extent << ")\n";
assert(loop->for_type == For::Parallel && "kernel loop must be parallel");
Expr simt_idx = Call::make(Int(32), simt_intrinsic(loop->name), std::vector<Expr>(), Call::Extern);
Expr loop_var = loop->min + simt_idx;
Expr cond = simt_idx < loop->extent;
debug(3) << "for -> if (" << cond << ")\n";
BasicBlock *loop_bb = BasicBlock::Create(*context, loop->name + "_loop", function);
BasicBlock *after_bb = BasicBlock::Create(*context, loop->name + "_after_loop", function);
builder->CreateCondBr(codegen(cond), loop_bb, after_bb);
builder->SetInsertPoint(loop_bb);
sym_push(loop->name, codegen(loop_var));
codegen(loop->body);
sym_pop(loop->name);
builder->CreateBr(after_bb);
builder->SetInsertPoint(after_bb);
} else {
CodeGen::visit(loop);
}
}
void CodeGen_PTX_Dev::visit(const Pipeline *n) {
n->produce.accept(this);
// Grab the syncthreads intrinsic, or declare it if it doesn't exist yet
llvm::Function *syncthreads = module->getFunction("llvm.nvvm.barrier0");
if (!syncthreads) {
FunctionType *func_t = FunctionType::get(llvm::Type::getVoidTy(*context), vector<llvm::Type *>(), false);
syncthreads = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, "llvm.nvvm.barrier0", module);
syncthreads->setCallingConv(CallingConv::C);
debug(2) << "Declaring syncthreads intrinsic\n";
}
if (n->update.defined()) {
// If we're producing into shared or global memory we need a
// syncthreads before continuing.
builder->CreateCall(syncthreads, std::vector<Value *>());
n->update.accept(this);
}
builder->CreateCall(syncthreads, std::vector<Value *>());
n->consume.accept(this);
}
void CodeGen_PTX_Dev::visit(const Allocate *alloc) {
debug(1) << "Allocate " << alloc->name << " on device\n";
llvm::Type *llvm_type = llvm_type_of(alloc->type);
string allocation_name = alloc->name + ".host";
debug(3) << "Pushing allocation called " << allocation_name << " onto the symbol table\n";
// If this is a shared allocation, there should already be a
// pointer into shared memory in the symbol table.
Value *ptr;
Value *offset = sym_get(alloc->name + ".shared_mem", false);
if (offset) {
// Bit-cast it to a shared memory pointer (address-space 3 is shared memory)
ptr = builder->CreateIntToPtr(offset, PointerType::get(llvm_type, 3));
} else {
// Otherwise jump back to the entry and generate an
// alloca. Note that by jumping back we're rendering any
// expression we carry back meaningless, so we had better only
// be dealing with constants here.
const IntImm *size = alloc->size.as<IntImm>();
assert(size && "Only fixed-size allocations are supported on the gpu. Try storing into shared memory instead.");
BasicBlock *here = builder->GetInsertBlock();
builder->SetInsertPoint(entry_block);
ptr = builder->CreateAlloca(llvm_type_of(alloc->type), ConstantInt::get(i32, size->value));
builder->SetInsertPoint(here);
}
sym_push(allocation_name, ptr);
codegen(alloc->body);
}
void CodeGen_PTX_Dev::visit(const Free *f) {
sym_pop(f->name + ".host");
}
string CodeGen_PTX_Dev::march() const {
return "nvptx64";
}
string CodeGen_PTX_Dev::mcpu() const {
return "sm_20";
}
string CodeGen_PTX_Dev::mattrs() const {
return "";
}
bool CodeGen_PTX_Dev::use_soft_float_abi() const {
return false;
}
vector<char> CodeGen_PTX_Dev::compile_to_src() {
#if WITH_PTX
debug(2) << "In CodeGen_PTX_Dev::compile_to_src";
optimize_module();
// DISABLED - hooked in here to force PrintBeforeAll option - seems to be the only way?
/*char* argv[] = { "llc", "-print-before-all" };*/
/*int argc = sizeof(argv)/sizeof(char*);*/
/*cl::ParseCommandLineOptions(argc, argv, "Halide PTX internal compiler\n");*/
// Generic llvm optimizations on the module.
optimize_module();
// Set up TargetTriple
module->setTargetTriple(Triple::normalize(march()+"--"));
Triple TheTriple(module->getTargetTriple());
// Allocate target machine
const std::string MArch = march();
const std::string MCPU = mcpu();
const llvm::Target* TheTarget = 0;
std::string errStr;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), errStr);
assert(TheTarget);
TargetOptions Options;
Options.LessPreciseFPMADOption = true;
Options.PrintMachineCode = false;
Options.NoFramePointerElim = false;
//Options.NoExcessFPPrecision = false;
Options.AllowFPOpFusion = FPOpFusion::Fast;
Options.UnsafeFPMath = true;
Options.NoInfsFPMath = false;
Options.NoNaNsFPMath = false;
Options.HonorSignDependentRoundingFPMathOption = false;
Options.UseSoftFloat = false;
/* if (FloatABIForCalls != FloatABI::Default) */
/* Options.FloatABIType = FloatABIForCalls; */
Options.NoZerosInBSS = false;
#if LLVM_VERSION < 33
Options.JITExceptionHandling = false;
#endif
Options.JITEmitDebugInfo = false;
Options.JITEmitDebugInfoToDisk = false;
Options.GuaranteedTailCallOpt = false;
Options.StackAlignmentOverride = 0;
// Options.DisableJumpTables = false;
Options.TrapFuncName = "";
Options.EnableSegmentedStacks = false;
CodeGenOpt::Level OLvl = CodeGenOpt::Aggressive;
const std::string FeaturesStr = "";
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
MCPU, FeaturesStr, Options,
llvm::Reloc::Default,
llvm::CodeModel::Default,
OLvl));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Set the module's data layout using the target machine.
if (const DataLayout *TD = Target.getDataLayout()) {
module->setDataLayout(TD);
}
// Set up passes
PassManager PM;
TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
PM.add(TLI);
if (target.get()) {
#if LLVM_VERSION < 33
PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
target->getVectorTargetTransformInfo()));
#else
target->addAnalysisPasses(PM);
#endif
}
// Add the target data from the target machine, if it exists, or the module.
#if LLVM_VERSION < 35
if (const DataLayout *TD = Target.getDataLayout()) {
PM.add(new DataLayout(*TD));
} else {
PM.add(new DataLayout(module));
}
#endif
// NVidia's libdevice library uses a __nvvm_reflect to choose
// how to handle denormalized numbers. (The pass replaces calls
// to __nvvm_reflect with a constant via a map lookup. The inliner
// pass then resolves these situations to fast code, often a single
// instruction per decision point.)
//
// The default is (more) IEEE like handling. FTZ mode flushes them
// to zero. (This may only apply to single-precision.)
//
// The libdevice documentation covers other options for math accuracy
// such as replacing division with multiply by the reciprocal and
// use of fused-multiply-add, but they do not seem to be controlled
// by this __nvvvm_reflect mechanism and may be flags to earlier compiler
// passes.
#define kDefaultDenorms 0
#define kFTZDenorms 1
StringMap<int> reflect_mapping;
reflect_mapping[StringRef("__CUDA_FTZ")] = kFTZDenorms;
PM.add(createNVVMReflectPass(reflect_mapping));
// Inlining functions is essential to PTX
PM.add(createAlwaysInlinerPass());
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
// Output string stream
std::string outstr;
raw_string_ostream outs(outstr);
formatted_raw_ostream ostream(outs);
// Ask the target to add backend passes as necessary.
bool fail = Target.addPassesToEmitFile(PM, ostream,
TargetMachine::CGFT_AssemblyFile,
true);
if (fail) {
debug(0) << "Failed to set up passes to emit PTX source\n";
assert(false);
}
PM.run(*module);
ostream.flush();
if (debug::debug_level >= 2) {
module->dump();
}
debug(2) << "Done with CodeGen_PTX_Dev::compile_to_src";
string str = outs.str();
vector<char> buffer(str.begin(), str.end());
buffer.push_back(0);
return buffer;
#else // WITH_PTX
return vector<char>();
#endif
}
string CodeGen_PTX_Dev::get_current_kernel_name() {
return function->getName();
}
void CodeGen_PTX_Dev::dump() {
module->dump();
}
}}
<commit_msg>ptx fix for llvm < 3.5<commit_after>#include "CodeGen_PTX_Dev.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "Debug.h"
#include "Target.h"
#include "LLVM_Headers.h"
// This is declared in NVPTX.h, which is not exported. Ugly, but seems better than
// hardcoding a path to the .h file.
#if WITH_PTX
namespace llvm { ModulePass *createNVVMReflectPass(const StringMap<int>& Mapping); }
#endif
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using namespace llvm;
CodeGen_PTX_Dev::CodeGen_PTX_Dev() : CodeGen() {
#if !(WITH_PTX)
assert(false && "ptx not enabled for this build of Halide.");
#endif
assert(llvm_NVPTX_enabled && "llvm build not configured with nvptx target enabled.");
}
void CodeGen_PTX_Dev::add_kernel(Stmt stmt, std::string name, const std::vector<Argument> &args) {
debug(2) << "In CodeGen_PTX_Dev::add_kernel\n";
// Now deduce the types of the arguments to our function
vector<llvm::Type *> arg_types(args.size());
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
arg_types[i] = llvm_type_of(UInt(8))->getPointerTo();
} else {
arg_types[i] = llvm_type_of(args[i].type);
}
}
// Make our function
function_name = name;
FunctionType *func_t = FunctionType::get(void_t, arg_types, false);
function = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, name, module);
// Mark the buffer args as no alias
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer) {
function->setDoesNotAlias(i+1);
}
}
// Make the initial basic block
entry_block = BasicBlock::Create(*context, "entry", function);
builder->SetInsertPoint(entry_block);
// Put the arguments in the symbol table
vector<string> arg_sym_names;
{
size_t i = 0;
for (llvm::Function::arg_iterator iter = function->arg_begin();
iter != function->arg_end();
iter++) {
string arg_sym_name = args[i].name;
if (args[i].is_buffer) {
// HACK: codegen expects a load from foo to use base
// address 'foo.host', so we store the device pointer
// as foo.host in this scope.
arg_sym_name += ".host";
}
sym_push(arg_sym_name, iter);
iter->setName(arg_sym_name);
arg_sym_names.push_back(arg_sym_name);
i++;
}
}
// We won't end the entry block yet, because we'll want to add
// some allocas to it later if there are local allocations. Start
// a new block to put all the code.
BasicBlock *body_block = BasicBlock::Create(*context, "body", function);
builder->SetInsertPoint(body_block);
debug(1) << "Generating llvm bitcode for kernel...\n";
// Ok, we have a module, function, context, and a builder
// pointing at a brand new basic block. We're good to go.
stmt.accept(this);
// Now we need to end the function
builder->CreateRetVoid();
// Make the entry block point to the body block
builder->SetInsertPoint(entry_block);
builder->CreateBr(body_block);
// Add the nvvm annotation that it is a kernel function.
MDNode *mdNode = MDNode::get(*context, vec<Value *>(function,
MDString::get(*context, "kernel"),
ConstantInt::get(i32, 1)));
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(mdNode);
// Now verify the function is ok
verifyFunction(*function);
// Finally, verify the module is ok
verifyModule(*module);
debug(2) << "Done generating llvm bitcode for PTX\n";
// Clear the symbol table
for (size_t i = 0; i < arg_sym_names.size(); i++) {
sym_pop(arg_sym_names[i]);
}
}
void CodeGen_PTX_Dev::init_module() {
CodeGen::init_module();
#if WITH_PTX
module = get_initial_module_for_ptx_device(context);
#endif
owns_module = true;
}
string CodeGen_PTX_Dev::simt_intrinsic(const string &name) {
if (ends_with(name, ".threadidx")) {
return "llvm.nvvm.read.ptx.sreg.tid.x";
} else if (ends_with(name, ".threadidy")) {
return "llvm.nvvm.read.ptx.sreg.tid.y";
} else if (ends_with(name, ".threadidz")) {
return "llvm.nvvm.read.ptx.sreg.tid.z";
} else if (ends_with(name, ".threadidw")) {
return "llvm.nvvm.read.ptx.sreg.tid.w";
} else if (ends_with(name, ".blockidx")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.x";
} else if (ends_with(name, ".blockidy")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.y";
} else if (ends_with(name, ".blockidz")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.z";
} else if (ends_with(name, ".blockidw")) {
return "llvm.nvvm.read.ptx.sreg.ctaid.w";
}
assert(false && "simt_intrinsic called on bad variable name");
return "";
}
void CodeGen_PTX_Dev::visit(const For *loop) {
if (is_gpu_var(loop->name)) {
debug(2) << "Dropping loop " << loop->name << " (" << loop->min << ", " << loop->extent << ")\n";
assert(loop->for_type == For::Parallel && "kernel loop must be parallel");
Expr simt_idx = Call::make(Int(32), simt_intrinsic(loop->name), std::vector<Expr>(), Call::Extern);
Expr loop_var = loop->min + simt_idx;
Expr cond = simt_idx < loop->extent;
debug(3) << "for -> if (" << cond << ")\n";
BasicBlock *loop_bb = BasicBlock::Create(*context, loop->name + "_loop", function);
BasicBlock *after_bb = BasicBlock::Create(*context, loop->name + "_after_loop", function);
builder->CreateCondBr(codegen(cond), loop_bb, after_bb);
builder->SetInsertPoint(loop_bb);
sym_push(loop->name, codegen(loop_var));
codegen(loop->body);
sym_pop(loop->name);
builder->CreateBr(after_bb);
builder->SetInsertPoint(after_bb);
} else {
CodeGen::visit(loop);
}
}
void CodeGen_PTX_Dev::visit(const Pipeline *n) {
n->produce.accept(this);
// Grab the syncthreads intrinsic, or declare it if it doesn't exist yet
llvm::Function *syncthreads = module->getFunction("llvm.nvvm.barrier0");
if (!syncthreads) {
FunctionType *func_t = FunctionType::get(llvm::Type::getVoidTy(*context), vector<llvm::Type *>(), false);
syncthreads = llvm::Function::Create(func_t, llvm::Function::ExternalLinkage, "llvm.nvvm.barrier0", module);
syncthreads->setCallingConv(CallingConv::C);
debug(2) << "Declaring syncthreads intrinsic\n";
}
if (n->update.defined()) {
// If we're producing into shared or global memory we need a
// syncthreads before continuing.
builder->CreateCall(syncthreads, std::vector<Value *>());
n->update.accept(this);
}
builder->CreateCall(syncthreads, std::vector<Value *>());
n->consume.accept(this);
}
void CodeGen_PTX_Dev::visit(const Allocate *alloc) {
debug(1) << "Allocate " << alloc->name << " on device\n";
llvm::Type *llvm_type = llvm_type_of(alloc->type);
string allocation_name = alloc->name + ".host";
debug(3) << "Pushing allocation called " << allocation_name << " onto the symbol table\n";
// If this is a shared allocation, there should already be a
// pointer into shared memory in the symbol table.
Value *ptr;
Value *offset = sym_get(alloc->name + ".shared_mem", false);
if (offset) {
// Bit-cast it to a shared memory pointer (address-space 3 is shared memory)
ptr = builder->CreateIntToPtr(offset, PointerType::get(llvm_type, 3));
} else {
// Otherwise jump back to the entry and generate an
// alloca. Note that by jumping back we're rendering any
// expression we carry back meaningless, so we had better only
// be dealing with constants here.
const IntImm *size = alloc->size.as<IntImm>();
assert(size && "Only fixed-size allocations are supported on the gpu. Try storing into shared memory instead.");
BasicBlock *here = builder->GetInsertBlock();
builder->SetInsertPoint(entry_block);
ptr = builder->CreateAlloca(llvm_type_of(alloc->type), ConstantInt::get(i32, size->value));
builder->SetInsertPoint(here);
}
sym_push(allocation_name, ptr);
codegen(alloc->body);
}
void CodeGen_PTX_Dev::visit(const Free *f) {
sym_pop(f->name + ".host");
}
string CodeGen_PTX_Dev::march() const {
return "nvptx64";
}
string CodeGen_PTX_Dev::mcpu() const {
return "sm_20";
}
string CodeGen_PTX_Dev::mattrs() const {
return "";
}
bool CodeGen_PTX_Dev::use_soft_float_abi() const {
return false;
}
vector<char> CodeGen_PTX_Dev::compile_to_src() {
#if WITH_PTX
debug(2) << "In CodeGen_PTX_Dev::compile_to_src";
optimize_module();
// DISABLED - hooked in here to force PrintBeforeAll option - seems to be the only way?
/*char* argv[] = { "llc", "-print-before-all" };*/
/*int argc = sizeof(argv)/sizeof(char*);*/
/*cl::ParseCommandLineOptions(argc, argv, "Halide PTX internal compiler\n");*/
// Generic llvm optimizations on the module.
optimize_module();
// Set up TargetTriple
module->setTargetTriple(Triple::normalize(march()+"--"));
Triple TheTriple(module->getTargetTriple());
// Allocate target machine
const std::string MArch = march();
const std::string MCPU = mcpu();
const llvm::Target* TheTarget = 0;
std::string errStr;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), errStr);
assert(TheTarget);
TargetOptions Options;
Options.LessPreciseFPMADOption = true;
Options.PrintMachineCode = false;
Options.NoFramePointerElim = false;
//Options.NoExcessFPPrecision = false;
Options.AllowFPOpFusion = FPOpFusion::Fast;
Options.UnsafeFPMath = true;
Options.NoInfsFPMath = false;
Options.NoNaNsFPMath = false;
Options.HonorSignDependentRoundingFPMathOption = false;
Options.UseSoftFloat = false;
/* if (FloatABIForCalls != FloatABI::Default) */
/* Options.FloatABIType = FloatABIForCalls; */
Options.NoZerosInBSS = false;
#if LLVM_VERSION < 33
Options.JITExceptionHandling = false;
#endif
Options.JITEmitDebugInfo = false;
Options.JITEmitDebugInfoToDisk = false;
Options.GuaranteedTailCallOpt = false;
Options.StackAlignmentOverride = 0;
// Options.DisableJumpTables = false;
Options.TrapFuncName = "";
Options.EnableSegmentedStacks = false;
CodeGenOpt::Level OLvl = CodeGenOpt::Aggressive;
const std::string FeaturesStr = "";
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(),
MCPU, FeaturesStr, Options,
llvm::Reloc::Default,
llvm::CodeModel::Default,
OLvl));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Set up passes
PassManager PM;
TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
PM.add(TLI);
if (target.get()) {
#if LLVM_VERSION < 33
PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),
target->getVectorTargetTransformInfo()));
#else
target->addAnalysisPasses(PM);
#endif
}
// Add the target data from the target machine, if it exists, or the module.
#if LLVM_VERSION < 35
if (const DataLayout *TD = Target.getDataLayout()) {
PM.add(new DataLayout(*TD));
} else {
PM.add(new DataLayout(module));
}
#else
if (const DataLayout *TD = Target.getDataLayout()) {
module->setDataLayout(TD);
}
#endif
// NVidia's libdevice library uses a __nvvm_reflect to choose
// how to handle denormalized numbers. (The pass replaces calls
// to __nvvm_reflect with a constant via a map lookup. The inliner
// pass then resolves these situations to fast code, often a single
// instruction per decision point.)
//
// The default is (more) IEEE like handling. FTZ mode flushes them
// to zero. (This may only apply to single-precision.)
//
// The libdevice documentation covers other options for math accuracy
// such as replacing division with multiply by the reciprocal and
// use of fused-multiply-add, but they do not seem to be controlled
// by this __nvvvm_reflect mechanism and may be flags to earlier compiler
// passes.
#define kDefaultDenorms 0
#define kFTZDenorms 1
StringMap<int> reflect_mapping;
reflect_mapping[StringRef("__CUDA_FTZ")] = kFTZDenorms;
PM.add(createNVVMReflectPass(reflect_mapping));
// Inlining functions is essential to PTX
PM.add(createAlwaysInlinerPass());
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
// Output string stream
std::string outstr;
raw_string_ostream outs(outstr);
formatted_raw_ostream ostream(outs);
// Ask the target to add backend passes as necessary.
bool fail = Target.addPassesToEmitFile(PM, ostream,
TargetMachine::CGFT_AssemblyFile,
true);
if (fail) {
debug(0) << "Failed to set up passes to emit PTX source\n";
assert(false);
}
PM.run(*module);
ostream.flush();
if (debug::debug_level >= 2) {
module->dump();
}
debug(2) << "Done with CodeGen_PTX_Dev::compile_to_src";
string str = outs.str();
vector<char> buffer(str.begin(), str.end());
buffer.push_back(0);
return buffer;
#else // WITH_PTX
return vector<char>();
#endif
}
string CodeGen_PTX_Dev::get_current_kernel_name() {
return function->getName();
}
void CodeGen_PTX_Dev::dump() {
module->dump();
}
}}
<|endoftext|> |
<commit_before>#include "DactApplication.hh"
#include <QFileOpenEvent>
DactApplication::DactApplication(int &argc, char** argv)
:
QApplication(argc, argv),
d_mainWindow(0)
{
//d_mainWindow = new DactMainWindow();
}
void DactApplication::init()
{
d_mainWindow.reset(new MainWindow());
d_mainWindow->show();
}
bool DactApplication::event(QEvent *event)
{
qDebug() << "event" << event->type();
switch (event->type())
{
case QEvent::FileOpen:
{
QFileOpenEvent *fileEvent(static_cast<QFileOpenEvent *>(event));
if (!fileEvent->file().isEmpty())
{
QStringList files;
files << fileEvent->file();
openCorpora(files);
}
else if (!fileEvent->url().isEmpty())
openUrl(fileEvent->url());
else
return false;
return true;
}
default:
return QApplication::event(event);
}
}
void DactApplication::openCorpora(QStringList const &fileNames)
{
d_mainWindow->readCorpora(fileNames);
}
void DactApplication::openMacros(QStringList const &fileNames)
{
d_mainWindow->readMacros(fileNames);
}
void DactApplication::openUrl(QUrl const &url)
{
if (url.scheme() != "dact")
return;
if (url.hasQueryItem("filter"))
{
QByteArray encodedFilter(url.queryItemValue("filter").toUtf8());
d_mainWindow->setFilter(QUrl::fromPercentEncoding(encodedFilter));
}
// Disabled because I don't trust this functionality. I think it can
// be easily abused to let Dact open arbritray files. We then have to
// trust dbxml for doing nothing stupid.
#if 0
if (url.hasQueryItem("corpus"))
{
QStringList fileNames;
foreach (QString fileName, url.allQueryItemValues("corpus"))
{
QByteArray encodedFileName(fileName.toUtf8());
fileNames << QUrl::fromPercentEncoding(encodedFileName);
}
d_mainWindow->readCorpora(fileNames);
}
#endif
}<commit_msg>Remove debug statement.<commit_after>#include "DactApplication.hh"
#include <QFileOpenEvent>
DactApplication::DactApplication(int &argc, char** argv)
:
QApplication(argc, argv),
d_mainWindow(0)
{
//d_mainWindow = new DactMainWindow();
}
void DactApplication::init()
{
d_mainWindow.reset(new MainWindow());
d_mainWindow->show();
}
bool DactApplication::event(QEvent *event)
{
switch (event->type())
{
case QEvent::FileOpen:
{
QFileOpenEvent *fileEvent(static_cast<QFileOpenEvent *>(event));
if (!fileEvent->file().isEmpty())
{
QStringList files;
files << fileEvent->file();
openCorpora(files);
}
else if (!fileEvent->url().isEmpty())
openUrl(fileEvent->url());
else
return false;
return true;
}
default:
return QApplication::event(event);
}
}
void DactApplication::openCorpora(QStringList const &fileNames)
{
d_mainWindow->readCorpora(fileNames);
}
void DactApplication::openMacros(QStringList const &fileNames)
{
d_mainWindow->readMacros(fileNames);
}
void DactApplication::openUrl(QUrl const &url)
{
if (url.scheme() != "dact")
return;
if (url.hasQueryItem("filter"))
{
QByteArray encodedFilter(url.queryItemValue("filter").toUtf8());
d_mainWindow->setFilter(QUrl::fromPercentEncoding(encodedFilter));
}
// Disabled because I don't trust this functionality. I think it can
// be easily abused to let Dact open arbritray files. We then have to
// trust dbxml for doing nothing stupid.
#if 0
if (url.hasQueryItem("corpus"))
{
QStringList fileNames;
foreach (QString fileName, url.allQueryItemValues("corpus"))
{
QByteArray encodedFileName(fileName.toUtf8());
fileNames << QUrl::fromPercentEncoding(encodedFileName);
}
d_mainWindow->readCorpora(fileNames);
}
#endif
}<|endoftext|> |
<commit_before>//
// This file is a part of pomerol - a scientific ED code for obtaining
// properties of a Hubbard model on a finite-size lattice
//
// Copyright (C) 2010-2012 Andrey Antipov <Andrey.E.Antipov@gmail.com>
// Copyright (C) 2010-2012 Igor Krivenko <Igor.S.Krivenko@gmail.com>
//
// pomerol 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.
//
// pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>.
#include"HamiltonianPart.h"
#include"StatesClassification.h"
#include<sstream>
#include<Eigen/Eigenvalues>
#ifdef ENABLE_SAVE_PLAINTEXT
#include<boost/filesystem.hpp>
#include<boost/filesystem/fstream.hpp>
#endif
// class HamiltonianPart
namespace Pomerol{
HamiltonianPart::HamiltonianPart(const IndexClassification& IndexInfo, const IndexHamiltonian &F, const StatesClassification &S, const BlockNumber& Block):
ComputableObject(),
IndexInfo(IndexInfo),
F(F), S(S),
Block(Block), QN(S.getQuantumNumbers(Block))
{
}
void HamiltonianPart::prepare()
{
size_t BlockSize = S.getBlockSize(Block);
H.resize(BlockSize,BlockSize);
H.setZero();
std::map<FockState,MelemType>::const_iterator melem_it;
for(InnerQuantumState right_st=0; right_st<BlockSize; right_st++)
{
FockState ket = S.getFockState(Block,right_st);
std::map<FockState,MelemType> mapStates = F.actRight(ket);
for (melem_it=mapStates.begin(); melem_it!=mapStates.end(); melem_it++) {
FockState bra = melem_it -> first;
MelemType melem = melem_it -> second;
//DEBUG("<" << bra << "|" << melem << "|" << F << "|" << ket << ">");
InnerQuantumState left_st = S.getInnerState(bra);
// if (left_st > right_st) { ERROR("!"); exit(1); };
H(left_st,right_st) = melem;
}
}
// H.triangularView<Eigen::Lower>() = H.triangularView<Eigen::Upper>().transpose();
// assert(MatrixType(H.triangularView<Eigen::Lower>()) == MatrixType(H.triangularView<Eigen::Upper>().transpose()));
assert(H.adjoint() == H);
Status = Prepared;
}
void HamiltonianPart::compute() //method of diagonalization classificated part of Hamiltonian
{
if (Status >= Computed) return;
if (H.rows() == 1) {
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
assert (std::abs(H(0,0) - std::real(H(0,0))) < std::numeric_limits<RealType>::epsilon());
#endif
Eigenvalues.resize(1);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
Eigenvalues << std::real(H(0,0));
#else
Eigenvalues << H(0,0);
#endif
H(0,0) = 1;
}
else {
Eigen::SelfAdjointEigenSolver<MatrixType> Solver(H,Eigen::ComputeEigenvectors);
H = Solver.eigenvectors();
Eigenvalues = Solver.eigenvalues(); // eigenvectors are ready
}
Status = Computed;
}
MelemType HamiltonianPart::getMatrixElement(InnerQuantumState m, InnerQuantumState n) const //return H(m,n)
{
return H(m,n);
}
RealType HamiltonianPart::getEigenValue(InnerQuantumState state) const // return Eigenvalues(state)
{
if ( Status < Computed ) throw (exStatusMismatch());
return Eigenvalues(state);
}
const RealVectorType& HamiltonianPart::getEigenValues() const
{
if ( Status < Computed ) throw (exStatusMismatch());
return Eigenvalues;
}
InnerQuantumState HamiltonianPart::getSize(void) const
{
return S.getBlockSize(Block);
}
BlockNumber HamiltonianPart::getBlockNumber(void) const
{
return S.getBlockNumber(QN);
}
QuantumNumbers HamiltonianPart::getQuantumNumbers(void) const
{
return QN;
}
void HamiltonianPart::print_to_screen() const
{
INFO(H << std::endl);
}
const MatrixType& HamiltonianPart::getMatrix() const
{
return H;
}
VectorType HamiltonianPart::getEigenState(InnerQuantumState state) const
{
if ( Status < Computed ) throw (exStatusMismatch());
return H.col(state);
}
RealType HamiltonianPart::getMinimumEigenvalue() const
{
if ( Status < Computed ) throw (exStatusMismatch());
return Eigenvalues.minCoeff();
}
bool HamiltonianPart::reduce(RealType ActualCutoff)
{
if ( Status < Computed ) throw (exStatusMismatch());
InnerQuantumState counter=0;
for (counter=0; (counter< (unsigned int)Eigenvalues.size() && Eigenvalues[counter]<=ActualCutoff); ++counter){};
std::cout << "Left " << counter << " eigenvalues : " << std::endl;
if (counter)
{std::cout << Eigenvalues.head(counter) << std::endl << "_________" << std::endl;
Eigenvalues = Eigenvalues.head(counter);
H = H.topLeftCorner(counter,counter);
return true;
}
else return false;
}
#ifdef ENABLE_SAVE_PLAINTEXT
bool HamiltonianPart::savetxt(const boost::filesystem::path &path1)
{
boost::filesystem::create_directory(path1);
boost::filesystem::fstream out;
if (Status >= Computed) {
out.open(path1 / boost::filesystem::path("evals.dat"),std::ios_base::out);
out << Eigenvalues << std::endl;
out.close();
out.open(path1 / boost::filesystem::path("evals_shift.dat"),std::ios_base::out);
out << __num_format<RealVectorType>(Eigenvalues - RealMatrixType::Identity(Eigenvalues.size(),Eigenvalues.size()).diagonal()*getMinimumEigenvalue()) << std::endl;
out.close();
};
if (Status >= Prepared) {
out.open(path1 / boost::filesystem::path("evecs.dat"),std::ios_base::out);
out << H << std::endl;
out.close();
};
out.open(path1 / boost::filesystem::path("info.dat"),std::ios_base::out);
out << "Quantum numbers: " << QN << std::endl;
out << "Block number: " << Block << std::endl;
out.close();
return true;
}
#endif
} // end of namespace Pomerol
<commit_msg>More tolerant check for Hamiltonian being self-adjoint.<commit_after>//
// This file is a part of pomerol - a scientific ED code for obtaining
// properties of a Hubbard model on a finite-size lattice
//
// Copyright (C) 2010-2012 Andrey Antipov <Andrey.E.Antipov@gmail.com>
// Copyright (C) 2010-2012 Igor Krivenko <Igor.S.Krivenko@gmail.com>
//
// pomerol 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.
//
// pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>.
#include"HamiltonianPart.h"
#include"StatesClassification.h"
#include<sstream>
#include<Eigen/Eigenvalues>
#ifdef ENABLE_SAVE_PLAINTEXT
#include<boost/filesystem.hpp>
#include<boost/filesystem/fstream.hpp>
#endif
// class HamiltonianPart
namespace Pomerol{
HamiltonianPart::HamiltonianPart(const IndexClassification& IndexInfo, const IndexHamiltonian &F, const StatesClassification &S, const BlockNumber& Block):
ComputableObject(),
IndexInfo(IndexInfo),
F(F), S(S),
Block(Block), QN(S.getQuantumNumbers(Block))
{
}
void HamiltonianPart::prepare()
{
size_t BlockSize = S.getBlockSize(Block);
H.resize(BlockSize,BlockSize);
H.setZero();
std::map<FockState,MelemType>::const_iterator melem_it;
for(InnerQuantumState right_st=0; right_st<BlockSize; right_st++)
{
FockState ket = S.getFockState(Block,right_st);
std::map<FockState,MelemType> mapStates = F.actRight(ket);
for (melem_it=mapStates.begin(); melem_it!=mapStates.end(); melem_it++) {
FockState bra = melem_it -> first;
MelemType melem = melem_it -> second;
//DEBUG("<" << bra << "|" << melem << "|" << F << "|" << ket << ">");
InnerQuantumState left_st = S.getInnerState(bra);
// if (left_st > right_st) { ERROR("!"); exit(1); };
H(left_st,right_st) = melem;
}
}
// H.triangularView<Eigen::Lower>() = H.triangularView<Eigen::Upper>().transpose();
// assert(MatrixType(H.triangularView<Eigen::Lower>()) == MatrixType(H.triangularView<Eigen::Upper>().transpose()));
assert((H.adjoint() - H).array().abs().maxCoeff() < 100*std::numeric_limits<RealType>::epsilon());
Status = Prepared;
}
void HamiltonianPart::compute() //method of diagonalization classificated part of Hamiltonian
{
if (Status >= Computed) return;
if (H.rows() == 1) {
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
assert (std::abs(H(0,0) - std::real(H(0,0))) < std::numeric_limits<RealType>::epsilon());
#endif
Eigenvalues.resize(1);
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENS
Eigenvalues << std::real(H(0,0));
#else
Eigenvalues << H(0,0);
#endif
H(0,0) = 1;
}
else {
Eigen::SelfAdjointEigenSolver<MatrixType> Solver(H,Eigen::ComputeEigenvectors);
H = Solver.eigenvectors();
Eigenvalues = Solver.eigenvalues(); // eigenvectors are ready
}
Status = Computed;
}
MelemType HamiltonianPart::getMatrixElement(InnerQuantumState m, InnerQuantumState n) const //return H(m,n)
{
return H(m,n);
}
RealType HamiltonianPart::getEigenValue(InnerQuantumState state) const // return Eigenvalues(state)
{
if ( Status < Computed ) throw (exStatusMismatch());
return Eigenvalues(state);
}
const RealVectorType& HamiltonianPart::getEigenValues() const
{
if ( Status < Computed ) throw (exStatusMismatch());
return Eigenvalues;
}
InnerQuantumState HamiltonianPart::getSize(void) const
{
return S.getBlockSize(Block);
}
BlockNumber HamiltonianPart::getBlockNumber(void) const
{
return S.getBlockNumber(QN);
}
QuantumNumbers HamiltonianPart::getQuantumNumbers(void) const
{
return QN;
}
void HamiltonianPart::print_to_screen() const
{
INFO(H << std::endl);
}
const MatrixType& HamiltonianPart::getMatrix() const
{
return H;
}
VectorType HamiltonianPart::getEigenState(InnerQuantumState state) const
{
if ( Status < Computed ) throw (exStatusMismatch());
return H.col(state);
}
RealType HamiltonianPart::getMinimumEigenvalue() const
{
if ( Status < Computed ) throw (exStatusMismatch());
return Eigenvalues.minCoeff();
}
bool HamiltonianPart::reduce(RealType ActualCutoff)
{
if ( Status < Computed ) throw (exStatusMismatch());
InnerQuantumState counter=0;
for (counter=0; (counter< (unsigned int)Eigenvalues.size() && Eigenvalues[counter]<=ActualCutoff); ++counter){};
std::cout << "Left " << counter << " eigenvalues : " << std::endl;
if (counter)
{std::cout << Eigenvalues.head(counter) << std::endl << "_________" << std::endl;
Eigenvalues = Eigenvalues.head(counter);
H = H.topLeftCorner(counter,counter);
return true;
}
else return false;
}
#ifdef ENABLE_SAVE_PLAINTEXT
bool HamiltonianPart::savetxt(const boost::filesystem::path &path1)
{
boost::filesystem::create_directory(path1);
boost::filesystem::fstream out;
if (Status >= Computed) {
out.open(path1 / boost::filesystem::path("evals.dat"),std::ios_base::out);
out << Eigenvalues << std::endl;
out.close();
out.open(path1 / boost::filesystem::path("evals_shift.dat"),std::ios_base::out);
out << __num_format<RealVectorType>(Eigenvalues - RealMatrixType::Identity(Eigenvalues.size(),Eigenvalues.size()).diagonal()*getMinimumEigenvalue()) << std::endl;
out.close();
};
if (Status >= Prepared) {
out.open(path1 / boost::filesystem::path("evecs.dat"),std::ios_base::out);
out << H << std::endl;
out.close();
};
out.open(path1 / boost::filesystem::path("info.dat"),std::ios_base::out);
out << "Quantum numbers: " << QN << std::endl;
out << "Block number: " << Block << std::endl;
out.close();
return true;
}
#endif
} // end of namespace Pomerol
<|endoftext|> |
<commit_before>#include "Moves/Pawn_Move.h"
#include "Moves/Move.h"
#include "Game/Board.h"
Pawn_Move::Pawn_Move(Color color_in) : Move(0, (color_in == WHITE ? 1 : -1))
{
}
Pawn_Move::~Pawn_Move()
{
}
bool Pawn_Move::move_specific_legal(const Board& board, char file_start, int rank_start) const
{
return rank_start != (rank_change() == 1 ? 7 : 2); // not promoting
}
bool Pawn_Move::can_capture() const
{
return false;
}
void Pawn_Move::side_effects(Board& board, char /* file_start */, int /* rank_start */) const
{
board.repeat_count.clear();
}
std::string Pawn_Move::name() const
{
return "Pawn Move";
}
std::string Pawn_Move::game_record_item(const Board& board, char file_start, int rank_start) const
{
return Move::game_record_item(board, file_start, rank_start);
}
<commit_msg>Comment out unused parameters in Pawn_Move::move_specific_legal()<commit_after>#include "Moves/Pawn_Move.h"
#include "Moves/Move.h"
#include "Game/Board.h"
Pawn_Move::Pawn_Move(Color color_in) : Move(0, (color_in == WHITE ? 1 : -1))
{
}
Pawn_Move::~Pawn_Move()
{
}
bool Pawn_Move::move_specific_legal(const Board& /* board */, char /* file_start */, int rank_start) const
{
return rank_start != (rank_change() == 1 ? 7 : 2); // not promoting
}
bool Pawn_Move::can_capture() const
{
return false;
}
void Pawn_Move::side_effects(Board& board, char /* file_start */, int /* rank_start */) const
{
board.repeat_count.clear();
}
std::string Pawn_Move::name() const
{
return "Pawn Move";
}
std::string Pawn_Move::game_record_item(const Board& board, char file_start, int rank_start) const
{
return Move::game_record_item(board, file_start, rank_start);
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2020-2022 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>
#include <modules/base/algorithm/volume/volumevoronoi.h>
#include <inviwo/core/datastructures/volume/volume.h>
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/util/indexmapper.h>
namespace inviwo {
constexpr auto clamp3D = Wrapping3D{Wrapping::Clamp, Wrapping::Clamp, Wrapping::Clamp};
namespace {
class Entity : public StructuredGridEntity<3> {
public:
Entity(size3_t dimensions)
: StructuredGridEntity<3>{dimensions, vec3{1.0f, 1.0f, 1.0f}}, dimensions{dimensions} {}
virtual Entity* clone() const override { return new Entity(*this); }
virtual size3_t getDimensions() const override { return dimensions; }
size3_t dimensions;
};
} // namespace
TEST(VolumeVoronoi, Voronoi_NoSeedPoints_ThrowsException) {
EXPECT_THROW(util::voronoiSegmentation(
/*volumeDimensions*/ size3_t{3, 3, 3},
/*indexToDataMatrix*/ mat4(), /*dataToModelMatrix*/ mat4(), /*seedPoints*/ {},
/*wrapping*/ clamp3D,
/*weights*/ std::nullopt),
inviwo::Exception);
}
TEST(VolumeVoronoi, WeightedVoronoi_WeightsAndSeedPointsDimensionMissmatch_ThrowsException) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{0.3, 0.2, 0.1}},
{2, vec3{0.1, 0.2, 0.3}}};
const std::vector<float> weights = {3.0, 4.0, 5.0, 6.0, 7.0};
Entity entity{size3_t{3, 3, 3}};
EXPECT_THROW(util::voronoiSegmentation(entity.getDimensions(),
entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, clamp3D, weights),
inviwo::Exception);
}
TEST(VolumeVoronoi, Voronoi_OneSeedPoint_WholeVolumeHasSameIndex) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{1, 1, 1}}};
Entity entity{size3_t{3, 3, 3}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::nullopt);
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
for (size_t x = 0; x < dim.x; x++) {
const auto val = static_cast<unsigned short>(data[im(x, y, z)]);
EXPECT_EQ(val, seedPoints[0].first);
}
}
}
}
TEST(VolumeVoronoi, Voronoi_TwoSeedPoints_PartitionsVolumeInTwo) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{1, 2, 2}},
{2, vec3{2, 2, 2}}};
Entity entity{size3_t{4, 4, 4}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::nullopt);
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
// First half of volume
for (size_t x1 = 0; x1 < dim.x / 2; x1++) {
const auto val1 = static_cast<unsigned short>(data[im(x1, y, z)]);
EXPECT_EQ(val1, seedPoints[0].first);
}
// Second half of volume
for (size_t x2 = dim.x / 2; x2 < dim.x; x2++) {
const auto val2 = static_cast<unsigned short>(data[im(x2, y, z)]);
EXPECT_EQ(val2, seedPoints[1].first);
}
}
}
}
TEST(VolumeVoronoi, WeightedVoronoi_TwoSeedPointsWithWeights_PartitionsVolumeInTwoWeightedParts) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{1, 2, 2}},
{2, vec3{2, 2, 2}}};
Entity entity{size3_t{4, 4, 4}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::vector<float>{1.0, 2.0});
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
// First part (smaller due to smaller weight)
for (size_t x1 = 0; x1 < dim.x / 4; x1++) {
const auto val1 = static_cast<unsigned short>(data[im(x1, y, z)]);
EXPECT_EQ(val1, seedPoints[0].first);
}
// Second part (larger due to larger weight)
for (size_t x2 = dim.x / 4; x2 < dim.x; x2++) {
const auto val2 = static_cast<unsigned short>(data[im(x2, y, z)]);
EXPECT_EQ(val2, seedPoints[1].first);
}
}
}
}
TEST(VolumeVoronoi, Voronoi_ThreeSeedPoints_PartitionsVolumeInThree) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {
{1, vec3{0, 1, 1}}, {2, vec3{1, 1, 1}}, {3, vec3{2, 1, 1}}};
Entity entity{size3_t{3, 3, 3}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::nullopt);
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
// First part
for (size_t x1 = 0; x1 < dim.x / 3; x1++) {
const auto val1 = static_cast<unsigned short>(data[im(x1, y, z)]);
EXPECT_EQ(val1, seedPoints[0].first);
}
// Second part
for (size_t x2 = dim.x / 3; x2 < 2 * dim.x / 3; x2++) {
const auto val2 = static_cast<unsigned short>(data[im(x2, y, z)]);
EXPECT_EQ(val2, seedPoints[1].first);
}
// Third part
for (size_t x3 = 2 * dim.x / 3; x3 < dim.x; x3++) {
const auto val3 = static_cast<unsigned short>(data[im(x3, y, z)]);
EXPECT_EQ(val3, seedPoints[2].first);
}
}
}
}
} // namespace inviwo
<commit_msg>Base: unittest fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2020-2022 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>
#include <modules/base/algorithm/volume/volumevoronoi.h>
#include <inviwo/core/datastructures/volume/volume.h>
#include <inviwo/core/datastructures/volume/volumeram.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/util/indexmapper.h>
namespace inviwo {
constexpr auto clamp3D = Wrapping3D{Wrapping::Clamp, Wrapping::Clamp, Wrapping::Clamp};
namespace {
class Entity : public StructuredGridEntity<3> {
public:
Entity(size3_t dimensions)
: StructuredGridEntity<3>{dimensions, vec3{1.0f, 1.0f, 1.0f}}, dimensions{dimensions} {}
virtual Entity* clone() const override { return new Entity(*this); }
virtual size3_t getDimensions() const override { return dimensions; }
size3_t dimensions;
};
} // namespace
TEST(VolumeVoronoi, Voronoi_NoSeedPoints_ThrowsException) {
EXPECT_THROW(util::voronoiSegmentation(
/*volumeDimensions*/ size3_t{3, 3, 3},
/*indexToDataMatrix*/ mat4(), /*dataToModelMatrix*/ mat4(), /*seedPoints*/ {},
/*wrapping*/ clamp3D,
/*weights*/ std::nullopt),
inviwo::Exception);
}
TEST(VolumeVoronoi, WeightedVoronoi_WeightsAndSeedPointsDimensionMissmatch_ThrowsException) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{0.3, 0.2, 0.1}},
{2, vec3{0.1, 0.2, 0.3}}};
const std::vector<float> weights = {3.0, 4.0, 5.0, 6.0, 7.0};
Entity entity{size3_t{3, 3, 3}};
EXPECT_THROW(util::voronoiSegmentation(entity.getDimensions(),
entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, clamp3D, weights),
inviwo::Exception);
}
TEST(VolumeVoronoi, Voronoi_OneSeedPoint_WholeVolumeHasSameIndex) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{1, 1, 1}}};
Entity entity{size3_t{3, 3, 3}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::nullopt);
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
for (size_t x = 0; x < dim.x; x++) {
const auto val = static_cast<unsigned short>(data[im(x, y, z)]);
EXPECT_EQ(val, seedPoints[0].first);
}
}
}
}
/*
*
* 2 ▲ ┌─────┬─────┬─────┬─────┐
* │ │ 1 │ 1 │ 2 │ 2 │
* │ 3│ │ │ │ │
* │ ├─────┼─────┼─────┼─────┤
* │ │ 1 │ 1 │ 2 │ 2 │
* │ 2│ │ │ │ │
* 0 │ ├─────X─────┼─────Y─────┤
* │ │ 1 │ 1 │ 2 │ 2 │
* │ 1│ │ │ │ │
* │ ├─────┼─────┼─────┼─────┤
* │ │ 1 │ 1 │ 2 │ 2 │
* │ 0│ │ │ │ │
* -2 ┼ └─────┴─────┴─────┴─────┘
* 0 1 2 3
* ┼───────────────────────▶
* -2 0 2
*/
TEST(VolumeVoronoi, Voronoi_TwoSeedPoints_PartitionsVolumeInTwo) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{-1, 0, 0}},
{2, vec3{1, 0, 0}}};
Entity entity{size3_t{4, 4, 4}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::nullopt);
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
// First half of volume
for (size_t x1 = 0; x1 < dim.x / 2; x1++) {
const auto val1 = static_cast<unsigned short>(data[im(x1, y, z)]);
EXPECT_EQ(val1, seedPoints[0].first) << "pos " << x1 << ", " << y << ", " << z;
}
// Second half of volume
for (size_t x2 = dim.x / 2; x2 < dim.x; x2++) {
const auto val2 = static_cast<unsigned short>(data[im(x2, y, z)]);
EXPECT_EQ(val2, seedPoints[1].first) << "pos " << x2 << ", " << y << ", " << z;
}
}
}
}
TEST(VolumeVoronoi, WeightedVoronoi_TwoSeedPointsWithWeights_PartitionsVolumeInTwoWeightedParts) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{-1, 0, 0}},
{2, vec3{1, 0, 0}}};
Entity entity{size3_t{4, 4, 4}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::vector<float>{1.0, 2.0});
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
// First part (smaller due to smaller weight)
for (size_t x1 = 0; x1 < dim.x / 4; x1++) {
const auto val1 = static_cast<unsigned short>(data[im(x1, y, z)]);
EXPECT_EQ(val1, seedPoints[0].first) << "pos " << x1 << ", " << y << ", " << z;
}
// Second part (larger due to larger weight)
for (size_t x2 = dim.x / 4; x2 < dim.x; x2++) {
const auto val2 = static_cast<unsigned short>(data[im(x2, y, z)]);
EXPECT_EQ(val2, seedPoints[1].first) << "pos " << x2 << ", " << y << ", " << z;
}
}
}
}
TEST(VolumeVoronoi, Voronoi_ThreeSeedPoints_PartitionsVolumeInThree) {
const std::vector<std::pair<uint32_t, vec3>> seedPoints = {
{1, vec3{-1.5, 0, 0}}, {2, vec3{0, 0, 0}}, {3, vec3{1.5, 0, 0}}};
Entity entity{size3_t{3, 3, 3}};
auto volumeVoronoi = util::voronoiSegmentation(
entity.getDimensions(), entity.getCoordinateTransformer().getIndexToDataMatrix(),
entity.getCoordinateTransformer().getDataToModelMatrix(),
seedPoints, /*wrapping*/ clamp3D, /*weights*/ std::nullopt);
const VolumeRAMPrecision<unsigned short>* ramtyped =
dynamic_cast<const VolumeRAMPrecision<unsigned short>*>(
volumeVoronoi->getRepresentation<VolumeRAM>());
EXPECT_TRUE(ramtyped != nullptr);
const auto data = ramtyped->getDataTyped();
const auto dim = entity.getDimensions();
const util::IndexMapper3D im(dim);
for (size_t z = 0; z < dim.z; z++) {
for (size_t y = 0; y < dim.y; y++) {
// First part
for (size_t x1 = 0; x1 < dim.x / 3; x1++) {
const auto val1 = static_cast<unsigned short>(data[im(x1, y, z)]);
EXPECT_EQ(val1, seedPoints[0].first);
}
// Second part
for (size_t x2 = dim.x / 3; x2 < 2 * dim.x / 3; x2++) {
const auto val2 = static_cast<unsigned short>(data[im(x2, y, z)]);
EXPECT_EQ(val2, seedPoints[1].first);
}
// Third part
for (size_t x3 = 2 * dim.x / 3; x3 < dim.x; x3++) {
const auto val3 = static_cast<unsigned short>(data[im(x3, y, z)]);
EXPECT_EQ(val3, seedPoints[2].first);
}
}
}
}
} // namespace inviwo
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2016 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "meshrenderprocessorgl.h"
#include <modules/opengl/geometry/meshgl.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/interaction/trackball.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/rendering/meshdrawerfactory.h>
#include <modules/opengl/rendering/meshdrawergl.h>
#include <inviwo/core/processors/processor.h>
#include <modules/opengl/shader/shader.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/openglutils.h>
#include <limits>
namespace inviwo {
const ProcessorInfo MeshRenderProcessorGL::processorInfo_{
"org.inviwo.GeometryRenderGL", // Class identifier
"Mesh Renderer", // Display name
"Mesh Rendering", // Category
CodeState::Stable, // Code state
Tags::GL, // Tags
};
const ProcessorInfo MeshRenderProcessorGL::getProcessorInfo() const { return processorInfo_; }
MeshRenderProcessorGL::MeshRenderProcessorGL()
: Processor()
, inport_("geometry")
, imageInport_("imageInport")
, outport_("image")
, camera_("camera", "Camera", vec3(0.0f, 0.0f, -2.0f), vec3(0.0f, 0.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f), &inport_)
, centerViewOnGeometry_("centerView", "Center view on geometry")
, setNearFarPlane_("setNearFarPlane", "Calculate Near and Far Plane")
, resetViewParams_("resetView", "Reset Camera")
, trackball_(&camera_)
, overrideColorBuffer_("overrideColorBuffer", "Override Color Buffer", false,
InvalidationLevel::InvalidResources)
, overrideColor_("overrideColor", "Override Color", vec4(0.75f, 0.75f, 0.75f, 1.0f), vec4(0.0f),
vec4(1.0f))
, geomProperties_("geometry", "Geometry Rendering Properties")
, cullFace_("cullFace", "Cull Face")
, polygonMode_("polygonMode", "Polygon Mode")
, renderPointSize_("renderPointSize", "Point Size", 1.0f, 0.001f, 15.0f, 0.001f)
, renderLineWidth_("renderLineWidth", "Line Width", 1.0f, 0.001f, 15.0f, 0.001f)
, enableDepthTest_("enableDepthTest_","Enable Depth Test" , true)
, lightingProperty_("lighting", "Lighting", &camera_)
, layers_("layers", "Output Layers")
, colorLayer_("colorLayer", "Color", true, InvalidationLevel::InvalidResources)
, texCoordLayer_("texCoordLayer", "Texture Coordinates", false,
InvalidationLevel::InvalidResources)
, normalsLayer_("normalsLayer", "Normals (World Space)", false,
InvalidationLevel::InvalidResources)
, viewNormalsLayer_("viewNormalsLayer", "Normals (View space)", false,
InvalidationLevel::InvalidResources)
, shader_("geometryrendering.vert", "geometryrendering.frag", false) {
addPort(inport_);
addPort(imageInport_);
addPort(outport_);
imageInport_.setOptional(true);
addProperty(camera_);
centerViewOnGeometry_.onChange(this, &MeshRenderProcessorGL::centerViewOnGeometry);
addProperty(centerViewOnGeometry_);
setNearFarPlane_.onChange(this, &MeshRenderProcessorGL::setNearFarPlane);
addProperty(setNearFarPlane_);
resetViewParams_.onChange([this]() { camera_.resetCamera(); });
addProperty(resetViewParams_);
outport_.addResizeEventListener(&camera_);
inport_.onChange(this, &MeshRenderProcessorGL::updateDrawers);
cullFace_.addOption("culldisable", "Disable", GL_NONE);
cullFace_.addOption("cullfront", "Front", GL_FRONT);
cullFace_.addOption("cullback", "Back", GL_BACK);
cullFace_.addOption("cullfrontback", "Front & Back", GL_FRONT_AND_BACK);
cullFace_.set(GL_NONE);
polygonMode_.addOption("polypoint", "Points", GL_POINT);
polygonMode_.addOption("polyline", "Lines", GL_LINE);
polygonMode_.addOption("polyfill", "Fill", GL_FILL);
polygonMode_.set(GL_FILL);
polygonMode_.onChange(this, &MeshRenderProcessorGL::changeRenderMode);
geomProperties_.addProperty(cullFace_);
geomProperties_.addProperty(polygonMode_);
geomProperties_.addProperty(renderPointSize_);
geomProperties_.addProperty(renderLineWidth_);
geomProperties_.addProperty(enableDepthTest_);
geomProperties_.addProperty(overrideColorBuffer_);
geomProperties_.addProperty(overrideColor_);
overrideColor_.setSemantics(PropertySemantics::Color);
overrideColor_.setVisible(false);
overrideColorBuffer_.onChange([&]() { overrideColor_.setVisible(overrideColorBuffer_.get()); });
float lineWidthRange[2];
float increment;
glGetFloatv(GL_LINE_WIDTH_RANGE, lineWidthRange);
glGetFloatv(GL_LINE_WIDTH_GRANULARITY, &increment);
renderLineWidth_.setMinValue(lineWidthRange[0]);
renderLineWidth_.setMaxValue(lineWidthRange[1]);
renderLineWidth_.setIncrement(increment);
renderLineWidth_.setVisible(false);
renderPointSize_.setVisible(false);
addProperty(geomProperties_);
addProperty(lightingProperty_);
addProperty(trackball_);
addProperty(layers_);
layers_.addProperty(colorLayer_);
layers_.addProperty(texCoordLayer_);
layers_.addProperty(normalsLayer_);
layers_.addProperty(viewNormalsLayer_);
setAllPropertiesCurrentStateAsDefault();
}
MeshRenderProcessorGL::~MeshRenderProcessorGL() {}
void MeshRenderProcessorGL::initializeResources() { addCommonShaderDefines(shader_); }
void MeshRenderProcessorGL::addCommonShaderDefines(Shader& shader) {
// shading defines
utilgl::addShaderDefines(shader, lightingProperty_);
if (overrideColorBuffer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("OVERRIDE_COLOR_BUFFER");
} else {
shader.getFragmentShaderObject()->removeShaderDefine("OVERRIDE_COLOR_BUFFER");
}
if (colorLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("COLOR_LAYER");
} else {
shader.getFragmentShaderObject()->removeShaderDefine("COLOR_LAYER");
}
// first two layers (color and picking) are reserved, but picking buffer will be removed since it is not drawn to
int layerID = 1;
if (texCoordLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("TEXCOORD_LAYER");
shader.getFragmentShaderObject()->addOutDeclaration("tex_coord_out", layerID);
layerID++;
} else {
shader.getFragmentShaderObject()->removeShaderDefine("TEXCOORD_LAYER");
}
if (normalsLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("NORMALS_LAYER");
shader.getFragmentShaderObject()->addOutDeclaration("normals_out", layerID);
layerID++;
} else {
shader.getFragmentShaderObject()->removeShaderDefine("NORMALS_LAYER");
}
if (viewNormalsLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("VIEW_NORMALS_LAYER");
shader.getFragmentShaderObject()->addOutDeclaration("view_normals_out", layerID);
layerID++;
} else {
shader.getFragmentShaderObject()->removeShaderDefine("VIEW_NORMALS_LAYER");
}
// get a hold of the current output data
auto prevData = outport_.getData();
auto numLayers = static_cast<std::size_t>(layerID);
if (prevData->getNumberOfColorLayers() != numLayers) {
// create new image with matching number of layers
auto image = std::make_shared<Image>(prevData->getDimensions(), prevData->getDataFormat());
// update number of layers
for (auto i = image->getNumberOfColorLayers(); i < numLayers; ++i) {
image->addColorLayer(std::shared_ptr<Layer>(image->getColorLayer(0)->clone()));
}
outport_.setData(image);
}
shader.build();
}
void MeshRenderProcessorGL::changeRenderMode() {
switch (polygonMode_.get()) {
case GL_FILL: {
renderLineWidth_.setVisible(false);
renderPointSize_.setVisible(false);
break;
}
case GL_LINE: {
renderLineWidth_.setVisible(true);
renderPointSize_.setVisible(false);
break;
}
case GL_POINT: {
renderLineWidth_.setVisible(false);
renderPointSize_.setVisible(true);
break;
}
}
}
void MeshRenderProcessorGL::process() {
if (imageInport_.isConnected()) {
utilgl::activateTargetAndCopySource(outport_, imageInport_);
} else {
utilgl::activateAndClearTarget(outport_, ImageType::ColorDepth);
}
shader_.activate();
utilgl::setShaderUniforms(shader_, camera_, "camera_");
utilgl::setShaderUniforms(shader_, lightingProperty_, "light_");
utilgl::setShaderUniforms(shader_, overrideColor_);
utilgl::GlBoolState depthTest(GL_DEPTH_TEST, enableDepthTest_.get());
utilgl::CullFaceState culling(cullFace_.get());
utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_);
for (auto& drawer : drawers_) {
utilgl::setShaderUniforms(shader_, *(drawer.second->getMesh()), "geometry_");
drawer.second->draw();
}
shader_.deactivate();
utilgl::deactivateCurrentTarget();
}
void MeshRenderProcessorGL::centerViewOnGeometry() {
if (!inport_.hasData()) return;
vec3 worldMin(std::numeric_limits<float>::max());
vec3 worldMax(std::numeric_limits<float>::lowest());
for (const auto& mesh : inport_) {
vec3 minPos(std::numeric_limits<float>::max());
vec3 maxPos(std::numeric_limits<float>::lowest());
for (auto buff : mesh->getBuffers()) {
if (buff.first.type == BufferType::PositionAttrib) {
const Vec3BufferRAM* posbuff =
dynamic_cast<const Vec3BufferRAM*>(buff.second->getRepresentation<BufferRAM>());
if (posbuff) {
const std::vector<vec3>* pos = posbuff->getDataContainer();
for (const auto& p : *pos) {
minPos = glm::min(minPos, p);
maxPos = glm::max(maxPos, p);
}
}
}
}
mat4 trans = mesh->getCoordinateTransformer().getDataToWorldMatrix();
worldMin = glm::min(worldMin, (trans * vec4(minPos, 1.f)).xyz());
worldMax = glm::max(worldMax, (trans * vec4(maxPos, 1.f)).xyz());
}
camera_.setLook(camera_.getLookFrom(), 0.5f * (worldMin + worldMax), camera_.getLookUp());
}
void MeshRenderProcessorGL::setNearFarPlane() {
if (!inport_.hasData()) return;
auto geom = inport_.getData();
auto posBuffer =
dynamic_cast<const Vec3BufferRAM*>(geom->getBuffer(0)->getRepresentation<BufferRAM>());
if (posBuffer == nullptr) return;
auto pos = posBuffer->getDataContainer();
if (pos->empty()) return;
float nearDist, farDist;
nearDist = std::numeric_limits<float>::infinity();
farDist = 0;
vec3 nearPos, farPos;
vec3 camPos = (geom->getCoordinateTransformer().getWorldToModelMatrix() *
vec4(camera_.getLookFrom(), 1.0))
.xyz();
for (auto& po : *pos) {
auto d = glm::distance2(po, camPos);
if (d < nearDist) {
nearDist = d;
nearPos = po;
}
if (d > farDist) {
farDist = d;
farPos = po;
}
}
mat4 m = camera_.viewMatrix() * geom->getCoordinateTransformer().getModelToWorldMatrix();
camera_.setNearPlaneDist(std::max(0.0f, 0.99f * std::abs((m * vec4(nearPos, 1.0f)).z)));
camera_.setFarPlaneDist(std::max(0.0f, 1.01f * std::abs((m * vec4(farPos, 1.0f)).z)));
}
void MeshRenderProcessorGL::updateDrawers() {
auto changed = inport_.getChangedOutports();
DrawerMap temp;
std::swap(temp, drawers_);
std::map<const Outport*, std::vector<std::shared_ptr<const Mesh>>> data;
for (auto& elem : inport_.getSourceVectorData()) {
data[elem.first].push_back(elem.second);
}
for (auto elem : data) {
auto ibegin = temp.lower_bound(elem.first);
auto iend = temp.upper_bound(elem.first);
if (util::contains(changed, elem.first) || ibegin == temp.end() ||
static_cast<long>(elem.second.size()) !=
std::distance(ibegin, iend)) { // data is changed or new.
for (auto geo : elem.second) {
auto factory = getNetwork()->getApplication()->getMeshDrawerFactory();
if (auto renderer = factory->create(geo.get())) {
drawers_.emplace(std::make_pair(elem.first, std::move(renderer)));
}
}
} else { // reuse the old data.
drawers_.insert(std::make_move_iterator(ibegin), std::make_move_iterator(iend));
}
}
}
} // namespace
<commit_msg>BaseGL: Mesh render processor to use correct default camera<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2016 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "meshrenderprocessorgl.h"
#include <modules/opengl/geometry/meshgl.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/interaction/trackball.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/rendering/meshdrawerfactory.h>
#include <modules/opengl/rendering/meshdrawergl.h>
#include <inviwo/core/processors/processor.h>
#include <modules/opengl/shader/shader.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/openglutils.h>
#include <limits>
namespace inviwo {
const ProcessorInfo MeshRenderProcessorGL::processorInfo_{
"org.inviwo.GeometryRenderGL", // Class identifier
"Mesh Renderer", // Display name
"Mesh Rendering", // Category
CodeState::Stable, // Code state
Tags::GL, // Tags
};
const ProcessorInfo MeshRenderProcessorGL::getProcessorInfo() const { return processorInfo_; }
MeshRenderProcessorGL::MeshRenderProcessorGL()
: Processor()
, inport_("geometry")
, imageInport_("imageInport")
, outport_("image")
, camera_("camera", "Camera", vec3(0.0f, 0.0f, 2.0f), vec3(0.0f, 0.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f), &inport_)
, centerViewOnGeometry_("centerView", "Center view on geometry")
, setNearFarPlane_("setNearFarPlane", "Calculate Near and Far Plane")
, resetViewParams_("resetView", "Reset Camera")
, trackball_(&camera_)
, overrideColorBuffer_("overrideColorBuffer", "Override Color Buffer", false,
InvalidationLevel::InvalidResources)
, overrideColor_("overrideColor", "Override Color", vec4(0.75f, 0.75f, 0.75f, 1.0f), vec4(0.0f),
vec4(1.0f))
, geomProperties_("geometry", "Geometry Rendering Properties")
, cullFace_("cullFace", "Cull Face")
, polygonMode_("polygonMode", "Polygon Mode")
, renderPointSize_("renderPointSize", "Point Size", 1.0f, 0.001f, 15.0f, 0.001f)
, renderLineWidth_("renderLineWidth", "Line Width", 1.0f, 0.001f, 15.0f, 0.001f)
, enableDepthTest_("enableDepthTest_","Enable Depth Test" , true)
, lightingProperty_("lighting", "Lighting", &camera_)
, layers_("layers", "Output Layers")
, colorLayer_("colorLayer", "Color", true, InvalidationLevel::InvalidResources)
, texCoordLayer_("texCoordLayer", "Texture Coordinates", false,
InvalidationLevel::InvalidResources)
, normalsLayer_("normalsLayer", "Normals (World Space)", false,
InvalidationLevel::InvalidResources)
, viewNormalsLayer_("viewNormalsLayer", "Normals (View space)", false,
InvalidationLevel::InvalidResources)
, shader_("geometryrendering.vert", "geometryrendering.frag", false) {
addPort(inport_);
addPort(imageInport_);
addPort(outport_);
imageInport_.setOptional(true);
addProperty(camera_);
centerViewOnGeometry_.onChange(this, &MeshRenderProcessorGL::centerViewOnGeometry);
addProperty(centerViewOnGeometry_);
setNearFarPlane_.onChange(this, &MeshRenderProcessorGL::setNearFarPlane);
addProperty(setNearFarPlane_);
resetViewParams_.onChange([this]() { camera_.resetCamera(); });
addProperty(resetViewParams_);
outport_.addResizeEventListener(&camera_);
inport_.onChange(this, &MeshRenderProcessorGL::updateDrawers);
cullFace_.addOption("culldisable", "Disable", GL_NONE);
cullFace_.addOption("cullfront", "Front", GL_FRONT);
cullFace_.addOption("cullback", "Back", GL_BACK);
cullFace_.addOption("cullfrontback", "Front & Back", GL_FRONT_AND_BACK);
cullFace_.set(GL_NONE);
polygonMode_.addOption("polypoint", "Points", GL_POINT);
polygonMode_.addOption("polyline", "Lines", GL_LINE);
polygonMode_.addOption("polyfill", "Fill", GL_FILL);
polygonMode_.set(GL_FILL);
polygonMode_.onChange(this, &MeshRenderProcessorGL::changeRenderMode);
geomProperties_.addProperty(cullFace_);
geomProperties_.addProperty(polygonMode_);
geomProperties_.addProperty(renderPointSize_);
geomProperties_.addProperty(renderLineWidth_);
geomProperties_.addProperty(enableDepthTest_);
geomProperties_.addProperty(overrideColorBuffer_);
geomProperties_.addProperty(overrideColor_);
overrideColor_.setSemantics(PropertySemantics::Color);
overrideColor_.setVisible(false);
overrideColorBuffer_.onChange([&]() { overrideColor_.setVisible(overrideColorBuffer_.get()); });
float lineWidthRange[2];
float increment;
glGetFloatv(GL_LINE_WIDTH_RANGE, lineWidthRange);
glGetFloatv(GL_LINE_WIDTH_GRANULARITY, &increment);
renderLineWidth_.setMinValue(lineWidthRange[0]);
renderLineWidth_.setMaxValue(lineWidthRange[1]);
renderLineWidth_.setIncrement(increment);
renderLineWidth_.setVisible(false);
renderPointSize_.setVisible(false);
addProperty(geomProperties_);
addProperty(lightingProperty_);
addProperty(trackball_);
addProperty(layers_);
layers_.addProperty(colorLayer_);
layers_.addProperty(texCoordLayer_);
layers_.addProperty(normalsLayer_);
layers_.addProperty(viewNormalsLayer_);
setAllPropertiesCurrentStateAsDefault();
}
MeshRenderProcessorGL::~MeshRenderProcessorGL() {}
void MeshRenderProcessorGL::initializeResources() { addCommonShaderDefines(shader_); }
void MeshRenderProcessorGL::addCommonShaderDefines(Shader& shader) {
// shading defines
utilgl::addShaderDefines(shader, lightingProperty_);
if (overrideColorBuffer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("OVERRIDE_COLOR_BUFFER");
} else {
shader.getFragmentShaderObject()->removeShaderDefine("OVERRIDE_COLOR_BUFFER");
}
if (colorLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("COLOR_LAYER");
} else {
shader.getFragmentShaderObject()->removeShaderDefine("COLOR_LAYER");
}
// first two layers (color and picking) are reserved, but picking buffer will be removed since it is not drawn to
int layerID = 1;
if (texCoordLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("TEXCOORD_LAYER");
shader.getFragmentShaderObject()->addOutDeclaration("tex_coord_out", layerID);
layerID++;
} else {
shader.getFragmentShaderObject()->removeShaderDefine("TEXCOORD_LAYER");
}
if (normalsLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("NORMALS_LAYER");
shader.getFragmentShaderObject()->addOutDeclaration("normals_out", layerID);
layerID++;
} else {
shader.getFragmentShaderObject()->removeShaderDefine("NORMALS_LAYER");
}
if (viewNormalsLayer_.get()) {
shader.getFragmentShaderObject()->addShaderDefine("VIEW_NORMALS_LAYER");
shader.getFragmentShaderObject()->addOutDeclaration("view_normals_out", layerID);
layerID++;
} else {
shader.getFragmentShaderObject()->removeShaderDefine("VIEW_NORMALS_LAYER");
}
// get a hold of the current output data
auto prevData = outport_.getData();
auto numLayers = static_cast<std::size_t>(layerID);
if (prevData->getNumberOfColorLayers() != numLayers) {
// create new image with matching number of layers
auto image = std::make_shared<Image>(prevData->getDimensions(), prevData->getDataFormat());
// update number of layers
for (auto i = image->getNumberOfColorLayers(); i < numLayers; ++i) {
image->addColorLayer(std::shared_ptr<Layer>(image->getColorLayer(0)->clone()));
}
outport_.setData(image);
}
shader.build();
}
void MeshRenderProcessorGL::changeRenderMode() {
switch (polygonMode_.get()) {
case GL_FILL: {
renderLineWidth_.setVisible(false);
renderPointSize_.setVisible(false);
break;
}
case GL_LINE: {
renderLineWidth_.setVisible(true);
renderPointSize_.setVisible(false);
break;
}
case GL_POINT: {
renderLineWidth_.setVisible(false);
renderPointSize_.setVisible(true);
break;
}
}
}
void MeshRenderProcessorGL::process() {
if (imageInport_.isConnected()) {
utilgl::activateTargetAndCopySource(outport_, imageInport_);
} else {
utilgl::activateAndClearTarget(outport_, ImageType::ColorDepth);
}
shader_.activate();
utilgl::setShaderUniforms(shader_, camera_, "camera_");
utilgl::setShaderUniforms(shader_, lightingProperty_, "light_");
utilgl::setShaderUniforms(shader_, overrideColor_);
utilgl::GlBoolState depthTest(GL_DEPTH_TEST, enableDepthTest_.get());
utilgl::CullFaceState culling(cullFace_.get());
utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_);
for (auto& drawer : drawers_) {
utilgl::setShaderUniforms(shader_, *(drawer.second->getMesh()), "geometry_");
drawer.second->draw();
}
shader_.deactivate();
utilgl::deactivateCurrentTarget();
}
void MeshRenderProcessorGL::centerViewOnGeometry() {
if (!inport_.hasData()) return;
vec3 worldMin(std::numeric_limits<float>::max());
vec3 worldMax(std::numeric_limits<float>::lowest());
for (const auto& mesh : inport_) {
vec3 minPos(std::numeric_limits<float>::max());
vec3 maxPos(std::numeric_limits<float>::lowest());
for (auto buff : mesh->getBuffers()) {
if (buff.first.type == BufferType::PositionAttrib) {
const Vec3BufferRAM* posbuff =
dynamic_cast<const Vec3BufferRAM*>(buff.second->getRepresentation<BufferRAM>());
if (posbuff) {
const std::vector<vec3>* pos = posbuff->getDataContainer();
for (const auto& p : *pos) {
minPos = glm::min(minPos, p);
maxPos = glm::max(maxPos, p);
}
}
}
}
mat4 trans = mesh->getCoordinateTransformer().getDataToWorldMatrix();
worldMin = glm::min(worldMin, (trans * vec4(minPos, 1.f)).xyz());
worldMax = glm::max(worldMax, (trans * vec4(maxPos, 1.f)).xyz());
}
camera_.setLook(camera_.getLookFrom(), 0.5f * (worldMin + worldMax), camera_.getLookUp());
}
void MeshRenderProcessorGL::setNearFarPlane() {
if (!inport_.hasData()) return;
auto geom = inport_.getData();
auto posBuffer =
dynamic_cast<const Vec3BufferRAM*>(geom->getBuffer(0)->getRepresentation<BufferRAM>());
if (posBuffer == nullptr) return;
auto pos = posBuffer->getDataContainer();
if (pos->empty()) return;
float nearDist, farDist;
nearDist = std::numeric_limits<float>::infinity();
farDist = 0;
vec3 nearPos, farPos;
vec3 camPos = (geom->getCoordinateTransformer().getWorldToModelMatrix() *
vec4(camera_.getLookFrom(), 1.0))
.xyz();
for (auto& po : *pos) {
auto d = glm::distance2(po, camPos);
if (d < nearDist) {
nearDist = d;
nearPos = po;
}
if (d > farDist) {
farDist = d;
farPos = po;
}
}
mat4 m = camera_.viewMatrix() * geom->getCoordinateTransformer().getModelToWorldMatrix();
camera_.setNearPlaneDist(std::max(0.0f, 0.99f * std::abs((m * vec4(nearPos, 1.0f)).z)));
camera_.setFarPlaneDist(std::max(0.0f, 1.01f * std::abs((m * vec4(farPos, 1.0f)).z)));
}
void MeshRenderProcessorGL::updateDrawers() {
auto changed = inport_.getChangedOutports();
DrawerMap temp;
std::swap(temp, drawers_);
std::map<const Outport*, std::vector<std::shared_ptr<const Mesh>>> data;
for (auto& elem : inport_.getSourceVectorData()) {
data[elem.first].push_back(elem.second);
}
for (auto elem : data) {
auto ibegin = temp.lower_bound(elem.first);
auto iend = temp.upper_bound(elem.first);
if (util::contains(changed, elem.first) || ibegin == temp.end() ||
static_cast<long>(elem.second.size()) !=
std::distance(ibegin, iend)) { // data is changed or new.
for (auto geo : elem.second) {
auto factory = getNetwork()->getApplication()->getMeshDrawerFactory();
if (auto renderer = factory->create(geo.get())) {
drawers_.emplace(std::make_pair(elem.first, std::move(renderer)));
}
}
} else { // reuse the old data.
drawers_.insert(std::make_move_iterator(ibegin), std::make_move_iterator(iend));
}
}
}
} // namespace
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "cpasterplugin.h"
#include "splitter.h"
#include "pasteview.h"
#include "codepasterprotocol.h"
#include "kdepasteprotocol.h"
#include "pastebindotcomprotocol.h"
#include "pastebindotcaprotocol.h"
#include "fileshareprotocol.h"
#include "pasteselectdialog.h"
#include "settingspage.h"
#include "settings.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/id.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <utils/qtcassert.h>
#include <utils/fileutils.h>
#include <texteditor/itexteditor.h>
#include <QtPlugin>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTemporaryFile>
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QMenu>
#include <QMainWindow>
using namespace Core;
using namespace TextEditor;
namespace CodePaster {
/*!
\class CodePaster::CodePasterService
\brief Service registered with PluginManager providing CodePaster
post() functionality.
\sa ExtensionSystem::PluginManager::getObjectByClassName, ExtensionSystem::invoke
\sa VcsBase::VcsBaseEditorWidget
*/
CodePasterService::CodePasterService(QObject *parent) :
QObject(parent)
{
}
void CodePasterService::postText(const QString &text, const QString &mimeType)
{
QTC_ASSERT(CodepasterPlugin::instance(), return; )
CodepasterPlugin::instance()->post(text, mimeType);
}
void CodePasterService::postCurrentEditor()
{
QTC_ASSERT(CodepasterPlugin::instance(), return; )
CodepasterPlugin::instance()->postEditor();
}
void CodePasterService::postClipboard()
{
QTC_ASSERT(CodepasterPlugin::instance(), return; )
CodepasterPlugin::instance()->postClipboard();
}
// ---------- CodepasterPlugin
CodepasterPlugin *CodepasterPlugin::m_instance = 0;
CodepasterPlugin::CodepasterPlugin() :
m_settings(new Settings),
m_postEditorAction(0), m_postClipboardAction(0), m_fetchAction(0)
{
CodepasterPlugin::m_instance = this;
}
CodepasterPlugin::~CodepasterPlugin()
{
qDeleteAll(m_protocols);
CodepasterPlugin::m_instance = 0;
}
bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
// Create the globalcontext list to register actions accordingly
Core::Context globalcontext(Core::Constants::C_GLOBAL);
// Create the settings Page
m_settings->fromSettings(Core::ICore::settings());
SettingsPage *settingsPage = new SettingsPage(m_settings);
addAutoReleasedObject(settingsPage);
// Create the protocols and append them to the Settings
const QSharedPointer<NetworkAccessManagerProxy> networkAccessMgrProxy(new NetworkAccessManagerProxy);
Protocol *protos[] = { new PasteBinDotComProtocol(networkAccessMgrProxy),
new PasteBinDotCaProtocol(networkAccessMgrProxy),
new KdePasteProtocol(networkAccessMgrProxy),
new CodePasterProtocol(networkAccessMgrProxy),
new FileShareProtocol
};
const int count = sizeof(protos) / sizeof(Protocol *);
for(int i = 0; i < count; ++i) {
connect(protos[i], SIGNAL(pasteDone(QString)), this, SLOT(finishPost(QString)));
connect(protos[i], SIGNAL(fetchDone(QString,QString,bool)),
this, SLOT(finishFetch(QString,QString,bool)));
settingsPage->addProtocol(protos[i]->name());
if (protos[i]->hasSettings())
addAutoReleasedObject(protos[i]->settingsPage());
m_protocols.append(protos[i]);
}
//register actions
Core::ActionManager *actionManager = ICore::actionManager();
Core::ActionContainer *toolsContainer =
actionManager->actionContainer(Core::Constants::M_TOOLS);
Core::ActionContainer *cpContainer =
actionManager->createMenu(Core::Id("CodePaster"));
cpContainer->menu()->setTitle(tr("&Code Pasting"));
toolsContainer->addMenu(cpContainer);
Core::Command *command;
m_postEditorAction = new QAction(tr("Paste Snippet..."), this);
command = actionManager->registerAction(m_postEditorAction, "CodePaster.Post", globalcontext);
command->setDefaultKeySequence(QKeySequence(tr("Alt+C,Alt+P")));
connect(m_postEditorAction, SIGNAL(triggered()), this, SLOT(postEditor()));
cpContainer->addAction(command);
m_postClipboardAction = new QAction(tr("Paste Clipboard..."), this);
command = actionManager->registerAction(m_postClipboardAction, "CodePaster.PostClipboard", globalcontext);
connect(m_postClipboardAction, SIGNAL(triggered()), this, SLOT(postClipboard()));
cpContainer->addAction(command);
m_fetchAction = new QAction(tr("Fetch Snippet..."), this);
command = actionManager->registerAction(m_fetchAction, "CodePaster.Fetch", globalcontext);
command->setDefaultKeySequence(QKeySequence(tr("Alt+C,Alt+F")));
connect(m_fetchAction, SIGNAL(triggered()), this, SLOT(fetch()));
cpContainer->addAction(command);
addAutoReleasedObject(new CodePasterService);
return true;
}
void CodepasterPlugin::extensionsInitialized()
{
}
ExtensionSystem::IPlugin::ShutdownFlag CodepasterPlugin::aboutToShutdown()
{
// Delete temporary, fetched files
foreach(const QString &fetchedSnippet, m_fetchedSnippets) {
QFile file(fetchedSnippet);
if (file.exists())
file.remove();
}
return SynchronousShutdown;
}
void CodepasterPlugin::postEditor()
{
QString data;
QString mimeType;
if (IEditor* editor = EditorManager::instance()->currentEditor()) {
if (ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor)) {
data = textEditor->selectedText();
if (data.isEmpty())
data = textEditor->contents();
mimeType = textEditor->document()->mimeType();
}
}
post(data, mimeType);
}
void CodepasterPlugin::postClipboard()
{
QString subtype = QLatin1String("plain");
const QString text = qApp->clipboard()->text(subtype, QClipboard::Clipboard);
if (!text.isEmpty())
post(text, QString());
}
static inline void fixSpecialCharacters(QString &data)
{
QChar *uc = data.data();
QChar *e = uc + data.size();
for (; uc != e; ++uc) {
switch (uc->unicode()) {
case 0xfdd0: // QTextBeginningOfFrame
case 0xfdd1: // QTextEndOfFrame
case QChar::ParagraphSeparator:
case QChar::LineSeparator:
*uc = QLatin1Char('\n');
break;
case QChar::Nbsp:
*uc = QLatin1Char(' ');
break;
default:
break;
}
}
}
void CodepasterPlugin::post(QString data, const QString &mimeType)
{
fixSpecialCharacters(data);
const QString username = m_settings->username;
PasteView view(m_protocols, mimeType, 0);
view.setProtocol(m_settings->protocol);
const FileDataList diffChunks = splitDiffToFiles(data);
const int dialogResult = diffChunks.isEmpty() ?
view.show(username, QString(), QString(), data) :
view.show(username, QString(), QString(), diffChunks);
// Save new protocol in case user changed it.
if (dialogResult == QDialog::Accepted
&& m_settings->protocol != view.protocol()) {
m_settings->protocol = view.protocol();
m_settings->toSettings(Core::ICore::settings());
}
}
void CodepasterPlugin::fetch()
{
PasteSelectDialog dialog(m_protocols, ICore::mainWindow());
dialog.setProtocol(m_settings->protocol);
if (dialog.exec() != QDialog::Accepted)
return;
// Save new protocol in case user changed it.
if (m_settings->protocol != dialog.protocol()) {
m_settings->protocol = dialog.protocol();
m_settings->toSettings(Core::ICore::settings());
}
const QString pasteID = dialog.pasteId();
if (pasteID.isEmpty())
return;
Protocol *protocol = m_protocols[dialog.protocolIndex()];
if (Protocol::ensureConfiguration(protocol))
protocol->fetch(pasteID);
}
void CodepasterPlugin::finishPost(const QString &link)
{
if (m_settings->copyToClipboard)
QApplication::clipboard()->setText(link);
ICore::messageManager()->printToOutputPane(link, m_settings->displayOutput);
}
// Extract the characters that can be used for a file name from a title
// "CodePaster.com-34" -> "CodePastercom34".
static inline QString filePrefixFromTitle(const QString &title)
{
QString rc;
const int titleSize = title.size();
rc.reserve(titleSize);
for (int i = 0; i < titleSize; i++)
if (title.at(i).isLetterOrNumber())
rc.append(title.at(i));
if (rc.isEmpty()) {
rc = QLatin1String("qtcreator");
} else {
if (rc.size() > 15)
rc.truncate(15);
}
return rc;
}
// Return a temp file pattern with extension or not
static inline QString tempFilePattern(const QString &prefix, const QString &extension)
{
// Get directory
QString pattern = QDir::tempPath();
if (!pattern.endsWith(QDir::separator()))
pattern.append(QDir::separator());
// Prefix, placeholder, extension
pattern += prefix;
pattern += QLatin1String("_XXXXXX.");
pattern += extension;
return pattern;
}
void CodepasterPlugin::finishFetch(const QString &titleDescription,
const QString &content,
bool error)
{
Core::MessageManager *messageManager = ICore::messageManager();
// Failure?
if (error) {
messageManager->printToOutputPane(content, true);
return;
}
if (content.isEmpty()) {
messageManager->printToOutputPane(tr("Empty snippet received for \"%1\".").arg(titleDescription), true);
return;
}
// If the mime type has a preferred suffix (cpp/h/patch...), use that for
// the temporary file. This is to make it more convenient to "Save as"
// for the user and also to be able to tell a patch or diff in the VCS plugins
// by looking at the file name of DocumentManager::currentFile() without expensive checking.
// Default to "txt".
QByteArray byteContent = content.toUtf8();
QString suffix;
if (const Core::MimeType mimeType = Core::ICore::mimeDatabase()->findByData(byteContent))
suffix = mimeType.preferredSuffix();
if (suffix.isEmpty())
suffix = QLatin1String("txt");
const QString filePrefix = filePrefixFromTitle(titleDescription);
Utils::TempFileSaver saver(tempFilePattern(filePrefix, suffix));
saver.setAutoRemove(false);
saver.write(byteContent);
if (!saver.finalize()) {
messageManager->printToOutputPane(saver.errorString());
return;
}
const QString fileName = saver.fileName();
m_fetchedSnippets.push_back(fileName);
// Open editor with title.
Core::IEditor* editor = EditorManager::instance()->openEditor(fileName, Core::Id(), EditorManager::ModeSwitch);
QTC_ASSERT(editor, return)
editor->setDisplayName(titleDescription);
}
CodepasterPlugin *CodepasterPlugin::instance()
{
return m_instance;
}
} // namespace CodePaster
Q_EXPORT_PLUGIN(CodePaster::CodepasterPlugin)
<commit_msg>Set the parent window correctly for Code paster window.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "cpasterplugin.h"
#include "splitter.h"
#include "pasteview.h"
#include "codepasterprotocol.h"
#include "kdepasteprotocol.h"
#include "pastebindotcomprotocol.h"
#include "pastebindotcaprotocol.h"
#include "fileshareprotocol.h"
#include "pasteselectdialog.h"
#include "settingspage.h"
#include "settings.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/id.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <utils/qtcassert.h>
#include <utils/fileutils.h>
#include <texteditor/itexteditor.h>
#include <QtPlugin>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTemporaryFile>
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QMenu>
#include <QMainWindow>
using namespace Core;
using namespace TextEditor;
namespace CodePaster {
/*!
\class CodePaster::CodePasterService
\brief Service registered with PluginManager providing CodePaster
post() functionality.
\sa ExtensionSystem::PluginManager::getObjectByClassName, ExtensionSystem::invoke
\sa VcsBase::VcsBaseEditorWidget
*/
CodePasterService::CodePasterService(QObject *parent) :
QObject(parent)
{
}
void CodePasterService::postText(const QString &text, const QString &mimeType)
{
QTC_ASSERT(CodepasterPlugin::instance(), return; )
CodepasterPlugin::instance()->post(text, mimeType);
}
void CodePasterService::postCurrentEditor()
{
QTC_ASSERT(CodepasterPlugin::instance(), return; )
CodepasterPlugin::instance()->postEditor();
}
void CodePasterService::postClipboard()
{
QTC_ASSERT(CodepasterPlugin::instance(), return; )
CodepasterPlugin::instance()->postClipboard();
}
// ---------- CodepasterPlugin
CodepasterPlugin *CodepasterPlugin::m_instance = 0;
CodepasterPlugin::CodepasterPlugin() :
m_settings(new Settings),
m_postEditorAction(0), m_postClipboardAction(0), m_fetchAction(0)
{
CodepasterPlugin::m_instance = this;
}
CodepasterPlugin::~CodepasterPlugin()
{
qDeleteAll(m_protocols);
CodepasterPlugin::m_instance = 0;
}
bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
// Create the globalcontext list to register actions accordingly
Core::Context globalcontext(Core::Constants::C_GLOBAL);
// Create the settings Page
m_settings->fromSettings(Core::ICore::settings());
SettingsPage *settingsPage = new SettingsPage(m_settings);
addAutoReleasedObject(settingsPage);
// Create the protocols and append them to the Settings
const QSharedPointer<NetworkAccessManagerProxy> networkAccessMgrProxy(new NetworkAccessManagerProxy);
Protocol *protos[] = { new PasteBinDotComProtocol(networkAccessMgrProxy),
new PasteBinDotCaProtocol(networkAccessMgrProxy),
new KdePasteProtocol(networkAccessMgrProxy),
new CodePasterProtocol(networkAccessMgrProxy),
new FileShareProtocol
};
const int count = sizeof(protos) / sizeof(Protocol *);
for(int i = 0; i < count; ++i) {
connect(protos[i], SIGNAL(pasteDone(QString)), this, SLOT(finishPost(QString)));
connect(protos[i], SIGNAL(fetchDone(QString,QString,bool)),
this, SLOT(finishFetch(QString,QString,bool)));
settingsPage->addProtocol(protos[i]->name());
if (protos[i]->hasSettings())
addAutoReleasedObject(protos[i]->settingsPage());
m_protocols.append(protos[i]);
}
//register actions
Core::ActionManager *actionManager = ICore::actionManager();
Core::ActionContainer *toolsContainer =
actionManager->actionContainer(Core::Constants::M_TOOLS);
Core::ActionContainer *cpContainer =
actionManager->createMenu(Core::Id("CodePaster"));
cpContainer->menu()->setTitle(tr("&Code Pasting"));
toolsContainer->addMenu(cpContainer);
Core::Command *command;
m_postEditorAction = new QAction(tr("Paste Snippet..."), this);
command = actionManager->registerAction(m_postEditorAction, "CodePaster.Post", globalcontext);
command->setDefaultKeySequence(QKeySequence(tr("Alt+C,Alt+P")));
connect(m_postEditorAction, SIGNAL(triggered()), this, SLOT(postEditor()));
cpContainer->addAction(command);
m_postClipboardAction = new QAction(tr("Paste Clipboard..."), this);
command = actionManager->registerAction(m_postClipboardAction, "CodePaster.PostClipboard", globalcontext);
connect(m_postClipboardAction, SIGNAL(triggered()), this, SLOT(postClipboard()));
cpContainer->addAction(command);
m_fetchAction = new QAction(tr("Fetch Snippet..."), this);
command = actionManager->registerAction(m_fetchAction, "CodePaster.Fetch", globalcontext);
command->setDefaultKeySequence(QKeySequence(tr("Alt+C,Alt+F")));
connect(m_fetchAction, SIGNAL(triggered()), this, SLOT(fetch()));
cpContainer->addAction(command);
addAutoReleasedObject(new CodePasterService);
return true;
}
void CodepasterPlugin::extensionsInitialized()
{
}
ExtensionSystem::IPlugin::ShutdownFlag CodepasterPlugin::aboutToShutdown()
{
// Delete temporary, fetched files
foreach(const QString &fetchedSnippet, m_fetchedSnippets) {
QFile file(fetchedSnippet);
if (file.exists())
file.remove();
}
return SynchronousShutdown;
}
void CodepasterPlugin::postEditor()
{
QString data;
QString mimeType;
if (IEditor* editor = EditorManager::instance()->currentEditor()) {
if (ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor)) {
data = textEditor->selectedText();
if (data.isEmpty())
data = textEditor->contents();
mimeType = textEditor->document()->mimeType();
}
}
post(data, mimeType);
}
void CodepasterPlugin::postClipboard()
{
QString subtype = QLatin1String("plain");
const QString text = qApp->clipboard()->text(subtype, QClipboard::Clipboard);
if (!text.isEmpty())
post(text, QString());
}
static inline void fixSpecialCharacters(QString &data)
{
QChar *uc = data.data();
QChar *e = uc + data.size();
for (; uc != e; ++uc) {
switch (uc->unicode()) {
case 0xfdd0: // QTextBeginningOfFrame
case 0xfdd1: // QTextEndOfFrame
case QChar::ParagraphSeparator:
case QChar::LineSeparator:
*uc = QLatin1Char('\n');
break;
case QChar::Nbsp:
*uc = QLatin1Char(' ');
break;
default:
break;
}
}
}
void CodepasterPlugin::post(QString data, const QString &mimeType)
{
fixSpecialCharacters(data);
const QString username = m_settings->username;
PasteView view(m_protocols, mimeType, ICore::mainWindow());
view.setProtocol(m_settings->protocol);
const FileDataList diffChunks = splitDiffToFiles(data);
const int dialogResult = diffChunks.isEmpty() ?
view.show(username, QString(), QString(), data) :
view.show(username, QString(), QString(), diffChunks);
// Save new protocol in case user changed it.
if (dialogResult == QDialog::Accepted
&& m_settings->protocol != view.protocol()) {
m_settings->protocol = view.protocol();
m_settings->toSettings(Core::ICore::settings());
}
}
void CodepasterPlugin::fetch()
{
PasteSelectDialog dialog(m_protocols, ICore::mainWindow());
dialog.setProtocol(m_settings->protocol);
if (dialog.exec() != QDialog::Accepted)
return;
// Save new protocol in case user changed it.
if (m_settings->protocol != dialog.protocol()) {
m_settings->protocol = dialog.protocol();
m_settings->toSettings(Core::ICore::settings());
}
const QString pasteID = dialog.pasteId();
if (pasteID.isEmpty())
return;
Protocol *protocol = m_protocols[dialog.protocolIndex()];
if (Protocol::ensureConfiguration(protocol))
protocol->fetch(pasteID);
}
void CodepasterPlugin::finishPost(const QString &link)
{
if (m_settings->copyToClipboard)
QApplication::clipboard()->setText(link);
ICore::messageManager()->printToOutputPane(link, m_settings->displayOutput);
}
// Extract the characters that can be used for a file name from a title
// "CodePaster.com-34" -> "CodePastercom34".
static inline QString filePrefixFromTitle(const QString &title)
{
QString rc;
const int titleSize = title.size();
rc.reserve(titleSize);
for (int i = 0; i < titleSize; i++)
if (title.at(i).isLetterOrNumber())
rc.append(title.at(i));
if (rc.isEmpty()) {
rc = QLatin1String("qtcreator");
} else {
if (rc.size() > 15)
rc.truncate(15);
}
return rc;
}
// Return a temp file pattern with extension or not
static inline QString tempFilePattern(const QString &prefix, const QString &extension)
{
// Get directory
QString pattern = QDir::tempPath();
if (!pattern.endsWith(QDir::separator()))
pattern.append(QDir::separator());
// Prefix, placeholder, extension
pattern += prefix;
pattern += QLatin1String("_XXXXXX.");
pattern += extension;
return pattern;
}
void CodepasterPlugin::finishFetch(const QString &titleDescription,
const QString &content,
bool error)
{
Core::MessageManager *messageManager = ICore::messageManager();
// Failure?
if (error) {
messageManager->printToOutputPane(content, true);
return;
}
if (content.isEmpty()) {
messageManager->printToOutputPane(tr("Empty snippet received for \"%1\".").arg(titleDescription), true);
return;
}
// If the mime type has a preferred suffix (cpp/h/patch...), use that for
// the temporary file. This is to make it more convenient to "Save as"
// for the user and also to be able to tell a patch or diff in the VCS plugins
// by looking at the file name of DocumentManager::currentFile() without expensive checking.
// Default to "txt".
QByteArray byteContent = content.toUtf8();
QString suffix;
if (const Core::MimeType mimeType = Core::ICore::mimeDatabase()->findByData(byteContent))
suffix = mimeType.preferredSuffix();
if (suffix.isEmpty())
suffix = QLatin1String("txt");
const QString filePrefix = filePrefixFromTitle(titleDescription);
Utils::TempFileSaver saver(tempFilePattern(filePrefix, suffix));
saver.setAutoRemove(false);
saver.write(byteContent);
if (!saver.finalize()) {
messageManager->printToOutputPane(saver.errorString());
return;
}
const QString fileName = saver.fileName();
m_fetchedSnippets.push_back(fileName);
// Open editor with title.
Core::IEditor* editor = EditorManager::instance()->openEditor(fileName, Core::Id(), EditorManager::ModeSwitch);
QTC_ASSERT(editor, return)
editor->setDisplayName(titleDescription);
}
CodepasterPlugin *CodepasterPlugin::instance()
{
return m_instance;
}
} // namespace CodePaster
Q_EXPORT_PLUGIN(CodePaster::CodepasterPlugin)
<|endoftext|> |
<commit_before>// Copyright 2013 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/android/new_tab_page_prefs.h"
#include <jni.h>
#include "base/android/jni_string.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile_android.h"
#include "chrome/common/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "jni/NewTabPagePrefs_jni.h"
using base::android::ConvertJavaStringToUTF8;
static jlong Init(JNIEnv* env, jclass clazz, jobject profile) {
NewTabPagePrefs* new_tab_page_prefs =
new NewTabPagePrefs(ProfileAndroid::FromProfileAndroid(profile));
return reinterpret_cast<intptr_t>(new_tab_page_prefs);
}
NewTabPagePrefs::NewTabPagePrefs(Profile* profile)
: profile_(profile) {
}
void NewTabPagePrefs::Destroy(JNIEnv* env, jobject obj) {
delete this;
}
NewTabPagePrefs::~NewTabPagePrefs() {
}
jboolean NewTabPagePrefs::GetCurrentlyOpenTabsCollapsed(JNIEnv* env,
jobject obj) {
PrefService* prefs = profile_->GetPrefs();
return prefs->GetBoolean(prefs::kNtpCollapsedCurrentlyOpenTabs);
}
void NewTabPagePrefs::SetCurrentlyOpenTabsCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedCurrentlyOpenTabs, is_collapsed);
}
jboolean NewTabPagePrefs::GetSnapshotDocumentCollapsed(JNIEnv* env,
jobject obj) {
return profile_->GetPrefs()->GetBoolean(prefs::kNtpCollapsedSnapshotDocument);
}
void NewTabPagePrefs::SetSnapshotDocumentCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedSnapshotDocument, is_collapsed);
}
jboolean NewTabPagePrefs::GetRecentlyClosedTabsCollapsed(JNIEnv* env,
jobject obj) {
return profile_->GetPrefs()->GetBoolean(
prefs::kNtpCollapsedRecentlyClosedTabs);
}
void NewTabPagePrefs::SetRecentlyClosedTabsCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedRecentlyClosedTabs, is_collapsed);
}
jboolean NewTabPagePrefs::GetSyncPromoCollapsed(JNIEnv* env,
jobject obj) {
return profile_->GetPrefs()->GetBoolean(prefs::kNtpCollapsedSyncPromo);
}
void NewTabPagePrefs::SetSyncPromoCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedSyncPromo, is_collapsed);
}
jboolean NewTabPagePrefs::GetForeignSessionCollapsed(JNIEnv* env,
jobject obj,
jstring session_tag) {
const base::DictionaryValue* dict = profile_->GetPrefs()->GetDictionary(
prefs::kNtpCollapsedForeignSessions);
return dict && dict->HasKey(ConvertJavaStringToUTF8(env, session_tag));
}
void NewTabPagePrefs::SetForeignSessionCollapsed(JNIEnv* env,
jobject obj,
jstring session_tag,
jboolean is_collapsed) {
// Store session tags for collapsed sessions in a preference so that the
// collapsed state persists.
PrefService* prefs = profile_->GetPrefs();
DictionaryPrefUpdate update(prefs, prefs::kNtpCollapsedForeignSessions);
if (is_collapsed)
update.Get()->SetBoolean(ConvertJavaStringToUTF8(env, session_tag), true);
else
update.Get()->Remove(ConvertJavaStringToUTF8(env, session_tag), NULL);
}
// static
void NewTabPagePrefs::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterBooleanPref(
prefs::kNtpCollapsedSnapshotDocument,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kNtpCollapsedRecentlyClosedTabs,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kNtpCollapsedSyncPromo,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDictionaryPref(
prefs::kNtpCollapsedForeignSessions,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDictionaryPref(
prefs::kNtpMostVisitedURLsBlacklist,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
bool NewTabPagePrefs::RegisterNewTabPagePrefs(JNIEnv* env) {
return RegisterNativesImpl(env);
}
<commit_msg>Register newly added pref<commit_after>// Copyright 2013 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/android/new_tab_page_prefs.h"
#include <jni.h>
#include "base/android/jni_string.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile_android.h"
#include "chrome/common/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "jni/NewTabPagePrefs_jni.h"
using base::android::ConvertJavaStringToUTF8;
static jlong Init(JNIEnv* env, jclass clazz, jobject profile) {
NewTabPagePrefs* new_tab_page_prefs =
new NewTabPagePrefs(ProfileAndroid::FromProfileAndroid(profile));
return reinterpret_cast<intptr_t>(new_tab_page_prefs);
}
NewTabPagePrefs::NewTabPagePrefs(Profile* profile)
: profile_(profile) {
}
void NewTabPagePrefs::Destroy(JNIEnv* env, jobject obj) {
delete this;
}
NewTabPagePrefs::~NewTabPagePrefs() {
}
jboolean NewTabPagePrefs::GetCurrentlyOpenTabsCollapsed(JNIEnv* env,
jobject obj) {
PrefService* prefs = profile_->GetPrefs();
return prefs->GetBoolean(prefs::kNtpCollapsedCurrentlyOpenTabs);
}
void NewTabPagePrefs::SetCurrentlyOpenTabsCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedCurrentlyOpenTabs, is_collapsed);
}
jboolean NewTabPagePrefs::GetSnapshotDocumentCollapsed(JNIEnv* env,
jobject obj) {
return profile_->GetPrefs()->GetBoolean(prefs::kNtpCollapsedSnapshotDocument);
}
void NewTabPagePrefs::SetSnapshotDocumentCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedSnapshotDocument, is_collapsed);
}
jboolean NewTabPagePrefs::GetRecentlyClosedTabsCollapsed(JNIEnv* env,
jobject obj) {
return profile_->GetPrefs()->GetBoolean(
prefs::kNtpCollapsedRecentlyClosedTabs);
}
void NewTabPagePrefs::SetRecentlyClosedTabsCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedRecentlyClosedTabs, is_collapsed);
}
jboolean NewTabPagePrefs::GetSyncPromoCollapsed(JNIEnv* env,
jobject obj) {
return profile_->GetPrefs()->GetBoolean(prefs::kNtpCollapsedSyncPromo);
}
void NewTabPagePrefs::SetSyncPromoCollapsed(JNIEnv* env,
jobject obj,
jboolean is_collapsed) {
PrefService* prefs = profile_->GetPrefs();
prefs->SetBoolean(prefs::kNtpCollapsedSyncPromo, is_collapsed);
}
jboolean NewTabPagePrefs::GetForeignSessionCollapsed(JNIEnv* env,
jobject obj,
jstring session_tag) {
const base::DictionaryValue* dict = profile_->GetPrefs()->GetDictionary(
prefs::kNtpCollapsedForeignSessions);
return dict && dict->HasKey(ConvertJavaStringToUTF8(env, session_tag));
}
void NewTabPagePrefs::SetForeignSessionCollapsed(JNIEnv* env,
jobject obj,
jstring session_tag,
jboolean is_collapsed) {
// Store session tags for collapsed sessions in a preference so that the
// collapsed state persists.
PrefService* prefs = profile_->GetPrefs();
DictionaryPrefUpdate update(prefs, prefs::kNtpCollapsedForeignSessions);
if (is_collapsed)
update.Get()->SetBoolean(ConvertJavaStringToUTF8(env, session_tag), true);
else
update.Get()->Remove(ConvertJavaStringToUTF8(env, session_tag), NULL);
}
// static
void NewTabPagePrefs::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterBooleanPref(
prefs::kNtpCollapsedCurrentlyOpenTabs,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kNtpCollapsedSnapshotDocument,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kNtpCollapsedRecentlyClosedTabs,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kNtpCollapsedSyncPromo,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDictionaryPref(
prefs::kNtpCollapsedForeignSessions,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDictionaryPref(
prefs::kNtpMostVisitedURLsBlacklist,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
bool NewTabPagePrefs::RegisterNewTabPagePrefs(JNIEnv* env) {
return RegisterNativesImpl(env);
}
<|endoftext|> |
<commit_before>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// 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.
#include "Step/BaseObject.h"
#include "Step/SPFData.h"
#include "Step/BaseVisitor.h"
using namespace Step;
ClassType_child_implementations(STEP_EXPORT,BaseObject,ClientDataHandler);
BaseObject::BaseObject(SPFData* data) :
m_inited((!data) || (data && (data->argc() == 0))), m_args(data)
{
}
void BaseObject::copy(const BaseObject& obj, const BaseCopyOp& copyop)
{
ClientDataHandler::copy(obj, copyop);
if (!obj.m_inited)
{
BaseObject* bo = const_cast<BaseObject*> (&obj);
bo->inited();
}
}
BaseObject::~BaseObject()
{
if (m_args)
delete m_args;
}
bool BaseObject::acceptVisitor(BaseVisitor *v)
{
return v->visitBaseObject(this);
}
bool BaseObject::inited()
{
if (!m_inited)
{
#ifdef STEP_THREAD_SAFE
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(m_mutex);
#endif
m_inited = true; // set this to break cycle when inverse attribute inits
bool inited = init();
if (inited)
{
delete m_args;
m_args = 0;
}
}
return m_inited;
}
BaseExpressDataSet* BaseObject::getExpressDataSet() const
{
return m_expressDataSet;
}
SPFData* BaseObject::getArgs()
{
return m_args;
}
bool BaseObject::isInited()
{
return m_inited;
}
BaseExpressDataSet * BaseObject::getExpressDataSet()
{
return m_expressDataSet;
}
void BaseObject::setExpressDataSet(BaseExpressDataSet * expressDataSet)
{
m_expressDataSet = expressDataSet;
}
void BaseObject::release()
{
}
<commit_msg>No need to check if a pointer is null before deleting it<commit_after>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// 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.
#include "Step/BaseObject.h"
#include "Step/SPFData.h"
#include "Step/BaseVisitor.h"
using namespace Step;
ClassType_child_implementations(STEP_EXPORT,BaseObject,ClientDataHandler);
BaseObject::BaseObject(SPFData* data) :
m_inited((!data) || (data && (data->argc() == 0))), m_args(data)
{
}
void BaseObject::copy(const BaseObject& obj, const BaseCopyOp& copyop)
{
ClientDataHandler::copy(obj, copyop);
if (!obj.m_inited)
{
BaseObject* bo = const_cast<BaseObject*> (&obj);
bo->inited();
}
}
BaseObject::~BaseObject()
{
delete m_args;
}
bool BaseObject::acceptVisitor(BaseVisitor *v)
{
return v->visitBaseObject(this);
}
bool BaseObject::inited()
{
if (!m_inited)
{
#ifdef STEP_THREAD_SAFE
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(m_mutex);
#endif
m_inited = true; // set this to break cycle when inverse attribute inits
bool inited = init();
if (inited)
{
delete m_args;
m_args = 0;
}
}
return m_inited;
}
BaseExpressDataSet* BaseObject::getExpressDataSet() const
{
return m_expressDataSet;
}
SPFData* BaseObject::getArgs()
{
return m_args;
}
bool BaseObject::isInited()
{
return m_inited;
}
BaseExpressDataSet * BaseObject::getExpressDataSet()
{
return m_expressDataSet;
}
void BaseObject::setExpressDataSet(BaseExpressDataSet * expressDataSet)
{
m_expressDataSet = expressDataSet;
}
void BaseObject::release()
{
}
<|endoftext|> |
<commit_before>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include <iterator>
#include <algorithm>
#include <math.h>
#include "AdaptiveLayerHeights.h"
namespace cura
{
AdaptiveLayer::AdaptiveLayer(int layer_height)
{
this->layer_height = layer_height;
}
AdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)
{
// store the required parameters
this->mesh = mesh;
this->layer_height = layer_thickness;
this->initial_layer_height = initial_layer_thickness;
this->max_variation = static_cast<int>(variation);
this->step_size = static_cast<int>(step_size);
this->threshold = threshold;
// calculate the allowed layer heights from variation and step size
// note: the order is from thickest to thinnest height!
for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)
{
this->allowed_layer_heights.push_back(allowed_layer_height);
}
this->calculateMeshTriangleSlopes();
this->calculateLayers();
}
int AdaptiveLayerHeights::getLayerCount()
{
return this->layers.size();
}
std::vector<AdaptiveLayer>* AdaptiveLayerHeights::getLayers()
{
return &this->layers;
}
void AdaptiveLayerHeights::calculateLayers()
{
const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());
SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance("slicing_tolerance");
std::vector<int> triangles_of_interest;
int z_level = 0;
int previous_layer_height = 0;
// the first layer has it's own independent height set, so we always add that
z_level += this->initial_layer_height;
// compensate first layer thickness depending on slicing mode
if (slicing_tolerance == SlicingTolerance::MIDDLE)
{
z_level += this->initial_layer_height / 2;
this->initial_layer_height += this->initial_layer_height / 2;
}
auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
// loop while triangles are found
while (!triangles_of_interest.empty() || this->layers.size() < 2)
{
// loop over all allowed layer heights starting with the largest
for (auto & layer_height : this->allowed_layer_heights)
{
// use lower and upper bounds to filter on triangles that are interesting for this potential layer
const int lower_bound = z_level;
const int upper_bound = z_level + layer_height;
triangles_of_interest.clear();
for (unsigned int i = 0; i < this->face_min_z_values.size(); ++i)
{
if (this->face_min_z_values[i] <= upper_bound && this->face_max_z_values[i] >= lower_bound)
{
triangles_of_interest.push_back(i);
}
}
// when there not interesting triangles in this potential layer go to the next one
if (triangles_of_interest.empty())
{
break;
}
std::vector<double> slopes;
// find all slopes for interesting triangles
for (auto & triangle_index : triangles_of_interest)
{
double slope = this->face_slopes.at(triangle_index);
slopes.push_back(slope);
}
double minimum_slope = *std::min_element(slopes.begin(), slopes.end());
double minimum_slope_tan = std::tan(minimum_slope);
// check if the maximum step size has been exceeded depending on layer height direction
bool has_exceeded_step_size = false;
if (previous_layer_height > layer_height && previous_layer_height - layer_height > this->step_size)
{
has_exceeded_step_size = true;
}
else if (layer_height - previous_layer_height > this->step_size && layer_height > minimum_layer_height)
{
continue;
}
// we add the layer in the following cases:
// 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size
// 2) the layer height is the smallest it is allowed
// 3) the layer is a flat surface (we can't divide by 0)
if (minimum_slope_tan == 0.0
|| (layer_height / minimum_slope_tan) <= this->threshold
|| layer_height == minimum_layer_height
|| has_exceeded_step_size)
{
z_level += layer_height;
auto * adaptive_layer = new AdaptiveLayer(layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
break;
}
}
// stop calculating when we're out of triangles (e.g. above the mesh)
if (triangles_of_interest.empty())
{
break;
}
}
}
void AdaptiveLayerHeights::calculateMeshTriangleSlopes()
{
// loop over all mesh faces (triangles) and find their slopes
for (const auto &face : this->mesh->faces)
{
const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];
const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];
const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];
FPoint3 p0 = v0.p;
FPoint3 p1 = v1.p;
FPoint3 p2 = v2.p;
float minZ = p0.z;
float maxZ = p0.z;
if (p1.z < minZ) minZ = p1.z;
if (p2.z < minZ) minZ = p2.z;
if (p1.z > maxZ) maxZ = p1.z;
if (p2.z > maxZ) maxZ = p2.z;
// calculate the angle of this triangle in the z direction
FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);
FPoint3 normal = n.normalized();
double z_angle = std::acos(std::abs(normal.z));
// prevent flat surfaces from influencing the algorithm
if (z_angle == 0)
{
z_angle = M_PI;
}
this->face_min_z_values.push_back(minZ * 1000);
this->face_max_z_values.push_back(maxZ * 1000);
this->face_slopes.push_back(z_angle);
}
}
}<commit_msg>Optimize the layer thickness calculation.<commit_after>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include <iterator>
#include <algorithm>
#include <math.h>
#include "AdaptiveLayerHeights.h"
namespace cura
{
AdaptiveLayer::AdaptiveLayer(int layer_height)
{
this->layer_height = layer_height;
}
AdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)
{
// store the required parameters
this->mesh = mesh;
this->layer_height = layer_thickness;
this->initial_layer_height = initial_layer_thickness;
this->max_variation = static_cast<int>(variation);
this->step_size = static_cast<int>(step_size);
this->threshold = threshold;
// calculate the allowed layer heights from variation and step size
// note: the order is from thickest to thinnest height!
for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)
{
this->allowed_layer_heights.push_back(allowed_layer_height);
}
this->calculateMeshTriangleSlopes();
this->calculateLayers();
}
int AdaptiveLayerHeights::getLayerCount()
{
return this->layers.size();
}
std::vector<AdaptiveLayer>* AdaptiveLayerHeights::getLayers()
{
return &this->layers;
}
void AdaptiveLayerHeights::calculateLayers()
{
const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());
SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance("slicing_tolerance");
std::vector<int> triangles_of_interest;
int z_level = 0;
int previous_layer_height = 0;
// the first layer has it's own independent height set, so we always add that
z_level += this->initial_layer_height;
// compensate first layer thickness depending on slicing mode
if (slicing_tolerance == SlicingTolerance::MIDDLE)
{
z_level += this->initial_layer_height / 2;
this->initial_layer_height += this->initial_layer_height / 2;
}
auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
// loop while triangles are found
while (!triangles_of_interest.empty() || this->layers.size() < 2)
{
// loop over all allowed layer heights starting with the largest
for (auto & layer_height : this->allowed_layer_heights)
{
// use lower and upper bounds to filter on triangles that are interesting for this potential layer
const int lower_bound = z_level;
const int upper_bound = z_level + layer_height;
if (layer_height == this->allowed_layer_heights[0])
{
// this is the max layer thickness, search through all of the triangles in the mesh to find those
// that intersect with a layer this thick
triangles_of_interest.clear();
for (unsigned int i = 0; i < this->face_min_z_values.size(); ++i)
{
if (this->face_min_z_values[i] <= upper_bound && this->face_max_z_values[i] >= lower_bound)
{
triangles_of_interest.push_back(i);
}
}
}
else
{
// this is a reduced thickness layer, just search those triangles that intersected with the maximum
// thickness layer
std::vector<int> last_triangles_of_interest = triangles_of_interest;
triangles_of_interest.clear();
for (int i : last_triangles_of_interest)
{
if (this->face_min_z_values[i] <= upper_bound)
{
triangles_of_interest.push_back(i);
}
}
}
// when there not interesting triangles in this potential layer go to the next one
if (triangles_of_interest.empty())
{
break;
}
std::vector<double> slopes;
// find all slopes for interesting triangles
for (auto & triangle_index : triangles_of_interest)
{
double slope = this->face_slopes.at(triangle_index);
slopes.push_back(slope);
}
double minimum_slope = *std::min_element(slopes.begin(), slopes.end());
double minimum_slope_tan = std::tan(minimum_slope);
// check if the maximum step size has been exceeded depending on layer height direction
bool has_exceeded_step_size = false;
if (previous_layer_height > layer_height && previous_layer_height - layer_height > this->step_size)
{
has_exceeded_step_size = true;
}
else if (layer_height - previous_layer_height > this->step_size && layer_height > minimum_layer_height)
{
continue;
}
// we add the layer in the following cases:
// 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size
// 2) the layer height is the smallest it is allowed
// 3) the layer is a flat surface (we can't divide by 0)
if (minimum_slope_tan == 0.0
|| (layer_height / minimum_slope_tan) <= this->threshold
|| layer_height == minimum_layer_height
|| has_exceeded_step_size)
{
z_level += layer_height;
auto * adaptive_layer = new AdaptiveLayer(layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
break;
}
}
// stop calculating when we're out of triangles (e.g. above the mesh)
if (triangles_of_interest.empty())
{
break;
}
}
}
void AdaptiveLayerHeights::calculateMeshTriangleSlopes()
{
// loop over all mesh faces (triangles) and find their slopes
for (const auto &face : this->mesh->faces)
{
const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];
const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];
const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];
FPoint3 p0 = v0.p;
FPoint3 p1 = v1.p;
FPoint3 p2 = v2.p;
float minZ = p0.z;
float maxZ = p0.z;
if (p1.z < minZ) minZ = p1.z;
if (p2.z < minZ) minZ = p2.z;
if (p1.z > maxZ) maxZ = p1.z;
if (p2.z > maxZ) maxZ = p2.z;
// calculate the angle of this triangle in the z direction
FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);
FPoint3 normal = n.normalized();
double z_angle = std::acos(std::abs(normal.z));
// prevent flat surfaces from influencing the algorithm
if (z_angle == 0)
{
z_angle = M_PI;
}
this->face_min_z_values.push_back(minZ * 1000);
this->face_max_z_values.push_back(maxZ * 1000);
this->face_slopes.push_back(z_angle);
}
}
}<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(NAMESPACE_HEADER_GUARD_1357924680)
#define NAMESPACE_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <XalanDOM/XalanDOMString.hpp>
/**
* A representation of a namespace. One of these will be pushed on the
* namespace stack for each element.
*/
class XALAN_XPATH_EXPORT NameSpace
{
public:
/**
* Construct a namespace for placement on the
* result tree namespace stack.
*
* @param prefix namespace prefix
* @param uri URI of namespace
*/
NameSpace(
const XalanDOMString& prefix = XalanDOMString(),
const XalanDOMString& uri = XalanDOMString()) :
m_prefix(prefix),
m_uri(uri),
m_resultCandidate(true)
{
}
/**
* Retrieve the prefix for namespace
*
* @return prefix string
*/
const XalanDOMString&
getPrefix() const
{
return m_prefix;
}
/**
* Retrieve the URI for namespace
*
* @return URI string
*/
const XalanDOMString&
getURI() const
{
return m_uri;
}
/**
* Whether the namespace is a candidate for result namespace.
*
* @return true if it is a candidate
*/
bool
getResultCandidate() const
{
return m_resultCandidate;
}
/**
* Set whether the namespace is a candidate for result namespace.
*
* @param fResultCandidate true to set namespace as candidate
*/
void
setResultCandidate(bool fResultCandidate)
{
m_resultCandidate = fResultCandidate;
}
/**
* Assignment operator, required for STL vector.
*
* @param theRHS namespace to assign
*/
NameSpace&
operator=(const NameSpace& theRHS)
{
if (&theRHS != this)
{
m_prefix = theRHS.m_prefix;
m_uri = theRHS.m_uri;
m_resultCandidate = theRHS.m_resultCandidate;
}
return *this;
}
private:
XalanDOMString m_prefix;
XalanDOMString m_uri; // if length is 0, then Element namespace is empty.
bool m_resultCandidate;
};
#endif // NAMESPACE_HEADER_GUARD_1357924680
<commit_msg>Removed unused member. Add set accessors.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(NAMESPACE_HEADER_GUARD_1357924680)
#define NAMESPACE_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
/**
* A representation of a namespace. One of these will be pushed on the
* namespace stack for each element.
*/
class XALAN_XPATH_EXPORT NameSpace
{
public:
/**
* Construct a namespace for placement on the
* result tree namespace stack.
*
* @param prefix namespace prefix
* @param uri URI of namespace
*/
NameSpace(
const XalanDOMString& prefix = XalanDOMString(),
const XalanDOMString& uri = XalanDOMString()) :
m_prefix(prefix),
m_uri(uri)
{
}
/**
* Retrieve the prefix for namespace
*
* @return prefix string
*/
const XalanDOMString&
getPrefix() const
{
return m_prefix;
}
/**
* Set the prefix for namespace
*
* @param prefix The new prefix value
*/
void
setPrefix(const XalanDOMString& prefix)
{
m_prefix = prefix;
}
/**
* Retrieve the URI for namespace
*
* @return URI string
*/
const XalanDOMString&
getURI() const
{
return m_uri;
}
/**
* Set the URI for namespace
*
* @param uri The new uri value
*/
void
setURI(const XalanDOMString& uri)
{
m_uri = uri;
}
/**
* Equality operator, necessary because DOMString::==()
* has screwy semantics.
*
* @param theRHS namespace to compare
*/
bool
operator==(const NameSpace& theRHS) const
{
return equals(m_prefix, theRHS.m_prefix) &&
equals(m_uri, theRHS.m_uri);
}
private:
XalanDOMString m_prefix;
XalanDOMString m_uri; // if length is 0, then Element namespace is empty.
};
#endif // NAMESPACE_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>#ifndef STAN_SERVICES_UTIL_INITIALIZE_HPP
#define STAN_SERVICES_UTIL_INITIALIZE_HPP
#include <stan/io/var_context.hpp>
#include <stan/io/random_var_context.hpp>
#include <stan/io/chained_var_context.hpp>
#include <stan/model/util.hpp>
#include <sstream>
#include <vector>
namespace stan {
namespace services {
namespace util {
template <class Model, class RNG>
std::vector<double> initialize(Model& model,
stan::io::var_context& init,
RNG& rng,
double init_radius,
bool print_timing,
callbacks::writer::base_writer&
message_writer,
callbacks::writer::base_writer&
init_writer) {
std::vector<double> unconstrained;
std::vector<int> disc_vector;
std::stringstream msg;
bool is_fully_initialized = true;
bool any_initialized = false;
std::vector<std::string> param_names;
model.get_param_names(param_names);
for (size_t n = 0; n < param_names.size(); n++) {
is_fully_initialized &= init.contains_r(param_names[n]);
any_initialized |= init.contains_r(param_names[n]);
}
bool init_zero = init_radius <= std::numeric_limits<double>::min();
int MAX_INIT_TRIES = is_fully_initialized || init_zero ? 1 : 100;
int num_init_tries = 0;
for (; num_init_tries < MAX_INIT_TRIES; num_init_tries++) {
if (!any_initialized) {
stan::io::random_var_context random_context(model, rng, init_radius, init_zero);
unconstrained = random_context.get_unconstrained();
} else {
stan::io::random_var_context random_context(model, rng, init_radius, init_zero);
stan::io::chained_var_context context(init, random_context);
model.transform_inits(context,
disc_vector,
unconstrained,
&msg);
if (msg.str().length() > 0)
message_writer(msg.str());
}
double log_prob(0);
try {
msg.str("");
log_prob = model.template log_prob<false, true>
(unconstrained, disc_vector, &msg);
if (msg.str().length() > 0)
message_writer(msg.str());
} catch (std::exception& e) {
message_writer();
message_writer("Rejecting initial value:");
message_writer(" Error evaluating the log probability "
"at the initial value.");
continue;
}
if (!boost::math::isfinite(log_prob)) {
message_writer("Rejecting initial value:");
message_writer(" Log probability evaluates to log(0), "
"i.e. negative infinity.");
message_writer(" Stan can't start sampling from this "
"initial value.");
continue;
}
msg.str("");
std::vector<double> gradient;
bool gradient_ok = true;
clock_t start_check = clock();
log_prob = stan::model::log_prob_grad<true, true>
(model, unconstrained, disc_vector,
gradient, &msg);
clock_t end_check = clock();
double deltaT = static_cast<double>(end_check - start_check)
/ CLOCKS_PER_SEC;
if (msg.str().length() > 0)
message_writer(msg.str());
for (size_t i = 0; i < gradient.size(); ++i) {
if (gradient_ok && !boost::math::isfinite(gradient[i])) {
message_writer("Rejecting initial value:");
message_writer(" Gradient evaluated at the initial value "
"is not finite.");
message_writer(" Stan can't start sampling from this "
"initial value.");
gradient_ok = false;
}
}
if (gradient_ok && print_timing) {
msg.str("");
message_writer();
msg << "Gradient evaluation took " << deltaT << " seconds";
message_writer(msg.str());
msg.str("");
msg << "1000 transitions using 10 leapfrog steps "
<< "per transition would take "
<< 1e4 * deltaT << " seconds.";
message_writer(msg.str());
msg.str("");
message_writer("Adjust your expectations accordingly!");
message_writer();
message_writer();
}
if (gradient_ok)
break;
}
if (num_init_tries == MAX_INIT_TRIES) {
if (!is_fully_initialized && !init_zero) {
message_writer();
msg.str("");
msg << "Initialization between (-" << init_radius
<< ", " << init_radius << ") failed after "
<< MAX_INIT_TRIES << " attempts. ";
message_writer(msg.str());
message_writer(" Try specifying initial values,"
" reducing ranges of constrained values,"
" or reparameterizing the model.");
}
throw std::domain_error("");
}
init_writer(unconstrained);
return unconstrained;
}
}
}
}
#endif
<commit_msg>cpplint<commit_after>#ifndef STAN_SERVICES_UTIL_INITIALIZE_HPP
#define STAN_SERVICES_UTIL_INITIALIZE_HPP
#include <stan/io/var_context.hpp>
#include <stan/io/random_var_context.hpp>
#include <stan/io/chained_var_context.hpp>
#include <stan/model/util.hpp>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
namespace stan {
namespace services {
namespace util {
template <class Model, class RNG>
std::vector<double> initialize(Model& model,
stan::io::var_context& init,
RNG& rng,
double init_radius,
bool print_timing,
callbacks::writer::base_writer&
message_writer,
callbacks::writer::base_writer&
init_writer) {
std::vector<double> unconstrained;
std::vector<int> disc_vector;
std::stringstream msg;
bool is_fully_initialized = true;
bool any_initialized = false;
std::vector<std::string> param_names;
model.get_param_names(param_names);
for (size_t n = 0; n < param_names.size(); n++) {
is_fully_initialized &= init.contains_r(param_names[n]);
any_initialized |= init.contains_r(param_names[n]);
}
bool init_zero = init_radius <= std::numeric_limits<double>::min();
int MAX_INIT_TRIES = is_fully_initialized || init_zero ? 1 : 100;
int num_init_tries = 0;
for (; num_init_tries < MAX_INIT_TRIES; num_init_tries++) {
stan::io::random_var_context
random_context(model, rng, init_radius, init_zero);
if (!any_initialized) {
unconstrained = random_context.get_unconstrained();
} else {
stan::io::chained_var_context context(init, random_context);
model.transform_inits(context,
disc_vector,
unconstrained,
&msg);
if (msg.str().length() > 0)
message_writer(msg.str());
}
double log_prob(0);
try {
msg.str("");
log_prob = model.template log_prob<false, true>
(unconstrained, disc_vector, &msg);
if (msg.str().length() > 0)
message_writer(msg.str());
} catch (std::exception& e) {
message_writer();
message_writer("Rejecting initial value:");
message_writer(" Error evaluating the log probability "
"at the initial value.");
continue;
}
if (!boost::math::isfinite(log_prob)) {
message_writer("Rejecting initial value:");
message_writer(" Log probability evaluates to log(0), "
"i.e. negative infinity.");
message_writer(" Stan can't start sampling from this "
"initial value.");
continue;
}
msg.str("");
std::vector<double> gradient;
bool gradient_ok = true;
clock_t start_check = clock();
log_prob = stan::model::log_prob_grad<true, true>
(model, unconstrained, disc_vector,
gradient, &msg);
clock_t end_check = clock();
double deltaT = static_cast<double>(end_check - start_check)
/ CLOCKS_PER_SEC;
if (msg.str().length() > 0)
message_writer(msg.str());
for (size_t i = 0; i < gradient.size(); ++i) {
if (gradient_ok && !boost::math::isfinite(gradient[i])) {
message_writer("Rejecting initial value:");
message_writer(" Gradient evaluated at the initial value "
"is not finite.");
message_writer(" Stan can't start sampling from this "
"initial value.");
gradient_ok = false;
}
}
if (gradient_ok && print_timing) {
msg.str("");
message_writer();
msg << "Gradient evaluation took " << deltaT << " seconds";
message_writer(msg.str());
msg.str("");
msg << "1000 transitions using 10 leapfrog steps "
<< "per transition would take "
<< 1e4 * deltaT << " seconds.";
message_writer(msg.str());
msg.str("");
message_writer("Adjust your expectations accordingly!");
message_writer();
message_writer();
}
if (gradient_ok)
break;
}
if (num_init_tries == MAX_INIT_TRIES) {
if (!is_fully_initialized && !init_zero) {
message_writer();
msg.str("");
msg << "Initialization between (-" << init_radius
<< ", " << init_radius << ") failed after "
<< MAX_INIT_TRIES << " attempts. ";
message_writer(msg.str());
message_writer(" Try specifying initial values,"
" reducing ranges of constrained values,"
" or reparameterizing the model.");
}
throw std::domain_error("");
}
init_writer(unconstrained);
return unconstrained;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>
#include "Ext.h"
#include <llvm/IR/Function.h>
#include <llvm/IR/TypeBuilder.h>
#include <llvm/IR/IntrinsicInst.h>
//#include <libdevcrypto/SHA3.h>
//#include <libevm/FeeStructure.h>
#include "RuntimeManager.h"
#include "Memory.h"
#include "Type.h"
#include "Endianness.h"
namespace dev
{
namespace eth
{
namespace jit
{
Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan):
RuntimeHelper(_runtimeManager),
m_memoryMan(_memoryMan),
m_funcs({}), // The only std::array initialization that works in both Visual Studio & GCC
m_argAllocas({})
{
m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size");
}
using FuncDesc = std::tuple<char const*, llvm::FunctionType*>;
llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes)
{
return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false);
}
std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs()
{
static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{
FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_getExtCode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})},
FuncDesc{"ext_calldataload", getFunctionType(Type::Void, {Type::RuntimeDataPtr, Type::WordPtr, Type::WordPtr})},
}};
return descs;
}
llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module)
{
auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)];
return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module);
}
llvm::Value* Ext::getArgAlloca()
{
auto& a = m_argAllocas[m_argCounter++];
if (!a)
{
// FIXME: Improve order and names
InsertPointGuard g{getBuilder()};
getBuilder().SetInsertPoint(getMainFunction()->front().getFirstNonPHI());
a = getBuilder().CreateAlloca(Type::Word, nullptr, "arg");
}
return a;
}
llvm::Value* Ext::byPtr(llvm::Value* _value)
{
auto a = getArgAlloca();
getBuilder().CreateStore(_value, a);
return a;
}
llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args)
{
auto& func = m_funcs[static_cast<size_t>(_funcId)];
if (!func)
func = createFunc(_funcId, getModule());
m_argCounter = 0;
return getBuilder().CreateCall(func, {_args.begin(), _args.size()});
}
llvm::Value* Ext::sload(llvm::Value* _index)
{
auto ret = getArgAlloca();
createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness
return m_builder.CreateLoad(ret);
}
void Ext::sstore(llvm::Value* _index, llvm::Value* _value)
{
createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness
}
llvm::Value* Ext::calldataload(llvm::Value* _index)
{
auto ret = getArgAlloca();
createCall(EnvFunc::calldataload, {getRuntimeManager().getDataPtr(), byPtr(_index), ret});
ret = m_builder.CreateLoad(ret);
return Endianness::toNative(m_builder, ret);
}
llvm::Value* Ext::balance(llvm::Value* _address)
{
auto address = Endianness::toBE(m_builder, _address);
auto ret = getArgAlloca();
createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret});
return m_builder.CreateLoad(ret);
}
llvm::Value* Ext::blockhash(llvm::Value* _number)
{
auto hash = getArgAlloca();
createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash});
hash = m_builder.CreateLoad(hash);
return Endianness::toNative(getBuilder(), hash);
}
llvm::Value* Ext::create(llvm::Value*& _gas, llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize)
{
auto gas = byPtr(_gas);
auto ret = getArgAlloca();
auto begin = m_memoryMan.getBytePtr(_initOff);
auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size");
createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), gas, byPtr(_endowment), begin, size, ret});
_gas = m_builder.CreateLoad(gas); // Return gas
llvm::Value* address = m_builder.CreateLoad(ret);
address = Endianness::toNative(m_builder, address);
return address;
}
llvm::Value* Ext::call(llvm::Value*& _gas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress)
{
auto gas = byPtr(_gas);
auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress);
auto inBeg = m_memoryMan.getBytePtr(_inOff);
auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size");
auto outBeg = m_memoryMan.getBytePtr(_outOff);
auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size");
auto codeAddress = Endianness::toBE(m_builder, _codeAddress);
auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), gas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)});
_gas = m_builder.CreateLoad(gas); // Return gas
return m_builder.CreateZExt(ret, Type::Word, "ret");
}
llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize)
{
auto begin = m_memoryMan.getBytePtr(_inOff);
auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size");
auto ret = getArgAlloca();
createCall(EnvFunc::sha3, {begin, size, ret});
llvm::Value* hash = m_builder.CreateLoad(ret);
hash = Endianness::toNative(m_builder, hash);
return hash;
}
MemoryRef Ext::getExtCode(llvm::Value* _addr)
{
auto addr = Endianness::toBE(m_builder, _addr);
auto code = createCall(EnvFunc::getExtCode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size});
auto codeSize = m_builder.CreateLoad(m_size);
auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word);
return {code, codeSize256};
}
void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics)
{
auto begin = m_memoryMan.getBytePtr(_memIdx);
auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size");
llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()};
auto topicArgPtr = &args[3];
for (auto&& topic : _topics)
{
if (topic)
m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr);
else
*topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr);
++topicArgPtr;
}
createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<>
}
}
}
}
<commit_msg>Fix for EVMJIT<commit_after>
#include "Ext.h"
#include <llvm/IR/Function.h>
#include <llvm/IR/TypeBuilder.h>
#include <llvm/IR/IntrinsicInst.h>
//#include <libdevcrypto/SHA3.h>
//#include <libevm/FeeStructure.h>
#include "RuntimeManager.h"
#include "Memory.h"
#include "Type.h"
#include "Endianness.h"
namespace dev
{
namespace eth
{
namespace jit
{
Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan):
RuntimeHelper(_runtimeManager),
m_memoryMan(_memoryMan)
#ifdef __MSCVER
,
m_funcs({}), // The only std::array initialization that works in both Visual Studio & GCC
m_argAllocas({})
#endif
{
m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size");
}
using FuncDesc = std::tuple<char const*, llvm::FunctionType*>;
llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes)
{
return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false);
}
std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs()
{
static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{
FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_getExtCode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})},
FuncDesc{"ext_calldataload", getFunctionType(Type::Void, {Type::RuntimeDataPtr, Type::WordPtr, Type::WordPtr})},
}};
return descs;
}
llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module)
{
auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)];
return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module);
}
llvm::Value* Ext::getArgAlloca()
{
auto& a = m_argAllocas[m_argCounter++];
if (!a)
{
// FIXME: Improve order and names
InsertPointGuard g{getBuilder()};
getBuilder().SetInsertPoint(getMainFunction()->front().getFirstNonPHI());
a = getBuilder().CreateAlloca(Type::Word, nullptr, "arg");
}
return a;
}
llvm::Value* Ext::byPtr(llvm::Value* _value)
{
auto a = getArgAlloca();
getBuilder().CreateStore(_value, a);
return a;
}
llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args)
{
auto& func = m_funcs[static_cast<size_t>(_funcId)];
if (!func)
func = createFunc(_funcId, getModule());
m_argCounter = 0;
return getBuilder().CreateCall(func, {_args.begin(), _args.size()});
}
llvm::Value* Ext::sload(llvm::Value* _index)
{
auto ret = getArgAlloca();
createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness
return m_builder.CreateLoad(ret);
}
void Ext::sstore(llvm::Value* _index, llvm::Value* _value)
{
createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness
}
llvm::Value* Ext::calldataload(llvm::Value* _index)
{
auto ret = getArgAlloca();
createCall(EnvFunc::calldataload, {getRuntimeManager().getDataPtr(), byPtr(_index), ret});
ret = m_builder.CreateLoad(ret);
return Endianness::toNative(m_builder, ret);
}
llvm::Value* Ext::balance(llvm::Value* _address)
{
auto address = Endianness::toBE(m_builder, _address);
auto ret = getArgAlloca();
createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret});
return m_builder.CreateLoad(ret);
}
llvm::Value* Ext::blockhash(llvm::Value* _number)
{
auto hash = getArgAlloca();
createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash});
hash = m_builder.CreateLoad(hash);
return Endianness::toNative(getBuilder(), hash);
}
llvm::Value* Ext::create(llvm::Value*& _gas, llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize)
{
auto gas = byPtr(_gas);
auto ret = getArgAlloca();
auto begin = m_memoryMan.getBytePtr(_initOff);
auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size");
createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), gas, byPtr(_endowment), begin, size, ret});
_gas = m_builder.CreateLoad(gas); // Return gas
llvm::Value* address = m_builder.CreateLoad(ret);
address = Endianness::toNative(m_builder, address);
return address;
}
llvm::Value* Ext::call(llvm::Value*& _gas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress)
{
auto gas = byPtr(_gas);
auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress);
auto inBeg = m_memoryMan.getBytePtr(_inOff);
auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size");
auto outBeg = m_memoryMan.getBytePtr(_outOff);
auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size");
auto codeAddress = Endianness::toBE(m_builder, _codeAddress);
auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), gas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)});
_gas = m_builder.CreateLoad(gas); // Return gas
return m_builder.CreateZExt(ret, Type::Word, "ret");
}
llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize)
{
auto begin = m_memoryMan.getBytePtr(_inOff);
auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size");
auto ret = getArgAlloca();
createCall(EnvFunc::sha3, {begin, size, ret});
llvm::Value* hash = m_builder.CreateLoad(ret);
hash = Endianness::toNative(m_builder, hash);
return hash;
}
MemoryRef Ext::getExtCode(llvm::Value* _addr)
{
auto addr = Endianness::toBE(m_builder, _addr);
auto code = createCall(EnvFunc::getExtCode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size});
auto codeSize = m_builder.CreateLoad(m_size);
auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word);
return {code, codeSize256};
}
void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics)
{
auto begin = m_memoryMan.getBytePtr(_memIdx);
auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size");
llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()};
auto topicArgPtr = &args[3];
for (auto&& topic : _topics)
{
if (topic)
m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr);
else
*topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr);
++topicArgPtr;
}
createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<>
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2013 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/app/chrome_breakpad_client.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/safe_sprintf.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_settings.h"
#if defined(OS_WIN)
#include <windows.h>
#include "base/file_version_info.h"
#include "base/win/registry.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "policy/policy_constants.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
#include "chrome/browser/crash_upload_list.h"
#include "chrome/common/chrome_version_info_posix.h"
#endif
#if defined(OS_POSIX)
#include "chrome/common/dump_without_crashing.h"
#endif
#if defined(OS_ANDROID)
#include "chrome/common/descriptors_android.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/common/chrome_version_info.h"
#include "chromeos/chromeos_switches.h"
#endif
namespace chrome {
namespace {
#if defined(OS_WIN)
// This is the minimum version of google update that is required for deferred
// crash uploads to work.
const char kMinUpdateVersion[] = "1.3.21.115";
// The value name prefix will be of the form {chrome-version}-{pid}-{timestamp}
// (i.e., "#####.#####.#####.#####-########-########") which easily fits into a
// 63 character buffer.
const char kBrowserCrashDumpPrefixTemplate[] = "%s-%08x-%08x";
const size_t kBrowserCrashDumpPrefixLength = 63;
char g_browser_crash_dump_prefix[kBrowserCrashDumpPrefixLength + 1] = {};
// These registry key to which we'll write a value for each crash dump attempt.
HKEY g_browser_crash_dump_regkey = NULL;
// A atomic counter to make each crash dump value name unique.
base::subtle::Atomic32 g_browser_crash_dump_count = 0;
#endif
} // namespace
ChromeBreakpadClient::ChromeBreakpadClient() {}
ChromeBreakpadClient::~ChromeBreakpadClient() {}
void ChromeBreakpadClient::SetClientID(const std::string& client_id) {
crash_keys::SetClientID(client_id);
}
#if defined(OS_WIN)
bool ChromeBreakpadClient::GetAlternativeCrashDumpLocation(
base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
*crash_dir = base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
return true;
}
return false;
}
void ChromeBreakpadClient::GetProductNameAndVersion(
const base::FilePath& exe_path,
base::string16* product_name,
base::string16* version,
base::string16* special_build,
base::string16* channel_name) {
DCHECK(product_name);
DCHECK(version);
DCHECK(special_build);
DCHECK(channel_name);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(exe_path));
if (version_info.get()) {
// Get the information from the file.
*version = version_info->product_version();
if (!version_info->is_official_build())
version->append(base::ASCIIToUTF16("-devel"));
const CommandLine& command = *CommandLine::ForCurrentProcess();
if (command.HasSwitch(switches::kChromeFrame)) {
*product_name = base::ASCIIToUTF16("ChromeFrame");
} else {
*product_name = version_info->product_short_name();
}
*special_build = version_info->special_build();
} else {
// No version info found. Make up the values.
*product_name = base::ASCIIToUTF16("Chrome");
*version = base::ASCIIToUTF16("0.0.0.0-devel");
}
std::wstring channel_string;
GoogleUpdateSettings::GetChromeChannelAndModifiers(
!GetIsPerUserInstall(exe_path), &channel_string);
*channel_name = base::WideToUTF16(channel_string);
}
bool ChromeBreakpadClient::ShouldShowRestartDialog(base::string16* title,
base::string16* message,
bool* is_rtl_locale) {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kShowRestart) ||
!env->HasVar(env_vars::kRestartInfo) ||
env->HasVar(env_vars::kMetroConnected)) {
return false;
}
std::string restart_info;
env->GetVar(env_vars::kRestartInfo, &restart_info);
// The CHROME_RESTART var contains the dialog strings separated by '|'.
// See ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment()
// for details.
std::vector<std::string> dlg_strings;
base::SplitString(restart_info, '|', &dlg_strings);
if (dlg_strings.size() < 3)
return false;
*title = base::UTF8ToUTF16(dlg_strings[0]);
*message = base::UTF8ToUTF16(dlg_strings[1]);
*is_rtl_locale = dlg_strings[2] == env_vars::kRtlLocale;
return true;
}
bool ChromeBreakpadClient::AboutToRestart() {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kRestartInfo))
return false;
env->SetVar(env_vars::kShowRestart, "1");
return true;
}
bool ChromeBreakpadClient::GetDeferredUploadsSupported(
bool is_per_user_install) {
Version update_version = GoogleUpdateSettings::GetGoogleUpdateVersion(
!is_per_user_install);
if (!update_version.IsValid() ||
update_version.IsOlderThan(std::string(kMinUpdateVersion)))
return false;
return true;
}
bool ChromeBreakpadClient::GetIsPerUserInstall(const base::FilePath& exe_path) {
return InstallUtil::IsPerUserInstall(exe_path.value().c_str());
}
bool ChromeBreakpadClient::GetShouldDumpLargerDumps(bool is_per_user_install) {
base::string16 channel_name(base::WideToUTF16(
GoogleUpdateSettings::GetChromeChannel(!is_per_user_install)));
// Capture more detail in crash dumps for beta and dev channel builds.
if (channel_name == base::ASCIIToUTF16("dev") ||
channel_name == base::ASCIIToUTF16("beta") ||
channel_name == GoogleChromeSxSDistribution::ChannelName())
return true;
return false;
}
int ChromeBreakpadClient::GetResultCodeRespawnFailed() {
return chrome::RESULT_CODE_RESPAWN_FAILED;
}
void ChromeBreakpadClient::InitBrowserCrashDumpsRegKey() {
DCHECK(g_browser_crash_dump_regkey == NULL);
base::win::RegKey regkey;
if (regkey.Create(HKEY_CURRENT_USER,
chrome::kBrowserCrashDumpAttemptsRegistryPath,
KEY_ALL_ACCESS) != ERROR_SUCCESS) {
return;
}
// We use the current process id and the current tick count as a (hopefully)
// unique combination for the crash dump value. There's a small chance that
// across a reboot we might have a crash dump signal written, and the next
// browser process might have the same process id and tick count, but crash
// before consuming the signal (overwriting the signal with an identical one).
// For now, we're willing to live with that risk.
int length = base::strings::SafeSPrintf(g_browser_crash_dump_prefix,
kBrowserCrashDumpPrefixTemplate,
chrome::kChromeVersion,
::GetCurrentProcessId(),
::GetTickCount());
if (length <= 0) {
NOTREACHED();
g_browser_crash_dump_prefix[0] = '\0';
return;
}
// Hold the registry key in a global for update on crash dump.
g_browser_crash_dump_regkey = regkey.Take();
}
void ChromeBreakpadClient::RecordCrashDumpAttempt(bool is_real_crash) {
// If we're not a browser (or the registry is unavailable to us for some
// reason) then there's nothing to do.
if (g_browser_crash_dump_regkey == NULL)
return;
// Generate the final value name we'll use (appends the crash number to the
// base value name).
const size_t kMaxValueSize = 2 * kBrowserCrashDumpPrefixLength;
char value_name[kMaxValueSize + 1] = {};
int length = base::strings::SafeSPrintf(
value_name,
"%s-%x",
g_browser_crash_dump_prefix,
base::subtle::NoBarrier_AtomicIncrement(&g_browser_crash_dump_count, 1));
if (length > 0) {
DWORD value_dword = is_real_crash ? 1 : 0;
::RegSetValueExA(g_browser_crash_dump_regkey, value_name, 0, REG_DWORD,
reinterpret_cast<BYTE*>(&value_dword),
sizeof(value_dword));
}
}
bool ChromeBreakpadClient::ReportingIsEnforcedByPolicy(bool* breakpad_enabled) {
// Determine whether configuration management allows loading the crash reporter.
// Since the configuration management infrastructure is not initialized at this
// point, we read the corresponding registry key directly. The return status
// indicates whether policy data was successfully read. If it is true,
// |breakpad_enabled| contains the value set by policy.
string16 key_name = UTF8ToUTF16(policy::key::kMetricsReportingEnabled);
DWORD value = 0;
base::win::RegKey hklm_policy_key(HKEY_LOCAL_MACHINE,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hklm_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
base::win::RegKey hkcu_policy_key(HKEY_CURRENT_USER,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hkcu_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
return false;
}
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
void ChromeBreakpadClient::GetProductNameAndVersion(std::string* product_name,
std::string* version) {
DCHECK(product_name);
DCHECK(version);
#if defined(OS_ANDROID)
*product_name = "Chrome_Android";
#elif defined(OS_CHROMEOS)
*product_name = "Chrome_ChromeOS";
#else // OS_LINUX
#if !defined(ADDRESS_SANITIZER)
*product_name = "Chrome_Linux";
#else
*product_name = "Chrome_Linux_ASan";
#endif
#endif
*version = PRODUCT_VERSION;
}
base::FilePath ChromeBreakpadClient::GetReporterLogFilename() {
return base::FilePath(CrashUploadList::kReporterLogFilename);
}
#endif
bool ChromeBreakpadClient::GetCrashDumpLocation(base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
base::FilePath crash_dumps_dir_path =
base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
PathService::Override(chrome::DIR_CRASH_DUMPS, crash_dumps_dir_path);
}
return PathService::Get(chrome::DIR_CRASH_DUMPS, crash_dir);
}
#if defined(OS_POSIX)
void ChromeBreakpadClient::SetDumpWithoutCrashingFunction(void (*function)()) {
logging::SetDumpWithoutCrashingFunction(function);
}
#endif
size_t ChromeBreakpadClient::RegisterCrashKeys() {
// Note: This is not called on Windows because Breakpad is initialized in the
// EXE module, but code that uses crash keys is in the DLL module.
// RegisterChromeCrashKeys() will be called after the DLL is loaded.
return crash_keys::RegisterChromeCrashKeys();
}
bool ChromeBreakpadClient::IsRunningUnattended() {
scoped_ptr<base::Environment> env(base::Environment::Create());
return env->HasVar(env_vars::kHeadless);
}
bool ChromeBreakpadClient::GetCollectStatsConsent() {
// Convert #define to a variable so that we can use if() rather than
// #if below and so at least compile-test the Chrome code in
// Chromium builds.
#if defined(GOOGLE_CHROME_BUILD)
bool is_chrome_build = true;
#else
bool is_chrome_build = false;
#endif
#if defined(OS_CHROMEOS)
bool is_guest_session = CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kGuestSession);
bool is_stable_channel =
chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE;
if (is_guest_session && is_stable_channel)
return false;
#endif
return is_chrome_build && GoogleUpdateSettings::GetCollectStatsConsent();
}
#if defined(OS_ANDROID)
int ChromeBreakpadClient::GetAndroidMinidumpDescriptor() {
return kAndroidMinidumpDescriptor;
}
#endif
} // namespace chrome
<commit_msg>On Android, always initial berakpad on official builds<commit_after>// Copyright 2013 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/app/chrome_breakpad_client.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/safe_sprintf.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_settings.h"
#if defined(OS_WIN)
#include <windows.h>
#include "base/file_version_info.h"
#include "base/win/registry.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "policy/policy_constants.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
#include "chrome/browser/crash_upload_list.h"
#include "chrome/common/chrome_version_info_posix.h"
#endif
#if defined(OS_POSIX)
#include "chrome/common/dump_without_crashing.h"
#endif
#if defined(OS_ANDROID)
#include "chrome/common/descriptors_android.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/common/chrome_version_info.h"
#include "chromeos/chromeos_switches.h"
#endif
namespace chrome {
namespace {
#if defined(OS_WIN)
// This is the minimum version of google update that is required for deferred
// crash uploads to work.
const char kMinUpdateVersion[] = "1.3.21.115";
// The value name prefix will be of the form {chrome-version}-{pid}-{timestamp}
// (i.e., "#####.#####.#####.#####-########-########") which easily fits into a
// 63 character buffer.
const char kBrowserCrashDumpPrefixTemplate[] = "%s-%08x-%08x";
const size_t kBrowserCrashDumpPrefixLength = 63;
char g_browser_crash_dump_prefix[kBrowserCrashDumpPrefixLength + 1] = {};
// These registry key to which we'll write a value for each crash dump attempt.
HKEY g_browser_crash_dump_regkey = NULL;
// A atomic counter to make each crash dump value name unique.
base::subtle::Atomic32 g_browser_crash_dump_count = 0;
#endif
} // namespace
ChromeBreakpadClient::ChromeBreakpadClient() {}
ChromeBreakpadClient::~ChromeBreakpadClient() {}
void ChromeBreakpadClient::SetClientID(const std::string& client_id) {
crash_keys::SetClientID(client_id);
}
#if defined(OS_WIN)
bool ChromeBreakpadClient::GetAlternativeCrashDumpLocation(
base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
*crash_dir = base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
return true;
}
return false;
}
void ChromeBreakpadClient::GetProductNameAndVersion(
const base::FilePath& exe_path,
base::string16* product_name,
base::string16* version,
base::string16* special_build,
base::string16* channel_name) {
DCHECK(product_name);
DCHECK(version);
DCHECK(special_build);
DCHECK(channel_name);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(exe_path));
if (version_info.get()) {
// Get the information from the file.
*version = version_info->product_version();
if (!version_info->is_official_build())
version->append(base::ASCIIToUTF16("-devel"));
const CommandLine& command = *CommandLine::ForCurrentProcess();
if (command.HasSwitch(switches::kChromeFrame)) {
*product_name = base::ASCIIToUTF16("ChromeFrame");
} else {
*product_name = version_info->product_short_name();
}
*special_build = version_info->special_build();
} else {
// No version info found. Make up the values.
*product_name = base::ASCIIToUTF16("Chrome");
*version = base::ASCIIToUTF16("0.0.0.0-devel");
}
std::wstring channel_string;
GoogleUpdateSettings::GetChromeChannelAndModifiers(
!GetIsPerUserInstall(exe_path), &channel_string);
*channel_name = base::WideToUTF16(channel_string);
}
bool ChromeBreakpadClient::ShouldShowRestartDialog(base::string16* title,
base::string16* message,
bool* is_rtl_locale) {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kShowRestart) ||
!env->HasVar(env_vars::kRestartInfo) ||
env->HasVar(env_vars::kMetroConnected)) {
return false;
}
std::string restart_info;
env->GetVar(env_vars::kRestartInfo, &restart_info);
// The CHROME_RESTART var contains the dialog strings separated by '|'.
// See ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment()
// for details.
std::vector<std::string> dlg_strings;
base::SplitString(restart_info, '|', &dlg_strings);
if (dlg_strings.size() < 3)
return false;
*title = base::UTF8ToUTF16(dlg_strings[0]);
*message = base::UTF8ToUTF16(dlg_strings[1]);
*is_rtl_locale = dlg_strings[2] == env_vars::kRtlLocale;
return true;
}
bool ChromeBreakpadClient::AboutToRestart() {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kRestartInfo))
return false;
env->SetVar(env_vars::kShowRestart, "1");
return true;
}
bool ChromeBreakpadClient::GetDeferredUploadsSupported(
bool is_per_user_install) {
Version update_version = GoogleUpdateSettings::GetGoogleUpdateVersion(
!is_per_user_install);
if (!update_version.IsValid() ||
update_version.IsOlderThan(std::string(kMinUpdateVersion)))
return false;
return true;
}
bool ChromeBreakpadClient::GetIsPerUserInstall(const base::FilePath& exe_path) {
return InstallUtil::IsPerUserInstall(exe_path.value().c_str());
}
bool ChromeBreakpadClient::GetShouldDumpLargerDumps(bool is_per_user_install) {
base::string16 channel_name(base::WideToUTF16(
GoogleUpdateSettings::GetChromeChannel(!is_per_user_install)));
// Capture more detail in crash dumps for beta and dev channel builds.
if (channel_name == base::ASCIIToUTF16("dev") ||
channel_name == base::ASCIIToUTF16("beta") ||
channel_name == GoogleChromeSxSDistribution::ChannelName())
return true;
return false;
}
int ChromeBreakpadClient::GetResultCodeRespawnFailed() {
return chrome::RESULT_CODE_RESPAWN_FAILED;
}
void ChromeBreakpadClient::InitBrowserCrashDumpsRegKey() {
DCHECK(g_browser_crash_dump_regkey == NULL);
base::win::RegKey regkey;
if (regkey.Create(HKEY_CURRENT_USER,
chrome::kBrowserCrashDumpAttemptsRegistryPath,
KEY_ALL_ACCESS) != ERROR_SUCCESS) {
return;
}
// We use the current process id and the current tick count as a (hopefully)
// unique combination for the crash dump value. There's a small chance that
// across a reboot we might have a crash dump signal written, and the next
// browser process might have the same process id and tick count, but crash
// before consuming the signal (overwriting the signal with an identical one).
// For now, we're willing to live with that risk.
int length = base::strings::SafeSPrintf(g_browser_crash_dump_prefix,
kBrowserCrashDumpPrefixTemplate,
chrome::kChromeVersion,
::GetCurrentProcessId(),
::GetTickCount());
if (length <= 0) {
NOTREACHED();
g_browser_crash_dump_prefix[0] = '\0';
return;
}
// Hold the registry key in a global for update on crash dump.
g_browser_crash_dump_regkey = regkey.Take();
}
void ChromeBreakpadClient::RecordCrashDumpAttempt(bool is_real_crash) {
// If we're not a browser (or the registry is unavailable to us for some
// reason) then there's nothing to do.
if (g_browser_crash_dump_regkey == NULL)
return;
// Generate the final value name we'll use (appends the crash number to the
// base value name).
const size_t kMaxValueSize = 2 * kBrowserCrashDumpPrefixLength;
char value_name[kMaxValueSize + 1] = {};
int length = base::strings::SafeSPrintf(
value_name,
"%s-%x",
g_browser_crash_dump_prefix,
base::subtle::NoBarrier_AtomicIncrement(&g_browser_crash_dump_count, 1));
if (length > 0) {
DWORD value_dword = is_real_crash ? 1 : 0;
::RegSetValueExA(g_browser_crash_dump_regkey, value_name, 0, REG_DWORD,
reinterpret_cast<BYTE*>(&value_dword),
sizeof(value_dword));
}
}
bool ChromeBreakpadClient::ReportingIsEnforcedByPolicy(bool* breakpad_enabled) {
// Determine whether configuration management allows loading the crash reporter.
// Since the configuration management infrastructure is not initialized at this
// point, we read the corresponding registry key directly. The return status
// indicates whether policy data was successfully read. If it is true,
// |breakpad_enabled| contains the value set by policy.
string16 key_name = UTF8ToUTF16(policy::key::kMetricsReportingEnabled);
DWORD value = 0;
base::win::RegKey hklm_policy_key(HKEY_LOCAL_MACHINE,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hklm_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
base::win::RegKey hkcu_policy_key(HKEY_CURRENT_USER,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hkcu_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
return false;
}
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
void ChromeBreakpadClient::GetProductNameAndVersion(std::string* product_name,
std::string* version) {
DCHECK(product_name);
DCHECK(version);
#if defined(OS_ANDROID)
*product_name = "Chrome_Android";
#elif defined(OS_CHROMEOS)
*product_name = "Chrome_ChromeOS";
#else // OS_LINUX
#if !defined(ADDRESS_SANITIZER)
*product_name = "Chrome_Linux";
#else
*product_name = "Chrome_Linux_ASan";
#endif
#endif
*version = PRODUCT_VERSION;
}
base::FilePath ChromeBreakpadClient::GetReporterLogFilename() {
return base::FilePath(CrashUploadList::kReporterLogFilename);
}
#endif
bool ChromeBreakpadClient::GetCrashDumpLocation(base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
base::FilePath crash_dumps_dir_path =
base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
PathService::Override(chrome::DIR_CRASH_DUMPS, crash_dumps_dir_path);
}
return PathService::Get(chrome::DIR_CRASH_DUMPS, crash_dir);
}
#if defined(OS_POSIX)
void ChromeBreakpadClient::SetDumpWithoutCrashingFunction(void (*function)()) {
logging::SetDumpWithoutCrashingFunction(function);
}
#endif
size_t ChromeBreakpadClient::RegisterCrashKeys() {
// Note: This is not called on Windows because Breakpad is initialized in the
// EXE module, but code that uses crash keys is in the DLL module.
// RegisterChromeCrashKeys() will be called after the DLL is loaded.
return crash_keys::RegisterChromeCrashKeys();
}
bool ChromeBreakpadClient::IsRunningUnattended() {
scoped_ptr<base::Environment> env(base::Environment::Create());
return env->HasVar(env_vars::kHeadless);
}
bool ChromeBreakpadClient::GetCollectStatsConsent() {
// Convert #define to a variable so that we can use if() rather than
// #if below and so at least compile-test the Chrome code in
// Chromium builds.
#if defined(GOOGLE_CHROME_BUILD)
bool is_chrome_build = true;
#else
bool is_chrome_build = false;
#endif
#if defined(OS_CHROMEOS)
bool is_guest_session = CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kGuestSession);
bool is_stable_channel =
chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE;
if (is_guest_session && is_stable_channel)
return false;
#endif // defined(OS_CHROMEOS)
#if defined(OS_ANDROID)
// TODO(jcivelli): we should not initialize the crash-reporter when it was not
// enabled. Right now if it is disabled we still generate the minidumps but we
// do not upload them.
return is_chrome_build;
#else // !defined(OS_ANDROID)
return is_chrome_build && GoogleUpdateSettings::GetCollectStatsConsent();
#endif // defined(OS_ANDROID)
}
#if defined(OS_ANDROID)
int ChromeBreakpadClient::GetAndroidMinidumpDescriptor() {
return kAndroidMinidumpDescriptor;
}
#endif
} // namespace chrome
<|endoftext|> |
<commit_before>#include "lux.hpp"
#include "cblas.h"
// Convert from strings to CBLAS enumerations
template <>
enum CBLAS_ORDER lux_to<enum CBLAS_ORDER>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'r':
case 'R':
return CblasRowMajor;
case 'c':
case 'C':
return CblasColMajor;
}
luaL_argerror(state, stack, "R or C");
}
template <>
enum CBLAS_TRANSPOSE lux_to<enum CBLAS_TRANSPOSE>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 't':
case 'T':
return CblasTrans;
case ' ':
return CblasNoTrans;
case 'h':
case 'H':
case '*':
return CblasConjTrans;
}
luaL_argerror(state, stack, "t, T, h, H or ' '");
}
template <>
enum CBLAS_UPLO lux_to<enum CBLAS_UPLO>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'u':
case 'U':
return CblasUpper;
case 'l':
case 'L':
return CblasLower;
}
luaL_argerror(state, stack, "u, U, l, or L");
}
template <>
enum CBLAS_DIAG lux_to<enum CBLAS_DIAG>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'u':
case 'U':
return CblasUnit;
case 'n':
case 'N':
return CblasNonUnit;
}
luaL_argerror(state, stack, "u, U, n, or N");
}
template <>
enum CBLAS_SIDE lux_to<enum CBLAS_SIDE>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'l':
case 'L':
case '<':
return CblasLeft;
case 'r':
case 'R':
case '>':
return CblasRight;
}
luaL_argerror(state, stack, "l, L, <, r, R, or >");
}
// Lua C module entry point
extern "C" int luaopen_cblas(lua_State *state)
{
luaL_Reg regs[] =
{
// SINGLE PRECISION REAL
// level 1
{"sdsdot", lux_cast(cblas_sdsdot)},
{"dsdot", lux_cast(cblas_dsdot)},
{"sdot", lux_cast(cblas_sdot)},
{"snrm2", lux_cast(cblas_snrm2)},
{"sasum", lux_cast(cblas_sasum)},
{"siamax", lux_cast(cblas_isamax)},
{"sswap", lux_cast(cblas_sswap)},
{"scopy", lux_cast(cblas_scopy)},
{"saxpy", lux_cast(cblas_saxpy)},
{"srotg", lux_cast(cblas_srotg)},
{"srotmg", lux_cast(cblas_srotmg)},
{"srot", lux_cast(cblas_srot)},
{"srotm", lux_cast(cblas_srotm)},
{"sscal", lux_cast(cblas_sscal)},
// level 2
{"sgemv", lux_cast(cblas_sgemv)},
{"sgbmv", lux_cast(cblas_sgbmv)},
{"strmv", lux_cast(cblas_strmv)},
{"stbmv", lux_cast(cblas_stbmv)},
{"stpmv", lux_cast(cblas_stpmv)},
{"strsv", lux_cast(cblas_strsv)},
{"stbsv", lux_cast(cblas_stbsv)},
{"stpsv", lux_cast(cblas_stpsv)},
{"ssymv", lux_cast(cblas_ssymv)},
{"ssbmv", lux_cast(cblas_ssbmv)},
{"sspmv", lux_cast(cblas_sspmv)},
{"sger", lux_cast(cblas_sger)},
{"ssyr", lux_cast(cblas_ssyr)},
{"sspr", lux_cast(cblas_sspr)},
{"ssyr2", lux_cast(cblas_ssyr2)},
{"sspr2", lux_cast(cblas_sspr2)},
// level 3
{"sgemm", lux_cast(cblas_sgemm)},
{"ssymm", lux_cast(cblas_ssymm)},
{"ssyrk", lux_cast(cblas_ssyrk)},
{"ssyr2k", lux_cast(cblas_ssyr2k)},
{"strmm", lux_cast(cblas_strmm)},
{"strsm", lux_cast(cblas_strsm)},
// SINGLE PRECISION COMPLEX
// level 1
{"cdotu", lux_cast(cblas_cdotu_sub)},
{"cdotc", lux_cast(cblas_cdotc_sub)},
{"cnrm2", lux_cast(cblas_scnrm2)},
{"casum", lux_cast(cblas_scasum)},
{"icamax", lux_cast(cblas_icamax)},
{"cswap", lux_cast(cblas_cswap)},
{"ccopy", lux_cast(cblas_ccopy)},
{"caxpy", lux_cast(cblas_caxpy)},
{"cscal", lux_cast(cblas_cscal)},
{"csscal", lux_cast(cblas_csscal)},
// level 2
{"cgemv", lux_cast(cblas_cgemv)},
{"cgbmv", lux_cast(cblas_cgbmv)},
{"ctrmv", lux_cast(cblas_ctrmv)},
{"ctbmv", lux_cast(cblas_ctbmv)},
{"ctpmv", lux_cast(cblas_ctpmv)},
{"ctrsv", lux_cast(cblas_ctrsv)},
{"ctbsv", lux_cast(cblas_ctbsv)},
{"ctpsv", lux_cast(cblas_ctpsv)},
{"chemv", lux_cast(cblas_chemv)},
{"chbmv", lux_cast(cblas_chbmv)},
{"chpmv", lux_cast(cblas_chpmv)},
{"cgeru", lux_cast(cblas_cgeru)},
{"cgerc", lux_cast(cblas_cgerc)},
{"cher", lux_cast(cblas_cher)},
{"chpr", lux_cast(cblas_chpr)},
{"cher2", lux_cast(cblas_cher2)},
{"chpr2", lux_cast(cblas_chpr2)},
// level 3
{"cgemm", lux_cast(cblas_cgemm)},
{"csymm", lux_cast(cblas_csymm)},
{"chemm", lux_cast(cblas_chemm)},
{"csyrk", lux_cast(cblas_csyrk)},
{"cherk", lux_cast(cblas_cherk)},
{"csyr2k", lux_cast(cblas_csyr2k)},
{"cher2k", lux_cast(cblas_cher2k)},
{"ctrmm", lux_cast(cblas_ctrmm)},
{"ctrsm", lux_cast(cblas_ctrsm)},
// SINGLE PRECISION REAL
// level 1
{"ddot", lux_cast(cblas_ddot)},
{"dnrm2", lux_cast(cblas_dnrm2)},
{"dasum", lux_cast(cblas_dasum)},
{"idamax", lux_cast(cblas_idamax)},
{"dswap", lux_cast(cblas_dswap)},
{"dcopy", lux_cast(cblas_dcopy)},
{"daxpy", lux_cast(cblas_daxpy)},
{"drotg", lux_cast(cblas_drotg)},
{"drotmg", lux_cast(cblas_drotmg)},
{"drot", lux_cast(cblas_drot)},
{"drotm", lux_cast(cblas_drotm)},
{"dscal", lux_cast(cblas_dscal)},
// level 2
{"dgemv", lux_cast(cblas_dgemv)},
{"dgbmv", lux_cast(cblas_dgbmv)},
{"dtrmv", lux_cast(cblas_dtrmv)},
{"dtbmv", lux_cast(cblas_dtbmv)},
{"dtpmv", lux_cast(cblas_dtpmv)},
{"dtrsv", lux_cast(cblas_dtrsv)},
{"dtbsv", lux_cast(cblas_dtbsv)},
{"dtpsv", lux_cast(cblas_dtpsv)},
{"dsymv", lux_cast(cblas_dsymv)},
{"dsbmv", lux_cast(cblas_dsbmv)},
{"dspmv", lux_cast(cblas_dspmv)},
{"dger", lux_cast(cblas_dger)},
{"dsyr", lux_cast(cblas_dsyr)},
{"dspr", lux_cast(cblas_dspr)},
{"dsyr2", lux_cast(cblas_dsyr2)},
{"dspr2", lux_cast(cblas_dspr2)},
// level 3
{"dgemm", lux_cast(cblas_dgemm)},
{"dsymm", lux_cast(cblas_dsymm)},
{"dsyrk", lux_cast(cblas_dsyrk)},
{"dsyr2k", lux_cast(cblas_dsyr2k)},
{"dtrmm", lux_cast(cblas_dtrmm)},
{"dtrsm", lux_cast(cblas_dtrsm)},
// DOUBLE PRECISION COMPLEX
// level 1
{"zdotu", lux_cast(cblas_zdotu_sub)},
{"zdotc", lux_cast(cblas_zdotc_sub)},
{"znrm2", lux_cast(cblas_dznrm2)},
{"zasum", lux_cast(cblas_dzasum)},
{"izamax", lux_cast(cblas_izamax)},
{"zswap", lux_cast(cblas_zswap)},
{"zcopy", lux_cast(cblas_zcopy)},
{"zaxpy", lux_cast(cblas_zaxpy)},
{"zscal", lux_cast(cblas_zscal)},
{"zdscal", lux_cast(cblas_zdscal)},
// level 2
{"zgemv", lux_cast(cblas_zgemv)},
{"zgbmv", lux_cast(cblas_zgbmv)},
{"ztrmv", lux_cast(cblas_ztrmv)},
{"ztbmv", lux_cast(cblas_ztbmv)},
{"ztpmv", lux_cast(cblas_ztpmv)},
{"ztrsv", lux_cast(cblas_ztrsv)},
{"ztbsv", lux_cast(cblas_ztbsv)},
{"ztpsv", lux_cast(cblas_ztpsv)},
{"zhemv", lux_cast(cblas_zhemv)},
{"zhbmv", lux_cast(cblas_zhbmv)},
{"zhpmv", lux_cast(cblas_zhpmv)},
{"zgeru", lux_cast(cblas_zgeru)},
{"zgerc", lux_cast(cblas_zgerc)},
{"zher", lux_cast(cblas_zher)},
{"zhpr", lux_cast(cblas_zhpr)},
{"zher2", lux_cast(cblas_zher2)},
{"zhpr2", lux_cast(cblas_zhpr2)},
// level 3
{"zgemm", lux_cast(cblas_zgemm)},
{"zsymm", lux_cast(cblas_zsymm)},
{"zhemm", lux_cast(cblas_zhemm)},
{"zsyrk", lux_cast(cblas_zsyrk)},
{"zherk", lux_cast(cblas_zherk)},
{"zsyr2k", lux_cast(cblas_zsyr2k)},
{"zher2k", lux_cast(cblas_zher2k)},
{"ztrmm", lux_cast(cblas_ztrmm)},
{"ztrsm", lux_cast(cblas_ztrsm)},
{nullptr}
};
luaL_newlib(state, regs);
return 1;
}
<commit_msg>Worked on CBLAS module, small fixes<commit_after>#include "lux.hpp"
#include "cblas.h"
// Convert from strings to CBLAS enumerations
template <>
enum CBLAS_ORDER lux_to<enum CBLAS_ORDER>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'C':
case 'c':
case '|':
return CblasColMajor;
case 'R':
case 'r':
case '_':
return CblasRowMajor;
}
luaL_argerror(state, stack, "R or C");
}
template <>
enum CBLAS_TRANSPOSE lux_to<enum CBLAS_TRANSPOSE>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'T':
case 't':
case '/':
return CblasTrans;
case 'N':
case 'n':
case ' ':
return CblasNoTrans;
case 'C':
case 'c':
case 'H':
case 'h':
case '*':
case '+':
return CblasConjTrans;
}
luaL_argerror(state, stack, "t, T, n, N, c, C");
}
template <>
enum CBLAS_UPLO lux_to<enum CBLAS_UPLO>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'U':
case 'u':
case '^':
return CblasUpper;
case 'L':
case 'l':
case '_':
return CblasLower;
}
luaL_argerror(state, stack, "U, u, L, l");
}
template <>
enum CBLAS_DIAG lux_to<enum CBLAS_DIAG>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'U':
case 'u':
case '1':
return CblasUnit;
case 'N':
case 'n':
case ' ':
return CblasNonUnit;
}
luaL_argerror(state, stack, "U, u, N, n");
}
template <>
enum CBLAS_SIDE lux_to<enum CBLAS_SIDE>(lua_State *state, int stack)
{
auto arg = lua_tostring(state, stack);
switch (*arg)
{
case 'L':
case 'l':
case '<':
return CblasLeft;
case 'R':
case 'r':
case '>':
return CblasRight;
}
luaL_argerror(state, stack, "L, l, R, r");
}
// Lua C module entry point
extern "C" int luaopen_cblas(lua_State *state)
{
luaL_Reg regs[] =
{
// SINGLE PRECISION REAL
// level 1
{"sdsdot", lux_cast(cblas_sdsdot)},
{"dsdot", lux_cast(cblas_dsdot)},
{"sdot", lux_cast(cblas_sdot)},
{"snrm2", lux_cast(cblas_snrm2)},
{"sasum", lux_cast(cblas_sasum)},
{"siamax", lux_cast(cblas_isamax)},
{"sswap", lux_cast(cblas_sswap)},
{"scopy", lux_cast(cblas_scopy)},
{"saxpy", lux_cast(cblas_saxpy)},
{"srotg", lux_cast(cblas_srotg)},
{"srotmg", lux_cast(cblas_srotmg)},
{"srot", lux_cast(cblas_srot)},
{"srotm", lux_cast(cblas_srotm)},
{"sscal", lux_cast(cblas_sscal)},
// level 2
{"sgemv", lux_cast(cblas_sgemv)},
{"sgbmv", lux_cast(cblas_sgbmv)},
{"strmv", lux_cast(cblas_strmv)},
{"stbmv", lux_cast(cblas_stbmv)},
{"stpmv", lux_cast(cblas_stpmv)},
{"strsv", lux_cast(cblas_strsv)},
{"stbsv", lux_cast(cblas_stbsv)},
{"stpsv", lux_cast(cblas_stpsv)},
{"ssymv", lux_cast(cblas_ssymv)},
{"ssbmv", lux_cast(cblas_ssbmv)},
{"sspmv", lux_cast(cblas_sspmv)},
{"sger", lux_cast(cblas_sger)},
{"ssyr", lux_cast(cblas_ssyr)},
{"sspr", lux_cast(cblas_sspr)},
{"ssyr2", lux_cast(cblas_ssyr2)},
{"sspr2", lux_cast(cblas_sspr2)},
// level 3
{"sgemm", lux_cast(cblas_sgemm)},
{"ssymm", lux_cast(cblas_ssymm)},
{"ssyrk", lux_cast(cblas_ssyrk)},
{"ssyr2k", lux_cast(cblas_ssyr2k)},
{"strmm", lux_cast(cblas_strmm)},
{"strsm", lux_cast(cblas_strsm)},
// SINGLE PRECISION COMPLEX
// level 1
{"cdotu", lux_cast(cblas_cdotu_sub)},
{"cdotc", lux_cast(cblas_cdotc_sub)},
{"cnrm2", lux_cast(cblas_scnrm2)},
{"casum", lux_cast(cblas_scasum)},
{"icamax", lux_cast(cblas_icamax)},
{"cswap", lux_cast(cblas_cswap)},
{"ccopy", lux_cast(cblas_ccopy)},
{"caxpy", lux_cast(cblas_caxpy)},
{"cscal", lux_cast(cblas_cscal)},
{"csscal", lux_cast(cblas_csscal)},
// level 2
{"cgemv", lux_cast(cblas_cgemv)},
{"cgbmv", lux_cast(cblas_cgbmv)},
{"ctrmv", lux_cast(cblas_ctrmv)},
{"ctbmv", lux_cast(cblas_ctbmv)},
{"ctpmv", lux_cast(cblas_ctpmv)},
{"ctrsv", lux_cast(cblas_ctrsv)},
{"ctbsv", lux_cast(cblas_ctbsv)},
{"ctpsv", lux_cast(cblas_ctpsv)},
{"chemv", lux_cast(cblas_chemv)},
{"chbmv", lux_cast(cblas_chbmv)},
{"chpmv", lux_cast(cblas_chpmv)},
{"cgeru", lux_cast(cblas_cgeru)},
{"cgerc", lux_cast(cblas_cgerc)},
{"cher", lux_cast(cblas_cher)},
{"chpr", lux_cast(cblas_chpr)},
{"cher2", lux_cast(cblas_cher2)},
{"chpr2", lux_cast(cblas_chpr2)},
// level 3
{"cgemm", lux_cast(cblas_cgemm)},
{"csymm", lux_cast(cblas_csymm)},
{"chemm", lux_cast(cblas_chemm)},
{"csyrk", lux_cast(cblas_csyrk)},
{"cherk", lux_cast(cblas_cherk)},
{"csyr2k", lux_cast(cblas_csyr2k)},
{"cher2k", lux_cast(cblas_cher2k)},
{"ctrmm", lux_cast(cblas_ctrmm)},
{"ctrsm", lux_cast(cblas_ctrsm)},
// SINGLE PRECISION REAL
// level 1
{"ddot", lux_cast(cblas_ddot)},
{"dnrm2", lux_cast(cblas_dnrm2)},
{"dasum", lux_cast(cblas_dasum)},
{"idamax", lux_cast(cblas_idamax)},
{"dswap", lux_cast(cblas_dswap)},
{"dcopy", lux_cast(cblas_dcopy)},
{"daxpy", lux_cast(cblas_daxpy)},
{"drotg", lux_cast(cblas_drotg)},
{"drotmg", lux_cast(cblas_drotmg)},
{"drot", lux_cast(cblas_drot)},
{"drotm", lux_cast(cblas_drotm)},
{"dscal", lux_cast(cblas_dscal)},
// level 2
{"dgemv", lux_cast(cblas_dgemv)},
{"dgbmv", lux_cast(cblas_dgbmv)},
{"dtrmv", lux_cast(cblas_dtrmv)},
{"dtbmv", lux_cast(cblas_dtbmv)},
{"dtpmv", lux_cast(cblas_dtpmv)},
{"dtrsv", lux_cast(cblas_dtrsv)},
{"dtbsv", lux_cast(cblas_dtbsv)},
{"dtpsv", lux_cast(cblas_dtpsv)},
{"dsymv", lux_cast(cblas_dsymv)},
{"dsbmv", lux_cast(cblas_dsbmv)},
{"dspmv", lux_cast(cblas_dspmv)},
{"dger", lux_cast(cblas_dger)},
{"dsyr", lux_cast(cblas_dsyr)},
{"dspr", lux_cast(cblas_dspr)},
{"dsyr2", lux_cast(cblas_dsyr2)},
{"dspr2", lux_cast(cblas_dspr2)},
// level 3
{"dgemm", lux_cast(cblas_dgemm)},
{"dsymm", lux_cast(cblas_dsymm)},
{"dsyrk", lux_cast(cblas_dsyrk)},
{"dsyr2k", lux_cast(cblas_dsyr2k)},
{"dtrmm", lux_cast(cblas_dtrmm)},
{"dtrsm", lux_cast(cblas_dtrsm)},
// DOUBLE PRECISION COMPLEX
// level 1
{"zdotu", lux_cast(cblas_zdotu_sub)},
{"zdotc", lux_cast(cblas_zdotc_sub)},
{"znrm2", lux_cast(cblas_dznrm2)},
{"zasum", lux_cast(cblas_dzasum)},
{"izamax", lux_cast(cblas_izamax)},
{"zswap", lux_cast(cblas_zswap)},
{"zcopy", lux_cast(cblas_zcopy)},
{"zaxpy", lux_cast(cblas_zaxpy)},
{"zscal", lux_cast(cblas_zscal)},
{"zdscal", lux_cast(cblas_zdscal)},
// level 2
{"zgemv", lux_cast(cblas_zgemv)},
{"zgbmv", lux_cast(cblas_zgbmv)},
{"ztrmv", lux_cast(cblas_ztrmv)},
{"ztbmv", lux_cast(cblas_ztbmv)},
{"ztpmv", lux_cast(cblas_ztpmv)},
{"ztrsv", lux_cast(cblas_ztrsv)},
{"ztbsv", lux_cast(cblas_ztbsv)},
{"ztpsv", lux_cast(cblas_ztpsv)},
{"zhemv", lux_cast(cblas_zhemv)},
{"zhbmv", lux_cast(cblas_zhbmv)},
{"zhpmv", lux_cast(cblas_zhpmv)},
{"zgeru", lux_cast(cblas_zgeru)},
{"zgerc", lux_cast(cblas_zgerc)},
{"zher", lux_cast(cblas_zher)},
{"zhpr", lux_cast(cblas_zhpr)},
{"zher2", lux_cast(cblas_zher2)},
{"zhpr2", lux_cast(cblas_zhpr2)},
// level 3
{"zgemm", lux_cast(cblas_zgemm)},
{"zsymm", lux_cast(cblas_zsymm)},
{"zhemm", lux_cast(cblas_zhemm)},
{"zsyrk", lux_cast(cblas_zsyrk)},
{"zherk", lux_cast(cblas_zherk)},
{"zsyr2k", lux_cast(cblas_zsyr2k)},
{"zher2k", lux_cast(cblas_zher2k)},
{"ztrmm", lux_cast(cblas_ztrmm)},
{"ztrsm", lux_cast(cblas_ztrsm)},
{nullptr}
};
luaL_newlib(state, regs);
return 1;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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/common/common_param_traits.h"
#include "base/gfx/rect.h"
#include "googleurl/src/gurl.h"
#ifndef EXCLUDE_SKIA_DEPENDENCIES
#include "third_party/skia/include/core/SkBitmap.h"
#endif
#include "webkit/glue/dom_operations.h"
namespace IPC {
#ifndef EXCLUDE_SKIA_DEPENDENCIES
namespace {
struct SkBitmap_Data {
// The configuration for the bitmap (bits per pixel, etc).
SkBitmap::Config fConfig;
// The width of the bitmap in pixels.
uint32 fWidth;
// The height of the bitmap in pixels.
uint32 fHeight;
// The number of bytes between subsequent rows of the bitmap.
uint32 fRowBytes;
void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
fConfig = bitmap.config();
fWidth = bitmap.width();
fHeight = bitmap.height();
fRowBytes = bitmap.rowBytes();
}
// Returns whether |bitmap| successfully initialized.
bool InitSkBitmapFromData(SkBitmap* bitmap, const char* pixels,
size_t total_pixels) const {
if (total_pixels) {
bitmap->setConfig(fConfig, fWidth, fHeight, fRowBytes);
if (!bitmap->allocPixels())
return false;
if (total_pixels > bitmap->getSize())
return false;
memcpy(bitmap->getPixels(), pixels, total_pixels);
}
return true;
}
};
} // namespace
void ParamTraits<SkBitmap>::Write(Message* m, const SkBitmap& p) {
size_t fixed_size = sizeof(SkBitmap_Data);
SkBitmap_Data bmp_data;
bmp_data.InitSkBitmapDataForTransfer(p);
m->WriteData(reinterpret_cast<const char*>(&bmp_data),
static_cast<int>(fixed_size));
size_t pixel_size = p.getSize();
SkAutoLockPixels p_lock(p);
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
bool ParamTraits<SkBitmap>::Read(const Message* m, void** iter, SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!m->ReadData(iter, &fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
NOTREACHED();
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!m->ReadData(iter, &variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
NOTREACHED();
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::wstring* l) {
l->append(StringPrintf(L"<SkBitmap>"));
}
#endif // EXCLUDE_SKIA_DEPENDENCIES
void ParamTraits<GURL>::Write(Message* m, const GURL& p) {
m->WriteString(p.possibly_invalid_spec());
// TODO(brettw) bug 684583: Add encoding for query params.
}
bool ParamTraits<GURL>::Read(const Message* m, void** iter, GURL* p) {
std::string s;
if (!m->ReadString(iter, &s)) {
*p = GURL();
return false;
}
*p = GURL(s);
return true;
}
void ParamTraits<GURL>::Log(const GURL& p, std::wstring* l) {
l->append(UTF8ToWide(p.spec()));
}
void ParamTraits<gfx::Point>::Write(Message* m, const gfx::Point& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
}
bool ParamTraits<gfx::Point>::Read(const Message* m, void** iter,
gfx::Point* r) {
int x, y;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y))
return false;
r->set_x(x);
r->set_y(y);
return true;
}
void ParamTraits<gfx::Point>::Log(const gfx::Point& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.x(), p.y()));
}
void ParamTraits<gfx::Rect>::Write(Message* m, const gfx::Rect& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Rect>::Read(const Message* m, void** iter, gfx::Rect* r) {
int x, y, w, h;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y) ||
!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
r->set_x(x);
r->set_y(y);
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Rect>::Log(const gfx::Rect& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d, %d, %d)", p.x(), p.y(),
p.width(), p.height()));
}
void ParamTraits<gfx::Size>::Write(Message* m, const gfx::Size& p) {
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Size>::Read(const Message* m, void** iter, gfx::Size* r) {
int w, h;
if (!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Size>::Log(const gfx::Size& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.width(), p.height()));
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Write(
Message* m, const webkit_glue::WebApplicationInfo& p) {
WriteParam(m, p.title);
WriteParam(m, p.description);
WriteParam(m, p.app_url);
WriteParam(m, p.icons.size());
for (size_t i = 0; i < p.icons.size(); ++i) {
WriteParam(m, p.icons[i].url);
WriteParam(m, p.icons[i].width);
WriteParam(m, p.icons[i].height);
}
}
bool ParamTraits<webkit_glue::WebApplicationInfo>::Read(
const Message* m, void** iter, webkit_glue::WebApplicationInfo* r) {
size_t icon_count;
bool result =
ReadParam(m, iter, &r->title) &&
ReadParam(m, iter, &r->description) &&
ReadParam(m, iter, &r->app_url) &&
ReadParam(m, iter, &icon_count);
if (!result)
return false;
for (size_t i = 0; i < icon_count && result; ++i) {
param_type::IconInfo icon_info;
result =
ReadParam(m, iter, &icon_info.url) &&
ReadParam(m, iter, &icon_info.width) &&
ReadParam(m, iter, &icon_info.height);
r->icons.push_back(icon_info);
}
return result;
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Log(
const webkit_glue::WebApplicationInfo& p, std::wstring* l) {
l->append(L"<WebApplicationInfo>");
}
} // namespace IPC
<commit_msg>Fix up rowbytes vs. width desynchronization, and fix failure to initialize entire bitmap memory. To fix up the rowbytes value properly, we simply don't send it via IPC any more, and recalulate it from width and depth in the trusted code. It's a cheap calculation. Also one bonus fix: don't use an unintialized IconInfo if deserialization fails.<commit_after>// Copyright (c) 2006-2008 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/common/common_param_traits.h"
#include "base/gfx/rect.h"
#include "googleurl/src/gurl.h"
#ifndef EXCLUDE_SKIA_DEPENDENCIES
#include "third_party/skia/include/core/SkBitmap.h"
#endif
#include "webkit/glue/dom_operations.h"
namespace IPC {
#ifndef EXCLUDE_SKIA_DEPENDENCIES
namespace {
struct SkBitmap_Data {
// The configuration for the bitmap (bits per pixel, etc).
SkBitmap::Config fConfig;
// The width of the bitmap in pixels.
uint32 fWidth;
// The height of the bitmap in pixels.
uint32 fHeight;
void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
fConfig = bitmap.config();
fWidth = bitmap.width();
fHeight = bitmap.height();
}
// Returns whether |bitmap| successfully initialized.
bool InitSkBitmapFromData(SkBitmap* bitmap, const char* pixels,
size_t total_pixels) const {
if (total_pixels) {
bitmap->setConfig(fConfig, fWidth, fHeight, 0);
if (!bitmap->allocPixels())
return false;
if (total_pixels != bitmap->getSize())
return false;
memcpy(bitmap->getPixels(), pixels, total_pixels);
}
return true;
}
};
} // namespace
void ParamTraits<SkBitmap>::Write(Message* m, const SkBitmap& p) {
size_t fixed_size = sizeof(SkBitmap_Data);
SkBitmap_Data bmp_data;
bmp_data.InitSkBitmapDataForTransfer(p);
m->WriteData(reinterpret_cast<const char*>(&bmp_data),
static_cast<int>(fixed_size));
size_t pixel_size = p.getSize();
SkAutoLockPixels p_lock(p);
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
bool ParamTraits<SkBitmap>::Read(const Message* m, void** iter, SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!m->ReadData(iter, &fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
NOTREACHED();
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!m->ReadData(iter, &variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
NOTREACHED();
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::wstring* l) {
l->append(StringPrintf(L"<SkBitmap>"));
}
#endif // EXCLUDE_SKIA_DEPENDENCIES
void ParamTraits<GURL>::Write(Message* m, const GURL& p) {
m->WriteString(p.possibly_invalid_spec());
// TODO(brettw) bug 684583: Add encoding for query params.
}
bool ParamTraits<GURL>::Read(const Message* m, void** iter, GURL* p) {
std::string s;
if (!m->ReadString(iter, &s)) {
*p = GURL();
return false;
}
*p = GURL(s);
return true;
}
void ParamTraits<GURL>::Log(const GURL& p, std::wstring* l) {
l->append(UTF8ToWide(p.spec()));
}
void ParamTraits<gfx::Point>::Write(Message* m, const gfx::Point& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
}
bool ParamTraits<gfx::Point>::Read(const Message* m, void** iter,
gfx::Point* r) {
int x, y;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y))
return false;
r->set_x(x);
r->set_y(y);
return true;
}
void ParamTraits<gfx::Point>::Log(const gfx::Point& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.x(), p.y()));
}
void ParamTraits<gfx::Rect>::Write(Message* m, const gfx::Rect& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Rect>::Read(const Message* m, void** iter, gfx::Rect* r) {
int x, y, w, h;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y) ||
!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
r->set_x(x);
r->set_y(y);
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Rect>::Log(const gfx::Rect& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d, %d, %d)", p.x(), p.y(),
p.width(), p.height()));
}
void ParamTraits<gfx::Size>::Write(Message* m, const gfx::Size& p) {
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Size>::Read(const Message* m, void** iter, gfx::Size* r) {
int w, h;
if (!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Size>::Log(const gfx::Size& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.width(), p.height()));
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Write(
Message* m, const webkit_glue::WebApplicationInfo& p) {
WriteParam(m, p.title);
WriteParam(m, p.description);
WriteParam(m, p.app_url);
WriteParam(m, p.icons.size());
for (size_t i = 0; i < p.icons.size(); ++i) {
WriteParam(m, p.icons[i].url);
WriteParam(m, p.icons[i].width);
WriteParam(m, p.icons[i].height);
}
}
bool ParamTraits<webkit_glue::WebApplicationInfo>::Read(
const Message* m, void** iter, webkit_glue::WebApplicationInfo* r) {
size_t icon_count;
bool result =
ReadParam(m, iter, &r->title) &&
ReadParam(m, iter, &r->description) &&
ReadParam(m, iter, &r->app_url) &&
ReadParam(m, iter, &icon_count);
if (!result)
return false;
for (size_t i = 0; i < icon_count; ++i) {
param_type::IconInfo icon_info;
result =
ReadParam(m, iter, &icon_info.url) &&
ReadParam(m, iter, &icon_info.width) &&
ReadParam(m, iter, &icon_info.height);
if (!result)
return false;
r->icons.push_back(icon_info);
}
return true;
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Log(
const webkit_glue::WebApplicationInfo& p, std::wstring* l) {
l->append(L"<WebApplicationInfo>");
}
} // namespace IPC
<|endoftext|> |
<commit_before>#pragma once
#include <optional>
#include <tuple>
#include <vector>
#include <utility>
#pragma GCC diagnostic push
#ifdef __clang__
// 8.0.1
#pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
#pragma GCC diagnostic ignored "-Wsigned-enum-bitfield" // fmt/format.h
#pragma GCC diagnostic ignored "-Wmissing-noreturn" // fmt/core.h
#pragma GCC diagnostic ignored "-Wundefined-func-template" // fmt/chrono.h:1182
// #pragma GCC diagnostic ignored "-Wextra-semi-stmt" // fmt/format.h:1242
// #pragma GCC diagnostic ignored "-Wsign-conversion" // fmt/format.h:2699
// #pragma GCC diagnostic ignored "-Wdouble-promotion" // fmt/core.h:769
// #pragma GCC diagnostic ignored "-Wshadow" // fmt/chrono.h
// #pragma GCC diagnostic ignored "-Wshadow-field" // fmt/core.h
// #pragma GCC diagnostic ignored "-Wundef" // fmt/core.h
// #pragma GCC diagnostic ignored "-Wunused-template" // fmt/chrono.h
// #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" // fmt/core.h
// clang 11
// #pragma GCC diagnostic ignored "-Wsuggest-override"
// #pragma GCC diagnostic ignored "-Wsuggest-destructor-override"
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
#endif
#ifdef __GNUG__
#pragma GCC diagnostic ignored "-Wdeprecated" // fmt/format.h: implicit capture of ‘this’ via ‘[=]’ is deprecated in C++20
#endif
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <fmt/chrono.h>
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
namespace acmacs::fmt_helper
{
struct default_formatter
{
};
struct float_formatter
{
};
}
// ----------------------------------------------------------------------
template <> struct fmt::formatter<acmacs::fmt_helper::default_formatter>
{
template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
};
template <> struct fmt::formatter<acmacs::fmt_helper::float_formatter>
{
template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
{
auto it = ctx.begin();
if (it != ctx.end() && *it == ':')
++it;
const auto end = std::find(it, ctx.end(), '}');
format_ = fmt::format("{{:{}}}", std::string_view(it, static_cast<size_t>(end - it)));
return end;
}
template <typename Val> std::string format_val(Val&& val) const
{
return fmt::format(fmt::runtime(format_), std::forward<Val>(val));
}
template <typename Val, typename FormatContext> auto format_val(Val&& val, FormatContext& ctx) const
{
return format_to(ctx.out(), fmt::runtime(format_), std::forward<Val>(val));
}
private:
std::string format_;
};
// ----------------------------------------------------------------------
template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<std::exception, T>, char>> : fmt::formatter<const char*> {
template <typename FormatCtx> auto format(const std::exception& err, FormatCtx& ctx) const { return fmt::formatter<const char*>::format(err.what(), ctx); }
};
// template <> struct fmt::formatter<std::exception>
// {
// template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
// template <typename FormatContext> auto format(const std::exception& err, FormatContext& ctx) { return format_to(ctx.out(), "{}", err.what()); }
// };
// template <> struct fmt::formatter<###> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
// template <typename FormatCtx> auto format(const ###& value, FormatCtx& ctx)
// {
// format_to(ctx.out(), "{} {}", );
// return format_to(ctx.out(), "{} {}", );
// return ctx.out();
// }
// };
// ----------------------------------------------------------------------
namespace fmt
{
template <typename T> std::string format(const std::vector<T>& collection, std::string_view entry_format, std::string_view entry_separator = "\n ")
{
return fmt::format(entry_format, fmt::join(collection, entry_separator));
}
} // namespace fmt
// ----------------------------------------------------------------------
// memory_buffer unexpected problem
// in 8.0 format_to(memory_buffer,...) is deprecated without clearly stating in docs
// https://www.gitmemory.com/issue/fmtlib/fmt/2420/877703767
// ----------------------------------------------------------------------
namespace fmt
{
template <typename BUF, typename... T> inline void format_to_mb(BUF& buf, format_string<T...> fmt, T&&... args)
{
detail::vformat_to(buf, string_view(fmt), fmt::make_format_args(args...));
}
}
// ----------------------------------------------------------------------
// substitute
// ----------------------------------------------------------------------
namespace fmt
{
enum class if_no_substitution_found { leave_as_is, empty };
std::vector<std::pair<std::string_view, std::string_view>> split_for_formatting(std::string_view source); // pair{key, format}: {"key", "{key:03d}"} {"", "between-format"}
template <typename FormatMatched, typename FormatNoPattern, typename... Args>
void substitute_to(FormatMatched&& format_matched, FormatNoPattern&& format_no_pattern, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
{
const auto match_and_format = [&format_matched](std::string_view look_for, std::string_view pattern_arg, const auto& en) {
if (look_for == std::get<0>(en)) {
format_matched(pattern_arg, en);
return true;
}
else
return false;
};
for (const auto& [key, pattern_arg] : split_for_formatting(pattern)) {
if (!key.empty()) {
if (!(match_and_format(key, pattern_arg, args) || ...)) {
// not matched
switch (insf) {
case if_no_substitution_found::leave_as_is:
format_no_pattern(pattern_arg);
break;
case if_no_substitution_found::empty:
break;
}
}
}
else
format_no_pattern(pattern_arg);
}
}
// substitute_to args:
// std::pair{"name", value} -- {name}, {name:3d}
// std::pair{"name", []() -> decltype(value) { return value; }} -- {name}, {name:3d}
// std::tuple{"name1", val1, "name2", val2} -- {name1:{name2}d}
template <typename... Args> void substitute_to(memory_buffer& output, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
{
const auto format_matched = [&output](std::string_view pattern_arg, const auto& key_value) {
static_assert(std::is_same_v<std::decay_t<decltype(std::get<0>(key_value))>, const char*>);
if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 2) {
if constexpr (std::is_invocable_v<decltype(std::get<1>(key_value))>)
format_to_mb(output, fmt::runtime(pattern_arg), arg(std::get<0>(key_value), std::invoke(std::get<1>(key_value))));
else
format_to_mb(output, fmt::runtime(pattern_arg), arg(std::get<0>(key_value), std::get<1>(key_value)));
}
else if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 4) {
format_to_mb(output, fmt::runtime(pattern_arg), arg(std::get<0>(key_value), std::get<1>(key_value)), arg(std::get<2>(key_value), std::get<3>(key_value)));
}
else
static_assert(
std::tuple_size<std::decay_t<decltype(key_value)>>::value == 0,
"fmt::substitute arg can be used in the following forms: std::pair<const char*, value>, std::pair<const char*, lambda>, std::tuple<const char*, value, const char*, value>");
};
const auto format_no_pattern = [&output](std::string_view no_pattern) { output.append(no_pattern); };
substitute_to(format_matched, format_no_pattern, pattern, insf, std::forward<Args>(args)...);
}
// see acmacs-chart-2/cc/name-format.cc for usage example
template <typename... Args> std::string substitute(std::string_view pattern, if_no_substitution_found insf, Args&&... args)
{
memory_buffer output;
substitute_to(output, pattern, insf, std::forward<Args>(args)...);
return to_string(output);
}
template <typename... Args> std::string substitute(std::string_view pattern, Args&&... args) { return substitute(pattern, if_no_substitution_found::leave_as_is, std::forward<Args>(args)...); }
} // namespace fmt
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>porting to clang++13<commit_after>#pragma once
#include <optional>
#include <tuple>
#include <vector>
#include <utility>
#pragma GCC diagnostic push
#ifdef __clang__
// 8.0.1, clang 13
#pragma GCC diagnostic ignored "-Wreserved-identifier" // identifier '_a' is reserved because it starts with '_' at global scope (bug in clang13 ?)
#pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
#pragma GCC diagnostic ignored "-Wsigned-enum-bitfield" // fmt/format.h
#pragma GCC diagnostic ignored "-Wmissing-noreturn" // fmt/core.h
#pragma GCC diagnostic ignored "-Wundefined-func-template" // fmt/chrono.h:1182
// #pragma GCC diagnostic ignored "-Wextra-semi-stmt" // fmt/format.h:1242
// #pragma GCC diagnostic ignored "-Wsign-conversion" // fmt/format.h:2699
// #pragma GCC diagnostic ignored "-Wdouble-promotion" // fmt/core.h:769
// #pragma GCC diagnostic ignored "-Wshadow" // fmt/chrono.h
// #pragma GCC diagnostic ignored "-Wshadow-field" // fmt/core.h
// #pragma GCC diagnostic ignored "-Wundef" // fmt/core.h
// #pragma GCC diagnostic ignored "-Wunused-template" // fmt/chrono.h
// #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" // fmt/core.h
// clang 11
// #pragma GCC diagnostic ignored "-Wsuggest-override"
// #pragma GCC diagnostic ignored "-Wsuggest-destructor-override"
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
#endif
#ifdef __GNUG__
#pragma GCC diagnostic ignored "-Wdeprecated" // fmt/format.h: implicit capture of ‘this’ via ‘[=]’ is deprecated in C++20
#endif
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <fmt/chrono.h>
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
namespace acmacs::fmt_helper
{
struct default_formatter
{
};
struct float_formatter
{
};
}
// ----------------------------------------------------------------------
template <> struct fmt::formatter<acmacs::fmt_helper::default_formatter>
{
template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
};
template <> struct fmt::formatter<acmacs::fmt_helper::float_formatter>
{
template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
{
auto it = ctx.begin();
if (it != ctx.end() && *it == ':')
++it;
const auto end = std::find(it, ctx.end(), '}');
format_ = fmt::format("{{:{}}}", std::string_view(it, static_cast<size_t>(end - it)));
return end;
}
template <typename Val> std::string format_val(Val&& val) const
{
return fmt::format(fmt::runtime(format_), std::forward<Val>(val));
}
template <typename Val, typename FormatContext> auto format_val(Val&& val, FormatContext& ctx) const
{
return format_to(ctx.out(), fmt::runtime(format_), std::forward<Val>(val));
}
private:
std::string format_;
};
// ----------------------------------------------------------------------
template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<std::exception, T>, char>> : fmt::formatter<const char*> {
template <typename FormatCtx> auto format(const std::exception& err, FormatCtx& ctx) const { return fmt::formatter<const char*>::format(err.what(), ctx); }
};
// template <> struct fmt::formatter<std::exception>
// {
// template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
// template <typename FormatContext> auto format(const std::exception& err, FormatContext& ctx) { return format_to(ctx.out(), "{}", err.what()); }
// };
// template <> struct fmt::formatter<###> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
// template <typename FormatCtx> auto format(const ###& value, FormatCtx& ctx)
// {
// format_to(ctx.out(), "{} {}", );
// return format_to(ctx.out(), "{} {}", );
// return ctx.out();
// }
// };
// ----------------------------------------------------------------------
namespace fmt
{
template <typename T> std::string format(const std::vector<T>& collection, std::string_view entry_format, std::string_view entry_separator = "\n ")
{
return fmt::format(entry_format, fmt::join(collection, entry_separator));
}
} // namespace fmt
// ----------------------------------------------------------------------
// memory_buffer unexpected problem
// in 8.0 format_to(memory_buffer,...) is deprecated without clearly stating in docs
// https://www.gitmemory.com/issue/fmtlib/fmt/2420/877703767
// ----------------------------------------------------------------------
namespace fmt
{
template <typename BUF, typename... T> inline void format_to_mb(BUF& buf, format_string<T...> fmt, T&&... args)
{
detail::vformat_to(buf, string_view(fmt), fmt::make_format_args(args...));
}
}
// ----------------------------------------------------------------------
// substitute
// ----------------------------------------------------------------------
namespace fmt
{
enum class if_no_substitution_found { leave_as_is, empty };
std::vector<std::pair<std::string_view, std::string_view>> split_for_formatting(std::string_view source); // pair{key, format}: {"key", "{key:03d}"} {"", "between-format"}
template <typename FormatMatched, typename FormatNoPattern, typename... Args>
void substitute_to(FormatMatched&& format_matched, FormatNoPattern&& format_no_pattern, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
{
const auto match_and_format = [&format_matched](std::string_view look_for, std::string_view pattern_arg, const auto& en) {
if (look_for == std::get<0>(en)) {
format_matched(pattern_arg, en);
return true;
}
else
return false;
};
for (const auto& [key, pattern_arg] : split_for_formatting(pattern)) {
if (!key.empty()) {
if (!(match_and_format(key, pattern_arg, args) || ...)) {
// not matched
switch (insf) {
case if_no_substitution_found::leave_as_is:
format_no_pattern(pattern_arg);
break;
case if_no_substitution_found::empty:
break;
}
}
}
else
format_no_pattern(pattern_arg);
}
}
// substitute_to args:
// std::pair{"name", value} -- {name}, {name:3d}
// std::pair{"name", []() -> decltype(value) { return value; }} -- {name}, {name:3d}
// std::tuple{"name1", val1, "name2", val2} -- {name1:{name2}d}
template <typename... Args> void substitute_to(memory_buffer& output, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
{
const auto format_matched = [&output](std::string_view pattern_arg, const auto& key_value) {
static_assert(std::is_same_v<std::decay_t<decltype(std::get<0>(key_value))>, const char*>);
if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 2) {
if constexpr (std::is_invocable_v<decltype(std::get<1>(key_value))>)
format_to_mb(output, fmt::runtime(pattern_arg), arg(std::get<0>(key_value), std::invoke(std::get<1>(key_value))));
else
format_to_mb(output, fmt::runtime(pattern_arg), arg(std::get<0>(key_value), std::get<1>(key_value)));
}
else if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 4) {
format_to_mb(output, fmt::runtime(pattern_arg), arg(std::get<0>(key_value), std::get<1>(key_value)), arg(std::get<2>(key_value), std::get<3>(key_value)));
}
else
static_assert(
std::tuple_size<std::decay_t<decltype(key_value)>>::value == 0,
"fmt::substitute arg can be used in the following forms: std::pair<const char*, value>, std::pair<const char*, lambda>, std::tuple<const char*, value, const char*, value>");
};
const auto format_no_pattern = [&output](std::string_view no_pattern) { output.append(no_pattern); };
substitute_to(format_matched, format_no_pattern, pattern, insf, std::forward<Args>(args)...);
}
// see acmacs-chart-2/cc/name-format.cc for usage example
template <typename... Args> std::string substitute(std::string_view pattern, if_no_substitution_found insf, Args&&... args)
{
memory_buffer output;
substitute_to(output, pattern, insf, std::forward<Args>(args)...);
return to_string(output);
}
template <typename... Args> std::string substitute(std::string_view pattern, Args&&... args) { return substitute(pattern, if_no_substitution_found::leave_as_is, std::forward<Args>(args)...); }
} // namespace fmt
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>// Rel native launcher for Linux.
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <string>
#include <fstream>
#include <streambuf>
int main(int argc, char **argv)
{
// Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found
char *dir = dirname(argv[0]);
chdir(dir);
// Read the ini file
std::string iniFileName("lib/Rel.ini");
std::ifstream configfile(iniFileName);
std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>());
// Empty or no ini file?
if (cmd.length() == 0) {
std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl;
return 10;
}
// Include command-line args.
std::string args("");
for (int i = 1; i < argc; i++)
args += std::string(" ") + std::string(argv[i]);
setenv("SWT_GTK3", "0", 1);
return system((cmd + args).c_str());
}
<commit_msg>Add double-quote delimiters to args.<commit_after>// Rel native launcher for Linux.
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <string>
#include <fstream>
#include <streambuf>
int main(int argc, char **argv)
{
// Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found
char *dir = dirname(argv[0]);
chdir(dir);
// Read the ini file
std::string iniFileName("lib/Rel.ini");
std::ifstream configfile(iniFileName);
std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>());
// Empty or no ini file?
if (cmd.length() == 0) {
std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl;
return 10;
}
// Include command-line args.
std::string args("");
for (int i = 1; i < argc; i++)
args += std::string(" \"") + std::string(argv[i]) + std::string("\"");
setenv("SWT_GTK3", "0", 1);
return system((cmd + args).c_str());
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
/***********************************************************************************************************************
* Reference.cpp
*
* Created on: Nov 17, 2010
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "nodes/Reference.h"
#include "commands/FieldSet.h"
#include "Model.h"
#include "ModelException.h"
namespace Model {
NODE_DEFINE_TYPE_REGISTRATION_METHODS(Reference, Node)
Reference::Reference(Node *parent) :
Node(parent), target_(nullptr)
{
manageUnresolvedReferencesListInModel();
}
Reference::Reference(Node *parent, PersistentStore &store, bool) :
Node(parent)
{
name_ = store.loadReferenceValue(this);
manageUnresolvedReferencesListInModel();
}
void Reference::setName(const QString &name, bool tryResolvingImmediately)
{
execute(new FieldSet<QString> (this, name_, name));
execute(new FieldSet<Node*> (this, target_, nullptr));
if (tryResolvingImmediately) resolve();
manageUnresolvedReferencesListInModel();
}
void Reference::setTarget(Node* target)
{
if (target) execute(new FieldSet<QString> (this, name_, QString()));
else execute(new FieldSet<QString> (this, name_, name()));
execute(new FieldSet<Node*> (this, target_, target));
manageUnresolvedReferencesListInModel();
}
bool Reference::resolve()
{
return false;
}
void Reference::save(PersistentStore &store) const
{
store.saveReferenceValue(name_, target_);
}
void Reference::load(PersistentStore &store)
{
// TODO: Implement reference loading properly.
throw ModelException("Loading references outside a Reference constructor is not properly implemented yet");
if (store.currentNodeType() != typeName())
throw ModelException("Trying to load a Reference node from an incompatible node type " + store.currentNodeType());
setName( store.loadReferenceValue(this) );
}
void Reference::manageUnresolvedReferencesListInModel()
{
if (model())
{
if (isResolved()) model()->removeUnresolvedReference(this);
else model()->addUnresolvedReference(this);
}
}
}
<commit_msg>Fix an uninitialized bug when pasting references<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
/***********************************************************************************************************************
* Reference.cpp
*
* Created on: Nov 17, 2010
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "nodes/Reference.h"
#include "commands/FieldSet.h"
#include "Model.h"
#include "ModelException.h"
namespace Model {
NODE_DEFINE_TYPE_REGISTRATION_METHODS(Reference, Node)
Reference::Reference(Node *parent) :
Node(parent), target_()
{
manageUnresolvedReferencesListInModel();
}
Reference::Reference(Node *parent, PersistentStore &store, bool) :
Node(parent), target_()
{
name_ = store.loadReferenceValue(this);
manageUnresolvedReferencesListInModel();
}
void Reference::setName(const QString &name, bool tryResolvingImmediately)
{
execute(new FieldSet<QString> (this, name_, name));
execute(new FieldSet<Node*> (this, target_, nullptr));
if (tryResolvingImmediately) resolve();
manageUnresolvedReferencesListInModel();
}
void Reference::setTarget(Node* target)
{
if (target) execute(new FieldSet<QString> (this, name_, QString()));
else execute(new FieldSet<QString> (this, name_, name()));
execute(new FieldSet<Node*> (this, target_, target));
manageUnresolvedReferencesListInModel();
}
bool Reference::resolve()
{
return false;
}
void Reference::save(PersistentStore &store) const
{
store.saveReferenceValue(name_, target_);
}
void Reference::load(PersistentStore &store)
{
// TODO: Implement reference loading properly.
throw ModelException("Loading references outside a Reference constructor is not properly implemented yet");
if (store.currentNodeType() != typeName())
throw ModelException("Trying to load a Reference node from an incompatible node type " + store.currentNodeType());
setName( store.loadReferenceValue(this) );
}
void Reference::manageUnresolvedReferencesListInModel()
{
if (model())
{
if (isResolved()) model()->removeUnresolvedReference(this);
else model()->addUnresolvedReference(this);
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include <complex>
#include <sndfile.hh>
#define kiss_fft_scalar float
#include "kiss_fft.h"
// https://stackoverflow.com/a/2284805/496459
template <typename Stream>
void reopen(Stream& pStream, const char * pFile,
std::ios_base::openmode pMode = std::ios_base::out)
{
pStream.close();
pStream.clear();
pStream.open(pFile, pMode);
}
int main(int argc, char *argv[])
{
const int I = 2;
const int D = 1;
const int N = 256;
const int M = I/D*N;
if (argc != 2) {
std::cerr << "Usage upsampling_algorithm_short_sequence <filename>\n";
return -1;
}
const std::string infilename = argv[argc-1];
const std::string resfilename = "res.wav";
SndfileHandle infile(infilename);
SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D);
// Input data
std::vector<kiss_fft_scalar> buffer(N);
if (infile.read(buffer.data(), N) != N) {
std::cerr << "Error reading " << N << " samples from " << infilename << ".\n";
}
// Kiss FFT configurations
auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(N, 0, NULL, NULL),
kiss_fft_free
};
auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(M, 1, NULL, NULL),
kiss_fft_free
};
if (fwd_cfg == nullptr || inv_cfg == nullptr) {
std::cerr << "Error allocating Kiss FFT configurations.\n";
}
// FFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> fwd_fft_in_buffer(N);
std::vector<std::complex<kiss_fft_scalar>> fwd_fft_out_buffer(N);
// IFFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> bwd_fft_in_buffer(M);
std::vector<std::complex<kiss_fft_scalar>> bwd_fft_out_buffer(M);
// Create FFT input buffer
std::ofstream ofs("fft_input_buffer.asc");
for (int i=0; i < N; ++i) {
fwd_fft_in_buffer[i] = std::complex<kiss_fft_scalar>(buffer[i], 0.0);
ofs << i << " " << fwd_fft_in_buffer[i].real() << " " << fwd_fft_in_buffer[i].imag() << "\n";
}
// Forward N points FFT
reopen(ofs, "fft_output_buffer.asc");
kiss_fft(fwd_cfg.get(), reinterpret_cast<kiss_fft_cpx*>(fwd_fft_in_buffer.data()), reinterpret_cast<kiss_fft_cpx*>(fwd_fft_out_buffer.data()));
for (int i=0; i < N; ++i) {
ofs << i << " " << fwd_fft_out_buffer[i].real() << " " << fwd_fft_out_buffer[i].imag() << "\n";
}
// Create IFFT input buffer
reopen(ofs, "ifft_input_buffer.asc");
for (int i=0; i < N/2; ++i) {
bwd_fft_in_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i];
}
for (int i=N/2; i < M - N/2; ++i) {
bwd_fft_in_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * std::complex<kiss_fft_scalar>(0.0, 0.0);
}
for (int i=M - N/2; i < M; ++i) {
bwd_fft_in_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N];
}
for (int i=0; i < M; ++i) {
ofs << i << " " << bwd_fft_in_buffer[i].real() << " " << bwd_fft_in_buffer[i].imag() << "\n";
}
// Backward M points IFFT
reopen(ofs, "ifft_output_buffer.asc");
kiss_fft(inv_cfg.get(), reinterpret_cast<kiss_fft_cpx*>(bwd_fft_in_buffer.data()), reinterpret_cast<kiss_fft_cpx*>(bwd_fft_out_buffer.data()));
for(int i=0; i < M; ++i) {
bwd_fft_out_buffer[i] = static_cast<kiss_fft_scalar>(1.0/M) * bwd_fft_out_buffer[i];
ofs << i << " " << bwd_fft_out_buffer[i].real() << " " << bwd_fft_out_buffer[i].imag() << "\n";
}
kiss_fft_cleanup();
return 0;
}
<commit_msg>Use std::transform to multiply vectors with scalars.<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include <complex>
#include <sndfile.hh>
#define kiss_fft_scalar float
#include "kiss_fft.h"
// https://stackoverflow.com/a/2284805/496459
template <typename Stream>
void reopen(Stream& pStream, const char * pFile,
std::ios_base::openmode pMode = std::ios_base::out)
{
pStream.close();
pStream.clear();
pStream.open(pFile, pMode);
}
int main(int argc, char *argv[])
{
const int I = 2;
const int D = 1;
const int N = 256;
const int M = I/D*N;
if (argc != 2) {
std::cerr << "Usage upsampling_algorithm_short_sequence <filename>\n";
return -1;
}
const std::string infilename = argv[argc-1];
const std::string resfilename = "res.wav";
SndfileHandle infile(infilename);
SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D);
// Input data
std::vector<kiss_fft_scalar> buffer(N);
if (infile.read(buffer.data(), N) != N) {
std::cerr << "Error reading " << N << " samples from " << infilename << ".\n";
}
// Kiss FFT configurations
auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(N, 0, NULL, NULL),
kiss_fft_free
};
auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(M, 1, NULL, NULL),
kiss_fft_free
};
if (fwd_cfg == nullptr || inv_cfg == nullptr) {
std::cerr << "Error allocating Kiss FFT configurations.\n";
}
// FFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> fwd_fft_in_buffer(N);
std::vector<std::complex<kiss_fft_scalar>> fwd_fft_out_buffer(N);
// IFFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> bwd_fft_in_buffer(M);
std::vector<std::complex<kiss_fft_scalar>> bwd_fft_out_buffer(M);
// Create FFT input buffer
std::ofstream ofs("fft_input_buffer.asc");
for (int i=0; i < N; ++i) {
fwd_fft_in_buffer[i] = std::complex<kiss_fft_scalar>(buffer[i], 0.0);
ofs << i << " " << fwd_fft_in_buffer[i].real() << " " << fwd_fft_in_buffer[i].imag() << "\n";
}
// Forward N points FFT
reopen(ofs, "fft_output_buffer.asc");
kiss_fft(fwd_cfg.get(), reinterpret_cast<kiss_fft_cpx*>(fwd_fft_in_buffer.data()), reinterpret_cast<kiss_fft_cpx*>(fwd_fft_out_buffer.data()));
for (int i=0; i < N; ++i) {
ofs << i << " " << fwd_fft_out_buffer[i].real() << " " << fwd_fft_out_buffer[i].imag() << "\n";
}
// Create IFFT input buffer
reopen(ofs, "ifft_input_buffer.asc");
for (int i=0; i < N/2; ++i) {
bwd_fft_in_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i];
}
for (int i=N/2; i < M - N/2; ++i) {
bwd_fft_in_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * std::complex<kiss_fft_scalar>(0.0, 0.0);
}
for (int i=M - N/2; i < M; ++i) {
bwd_fft_in_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N];
}
for (int i=0; i < M; ++i) {
ofs << i << " " << bwd_fft_in_buffer[i].real() << " " << bwd_fft_in_buffer[i].imag() << "\n";
}
// Backward M points IFFT
reopen(ofs, "ifft_output_buffer.asc");
kiss_fft(inv_cfg.get(), reinterpret_cast<kiss_fft_cpx*>(bwd_fft_in_buffer.data()), reinterpret_cast<kiss_fft_cpx*>(bwd_fft_out_buffer.data()));
std::transform(bwd_fft_out_buffer.begin(), bwd_fft_out_buffer.end(),
bwd_fft_out_buffer.begin(), std::bind1st(std::multiplies<std::complex<float>>(), 1.0/M ));
for(int i=0; i < M; ++i) {
ofs << i << " " << bwd_fft_out_buffer[i].real() << " " << bwd_fft_out_buffer[i].imag() << "\n";
}
kiss_fft_cleanup();
return 0;
}
<|endoftext|> |
<commit_before>#include <memory>
#include <poll.h>
#include <string>
#include <vector>
#include "../../helper/linux/helper.h"
#include "../../log.h"
#include "../../message.h"
#include "../../result.h"
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "cookie_jar.h"
#include "pipe.h"
#include "side_effect.h"
#include "watch_registry.h"
using std::endl;
using std::string;
using std::unique_ptr;
using std::vector;
// Platform-specific worker implementation for Linux systems.
class LinuxWorkerPlatform : public WorkerPlatform
{
public:
LinuxWorkerPlatform(WorkerThread *thread) : WorkerPlatform(thread)
{
report_errable(pipe);
report_errable(watch_registry);
freeze();
};
// Inform the listen() loop that one or more commands are waiting from the main thread.
Result<> wake() override { return pipe.signal(); }
// Main event loop. Use poll(2) to wait on I/O from either the Pipe or inotify events.
Result<> listen() override
{
pollfd to_poll[2];
to_poll[0].fd = pipe.get_read_fd();
to_poll[0].events = POLLIN;
to_poll[0].revents = 0;
to_poll[1].fd = registry.get_read_fd();
to_poll[1].events = POLLIN;
to_poll[1].revents = 0;
while (true) {
int result = poll(to_poll, 2, -1);
if (result < 0) {
return errno_result<>("Unable to poll");
}
if (result == 0) {
return error_result("Unexpected poll() timeout");
}
if ((to_poll[0].revents & (POLLIN | POLLERR)) != 0u) {
Result<> cr = pipe.consume();
if (cr.is_error()) return cr;
Result<> hr = handle_commands();
if (hr.is_error()) return hr;
}
if ((to_poll[1].revents & (POLLIN | POLLERR)) != 0u) {
MessageBuffer messages;
SideEffect side;
Result<> cr = registry.consume(messages, jar, side);
if (cr.is_error()) LOGGER << cr << endl;
side.enact_in(®istry, messages);
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) return er;
}
}
}
return error_result("Polling loop exited unexpectedly");
}
// Recursively watch a directory tree.
Result<bool> handle_add_command(CommandID /*command*/,
ChannelID channel,
const string &root_path,
bool recursive) override
{
vector<string> poll;
Result<> r = registry.add(channel, string(root_path), recursive, poll);
if (r.is_error()) return r.propagate<bool>();
if (!poll.empty()) {
vector<Message> poll_messages;
poll_messages.reserve(poll.size());
for (string &poll_root : poll) {
poll_messages.emplace_back(
CommandPayloadBuilder::add(channel, move(poll_root), recursive, poll.size()).build());
}
return emit_all(poll_messages.begin(), poll_messages.end()).propagate(false);
}
return ok_result(true);
}
// Unwatch a directory tree.
Result<bool> handle_remove_command(CommandID /*command*/, ChannelID channel) override
{
return registry.remove(channel).propagate(true);
}
private:
Pipe pipe;
WatchRegistry registry;
CookieJar jar;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new LinuxWorkerPlatform(thread));
}
<commit_msg>Yet Another Linux Compile Error<commit_after>#include <memory>
#include <poll.h>
#include <string>
#include <vector>
#include "../../helper/linux/helper.h"
#include "../../log.h"
#include "../../message.h"
#include "../../result.h"
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "cookie_jar.h"
#include "pipe.h"
#include "side_effect.h"
#include "watch_registry.h"
using std::endl;
using std::string;
using std::unique_ptr;
using std::vector;
// Platform-specific worker implementation for Linux systems.
class LinuxWorkerPlatform : public WorkerPlatform
{
public:
LinuxWorkerPlatform(WorkerThread *thread) : WorkerPlatform(thread)
{
report_errable(pipe);
report_errable(registry);
freeze();
};
// Inform the listen() loop that one or more commands are waiting from the main thread.
Result<> wake() override { return pipe.signal(); }
// Main event loop. Use poll(2) to wait on I/O from either the Pipe or inotify events.
Result<> listen() override
{
pollfd to_poll[2];
to_poll[0].fd = pipe.get_read_fd();
to_poll[0].events = POLLIN;
to_poll[0].revents = 0;
to_poll[1].fd = registry.get_read_fd();
to_poll[1].events = POLLIN;
to_poll[1].revents = 0;
while (true) {
int result = poll(to_poll, 2, -1);
if (result < 0) {
return errno_result<>("Unable to poll");
}
if (result == 0) {
return error_result("Unexpected poll() timeout");
}
if ((to_poll[0].revents & (POLLIN | POLLERR)) != 0u) {
Result<> cr = pipe.consume();
if (cr.is_error()) return cr;
Result<> hr = handle_commands();
if (hr.is_error()) return hr;
}
if ((to_poll[1].revents & (POLLIN | POLLERR)) != 0u) {
MessageBuffer messages;
SideEffect side;
Result<> cr = registry.consume(messages, jar, side);
if (cr.is_error()) LOGGER << cr << endl;
side.enact_in(®istry, messages);
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) return er;
}
}
}
return error_result("Polling loop exited unexpectedly");
}
// Recursively watch a directory tree.
Result<bool> handle_add_command(CommandID /*command*/,
ChannelID channel,
const string &root_path,
bool recursive) override
{
vector<string> poll;
Result<> r = registry.add(channel, string(root_path), recursive, poll);
if (r.is_error()) return r.propagate<bool>();
if (!poll.empty()) {
vector<Message> poll_messages;
poll_messages.reserve(poll.size());
for (string &poll_root : poll) {
poll_messages.emplace_back(
CommandPayloadBuilder::add(channel, move(poll_root), recursive, poll.size()).build());
}
return emit_all(poll_messages.begin(), poll_messages.end()).propagate(false);
}
return ok_result(true);
}
// Unwatch a directory tree.
Result<bool> handle_remove_command(CommandID /*command*/, ChannelID channel) override
{
return registry.remove(channel).propagate(true);
}
private:
Pipe pipe;
WatchRegistry registry;
CookieJar jar;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new LinuxWorkerPlatform(thread));
}
<|endoftext|> |
<commit_before>#include "rapid_pbd/landmarks.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "ros/ros.h"
namespace msgs = rapid_pbd_msgs;
namespace rapid {
namespace pbd {
void ProcessSurfaceBox(const rapid_pbd_msgs::Landmark& landmark_in,
rapid_pbd_msgs::Landmark* landmark_out) {
*landmark_out = landmark_in;
if (landmark_in.type != msgs::Landmark::SURFACE_BOX) {
ROS_ERROR("Called ProcessSurfaceBox with non-surface box landmark.");
return;
}
double x = landmark_in.surface_box_dims.x;
double y = landmark_in.surface_box_dims.y;
if (y == 0) {
ROS_ERROR("Surface box y dimension is 0!");
return;
}
if (x / y > 1) {
ROS_ERROR("surface_perception box has x > y!");
return;
}
double cylinder_ratio;
ros::param::param<double>("cylinder_ratio", cylinder_ratio, 0.85);
ROS_INFO("Cylinder ratio is %f/%f = %f (param is %f)", x, y, x / y,
cylinder_ratio);
if (x / y > cylinder_ratio) {
landmark_out->pose_stamped.pose.orientation.w = 1;
landmark_out->pose_stamped.pose.orientation.x = 0;
landmark_out->pose_stamped.pose.orientation.y = 0;
landmark_out->pose_stamped.pose.orientation.z = 0;
}
}
} // namespace pbd
} // namespace rapid
<commit_msg>Removed log statement.<commit_after>#include "rapid_pbd/landmarks.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "ros/ros.h"
namespace msgs = rapid_pbd_msgs;
namespace rapid {
namespace pbd {
void ProcessSurfaceBox(const rapid_pbd_msgs::Landmark& landmark_in,
rapid_pbd_msgs::Landmark* landmark_out) {
*landmark_out = landmark_in;
if (landmark_in.type != msgs::Landmark::SURFACE_BOX) {
ROS_ERROR("Called ProcessSurfaceBox with non-surface box landmark.");
return;
}
double x = landmark_in.surface_box_dims.x;
double y = landmark_in.surface_box_dims.y;
if (y == 0) {
ROS_ERROR("Surface box y dimension is 0!");
return;
}
if (x / y > 1) {
ROS_ERROR("surface_perception box has x > y!");
return;
}
double cylinder_ratio;
ros::param::param<double>("cylinder_ratio", cylinder_ratio, 0.85);
if (x / y > cylinder_ratio) {
landmark_out->pose_stamped.pose.orientation.w = 1;
landmark_out->pose_stamped.pose.orientation.x = 0;
landmark_out->pose_stamped.pose.orientation.y = 0;
landmark_out->pose_stamped.pose.orientation.z = 0;
}
}
} // namespace pbd
} // namespace rapid
<|endoftext|> |
<commit_before>#ifndef __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP
#define __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// C
#include <assert.h>
// STL
#include <vector>
#include <string>
#include <map>
//STDAIR
#include <stdair/bom/BomChildrenHolder.hpp>
#include <stdair/bom/BomIterator.hpp>
namespace stdair {
/** Template class aimed at holding a list and a map of children BOM
structure of a dedicated type. */
template <typename BOM_CONTENT_CHILD>
class BomChildrenHolderImp : public BomChildrenHolder {
friend class FacBomStructure;
/** Retrieve associated bom structure type. */
typedef typename BOM_CONTENT_CHILD::BomStructure_T BomStructure_T;
public:
/** Define lists of children BOM structures. */
typedef std::vector<BomStructure_T*> BomChildrenOrderedList_T;
typedef std::map<const std::string, BomStructure_T*> BomChildrenList_T;
/** Define the different types of iterators. */
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::const_iterator> ListConstIterator_T;
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::const_reverse_iterator> ListConstReverseIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::const_iterator> ListIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::const_reverse_iterator> ListReverseIterator_T;
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_iterator> MapConstIterator_T;
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_reverse_iterator> MapConstReverseIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_iterator> MapIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_reverse_iterator> MapReverseIterator_T;
public:
// /////////// Display support methods /////////
/** Dump a Business Object into an output stream.
@param ostream& the output stream. */
void toStream (std::ostream& ioOut) const { ioOut << toString(); }
/** Read a Business Object from an input stream.
@param istream& the input stream. */
void fromStream (std::istream& ioIn) { }
/** Get the serialised version of the Business Object. */
std::string toString() const { return std::string (""); }
/** Get a string describing the whole key (differentiating two objects
at any level). */
const std::string describeKey() const { return std::string (""); }
/** Get a string describing the short key (differentiating two objects
at the same level). */
const std::string describeShortKey() const { return std::string (""); }
/** Dump a Business Object into an output stream.
@param ostream& the output stream. */
void describeFull (std::ostringstream& ioOut) const {
// Initialise the index
unsigned short lIdx = 0;
for (typename BomChildrenOrderedList_T::const_iterator itChild =
_bomChildrenOrderedList.begin();
itChild != _bomChildrenOrderedList.end(); ++itChild, ++lIdx) {
const BomStructure_T* lCurrentChild_ptr = *itChild;
ioOut << "[" << lIdx << "]: ";
lCurrentChild_ptr->describeFull (ioOut);
}
}
// /////////// Iteration methods //////////
/** Initialise the internal const iterators on bom objects:
return the iterator at the begining of the list. */
ListConstIterator_T listConstIteratorBegin () const {
return _bomChildrenOrderedList.begin();
}
/** Initialise the internal const iterators on bom objects:
return the iterator past the end of the list. */
ListConstIterator_T listConstIteratorEnd () const {
return _bomChildrenOrderedList.end();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator at the rbegining of the list. */
ListConstReverseIterator_T listConstIteratorRBegin () const {
return _bomChildrenOrderedList.rbegin();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator past the rend of the list. */
ListConstReverseIterator_T listConstIteratorREnd () const {
return _bomChildrenOrderedList.rend();
}
/** Initialise the internal iterators on bom objects:
return the iterator at the begining of the list. */
ListIterator_T listIteratorBegin () {
return _bomChildrenOrderedList.begin();
}
/** Initialise the internal iterators on bom objects:
return the iterator past the end of the list. */
ListIterator_T listIteratorEnd () const {
return _bomChildrenOrderedList.end();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator at the rbegining of the list. */
ListReverseIterator_T listIteratorRBegin () const {
return _bomChildrenOrderedList.rbegin();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator past the rend of the list. */
ListReverseIterator_T listIteratorREnd () const {
return _bomChildrenOrderedList.rend();
}
/** Initialise the internal const iterators on bom objects:
return the iterator at the begining of the map. */
MapConstIterator_T mapConstIteratorBegin () const {
return _bomChildrenList.begin();
}
/** Initialise the internal const iterators on bom objects:
return the iterator past the end of the map. */
MapConstIterator_T mapConstIteratorEnd () const {
return _bomChildrenList.end();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator at the rbegining of the map. */
MapConstReverseIterator_T mapConstIteratorRBegin () const {
return _bomChildrenList.rbegin();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator past the rend of the map. */
MapConstReverseIterator_T mapConstIteratorREnd () const {
return _bomChildrenList.rend();
}
/** Initialise the internal iterators on bom objects:
return the iterator at the begining of the map. */
MapIterator_T mapIteratorBegin () const {
return _bomChildrenList.begin();
}
/** Initialise the internal iterators on bom objects:
return the iterator past the end of the map. */
MapIterator_T mapIteratorEnd () const {
return _bomChildrenList.end();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator at the rbegining of the map. */
MapReverseIterator_T mapIteratorRBegin () const {
return _bomChildrenList.rbegin();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator past the rend of the map. */
MapReverseIterator_T mapIteratorREnd () const {
return _bomChildrenList.rend();
}
private:
/** Constructors are private so as to force the usage of the Factory
layer. */
/** Default constructors. */
BomChildrenHolderImp () { }
BomChildrenHolderImp (const BomChildrenHolderImp&);
/** Destructor. */
~BomChildrenHolderImp() { }
private:
///////////// Attributes //////////////
/** List of children BOM structures. */
BomChildrenList_T _bomChildrenList;
/** Map of children BOM structures with their key. */
BomChildrenOrderedList_T _bomChildrenOrderedList;
};
}
#endif // __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP
<commit_msg>[Dev] Some small changes.<commit_after>#ifndef __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP
#define __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// C
#include <assert.h>
// STL
#include <vector>
#include <string>
#include <map>
//STDAIR
#include <stdair/bom/BomChildrenHolder.hpp>
#include <stdair/bom/BomIterator.hpp>
namespace stdair {
/** Template class aimed at holding a list and a map of children BOM
structure of a dedicated type. */
template <typename BOM_CONTENT_CHILD>
class BomChildrenHolderImp : public BomChildrenHolder {
friend class FacBomStructure;
/** Retrieve associated bom structure type. */
typedef typename BOM_CONTENT_CHILD::BomStructure_T BomStructure_T;
public:
/** Define lists of children BOM structures. */
typedef std::vector<BomStructure_T*> BomChildrenOrderedList_T;
typedef std::map<const std::string, BomStructure_T*> BomChildrenList_T;
/** Define the different types of iterators. */
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::const_iterator> ListConstIterator_T;
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::const_reverse_iterator> ListConstReverseIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::iterator> ListIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenOrderedList_T::const_reverse_iterator> ListReverseIterator_T;
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_iterator> MapConstIterator_T;
typedef BomConstIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_reverse_iterator> MapConstReverseIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_iterator> MapIterator_T;
typedef BomIterator_T<BOM_CONTENT_CHILD,
typename BomChildrenList_T::const_reverse_iterator> MapReverseIterator_T;
public:
// /////////// Display support methods /////////
/** Dump a Business Object into an output stream.
@param ostream& the output stream. */
void toStream (std::ostream& ioOut) const { ioOut << toString(); }
/** Read a Business Object from an input stream.
@param istream& the input stream. */
void fromStream (std::istream& ioIn) { }
/** Get the serialised version of the Business Object. */
std::string toString() const { return std::string (""); }
/** Get a string describing the whole key (differentiating two objects
at any level). */
const std::string describeKey() const { return std::string (""); }
/** Get a string describing the short key (differentiating two objects
at the same level). */
const std::string describeShortKey() const { return std::string (""); }
/** Dump a Business Object into an output stream.
@param ostream& the output stream. */
void describeFull (std::ostringstream& ioOut) const {
// Initialise the index
unsigned short lIdx = 0;
for (typename BomChildrenOrderedList_T::const_iterator itChild =
_bomChildrenOrderedList.begin();
itChild != _bomChildrenOrderedList.end(); ++itChild, ++lIdx) {
const BomStructure_T* lCurrentChild_ptr = *itChild;
ioOut << "[" << lIdx << "]: ";
lCurrentChild_ptr->describeFull (ioOut);
}
}
// /////////// Iteration methods //////////
/** Initialise the internal const iterators on bom objects:
return the iterator at the begining of the list. */
ListConstIterator_T listConstIteratorBegin () const {
return _bomChildrenOrderedList.begin();
}
/** Initialise the internal const iterators on bom objects:
return the iterator past the end of the list. */
ListConstIterator_T listConstIteratorEnd () const {
return _bomChildrenOrderedList.end();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator at the rbegining of the list. */
ListConstReverseIterator_T listConstIteratorRBegin () const {
return _bomChildrenOrderedList.rbegin();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator past the rend of the list. */
ListConstReverseIterator_T listConstIteratorREnd () const {
return _bomChildrenOrderedList.rend();
}
/** Initialise the internal iterators on bom objects:
return the iterator at the begining of the list. */
ListIterator_T listIteratorBegin () {
return _bomChildrenOrderedList.begin();
}
/** Initialise the internal iterators on bom objects:
return the iterator past the end of the list. */
ListIterator_T listIteratorEnd () const {
return _bomChildrenOrderedList.end();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator at the rbegining of the list. */
ListReverseIterator_T listIteratorRBegin () const {
return _bomChildrenOrderedList.rbegin();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator past the rend of the list. */
ListReverseIterator_T listIteratorREnd () const {
return _bomChildrenOrderedList.rend();
}
/** Initialise the internal const iterators on bom objects:
return the iterator at the begining of the map. */
MapConstIterator_T mapConstIteratorBegin () const {
return _bomChildrenList.begin();
}
/** Initialise the internal const iterators on bom objects:
return the iterator past the end of the map. */
MapConstIterator_T mapConstIteratorEnd () const {
return _bomChildrenList.end();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator at the rbegining of the map. */
MapConstReverseIterator_T mapConstIteratorRBegin () const {
return _bomChildrenList.rbegin();
}
/** Initialise the internal const reverse iterators on bom objects:
return the reverse iterator past the rend of the map. */
MapConstReverseIterator_T mapConstIteratorREnd () const {
return _bomChildrenList.rend();
}
/** Initialise the internal iterators on bom objects:
return the iterator at the begining of the map. */
MapIterator_T mapIteratorBegin () const {
return _bomChildrenList.begin();
}
/** Initialise the internal iterators on bom objects:
return the iterator past the end of the map. */
MapIterator_T mapIteratorEnd () const {
return _bomChildrenList.end();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator at the rbegining of the map. */
MapReverseIterator_T mapIteratorRBegin () const {
return _bomChildrenList.rbegin();
}
/** Initialise the internal reverse iterators on bom objects:
return the reverse iterator past the rend of the map. */
MapReverseIterator_T mapIteratorREnd () const {
return _bomChildrenList.rend();
}
private:
/** Constructors are private so as to force the usage of the Factory
layer. */
/** Default constructors. */
BomChildrenHolderImp () { }
BomChildrenHolderImp (const BomChildrenHolderImp&);
/** Destructor. */
~BomChildrenHolderImp() { }
private:
///////////// Attributes //////////////
/** List of children BOM structures. */
BomChildrenList_T _bomChildrenList;
/** Map of children BOM structures with their key. */
BomChildrenOrderedList_T _bomChildrenOrderedList;
};
}
#endif // __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP
<|endoftext|> |
<commit_before>// Copyright 2007 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test prog.cc, compile.cc
#include <string>
#include <vector>
#include "util/test.h"
#include "re2/regexp.h"
#include "re2/prog.h"
DEFINE_string(show, "", "regular expression to compile and dump");
namespace re2 {
// Simple input/output tests checking that
// the regexp compiles to the expected code.
// These are just to sanity check the basic implementation.
// The real confidence tests happen by testing the NFA/DFA
// that run the compiled code.
struct Test {
const char* regexp;
const char* code;
};
static Test tests[] = {
{ "a",
"3. byte [61-61] -> 4\n"
"4. match! 0\n" },
{ "ab",
"3. byte [61-61] -> 4\n"
"4. byte [62-62] -> 5\n"
"5. match! 0\n" },
{ "a|c",
"3+ byte [61-61] -> 5\n"
"4. byte [63-63] -> 5\n"
"5. match! 0\n" },
{ "a|b",
"3. byte [61-62] -> 4\n"
"4. match! 0\n" },
{ "[ab]",
"3. byte [61-62] -> 4\n"
"4. match! 0\n" },
{ "a+",
"3. byte [61-61] -> 4\n"
"4+ nop -> 3\n"
"5. match! 0\n" },
{ "a+?",
"3. byte [61-61] -> 4\n"
"4+ match! 0\n"
"5. nop -> 3\n" },
{ "a*",
"3+ byte [61-61] -> 3\n"
"4. match! 0\n" },
{ "a*?",
"3+ match! 0\n"
"4. byte [61-61] -> 3\n" },
{ "a?",
"3+ byte [61-61] -> 5\n"
"4. nop -> 5\n"
"5. match! 0\n" },
{ "a??",
"3+ nop -> 5\n"
"4. byte [61-61] -> 5\n"
"5. match! 0\n" },
{ "a{4}",
"3. byte [61-61] -> 4\n"
"4. byte [61-61] -> 5\n"
"5. byte [61-61] -> 6\n"
"6. byte [61-61] -> 7\n"
"7. match! 0\n" },
{ "(a)",
"3. capture 2 -> 4\n"
"4. byte [61-61] -> 5\n"
"5. capture 3 -> 6\n"
"6. match! 0\n" },
{ "(?:a)",
"3. byte [61-61] -> 4\n"
"4. match! 0\n" },
{ "",
"3. match! 0\n" },
{ ".",
"3+ byte [00-09] -> 5\n"
"4. byte [0b-ff] -> 5\n"
"5. match! 0\n" },
{ "[^ab]",
"3+ byte [00-09] -> 6\n"
"4+ byte [0b-60] -> 6\n"
"5. byte [63-ff] -> 6\n"
"6. match! 0\n" },
{ "[Aa]",
"3. byte/i [61-61] -> 4\n"
"4. match! 0\n" },
{ "\\C+",
"3. byte [00-ff] -> 4\n"
"4+ altmatch -> 5 | 6\n"
"5+ nop -> 3\n"
"6. match! 0\n" },
{ "\\C*",
"3+ altmatch -> 4 | 5\n"
"4+ byte [00-ff] -> 3\n"
"5. match! 0\n" },
{ "\\C?",
"3+ byte [00-ff] -> 5\n"
"4. nop -> 5\n"
"5. match! 0\n" },
// Issue 20992936
{ "[[-`]",
"3. byte [5b-60] -> 4\n"
"4. match! 0\n" },
};
TEST(TestRegexpCompileToProg, Simple) {
int failed = 0;
for (int i = 0; i < arraysize(tests); i++) {
const re2::Test& t = tests[i];
Regexp* re = Regexp::Parse(t.regexp, Regexp::PerlX|Regexp::Latin1, NULL);
if (re == NULL) {
LOG(ERROR) << "Cannot parse: " << t.regexp;
failed++;
continue;
}
Prog* prog = re->CompileToProg(0);
if (prog == NULL) {
LOG(ERROR) << "Cannot compile: " << t.regexp;
re->Decref();
failed++;
continue;
}
CHECK(re->CompileToProg(1) == NULL);
string s = prog->Dump();
if (s != t.code) {
LOG(ERROR) << "Incorrect compiled code for: " << t.regexp;
LOG(ERROR) << "Want:\n" << t.code;
LOG(ERROR) << "Got:\n" << s;
failed++;
}
delete prog;
re->Decref();
}
EXPECT_EQ(failed, 0);
}
// The distinct byte ranges involved in the Latin-1 dot ([^\n]).
static struct Latin1ByteRange {
int lo;
int hi;
} latin1ranges[] = {
{ 0x00, 0x09 },
{ 0x0A, 0x0A },
{ 0x0B, 0xFF },
};
TEST(TestCompile, Latin1Ranges) {
Regexp* re = Regexp::Parse(".", Regexp::PerlX|Regexp::Latin1, NULL);
EXPECT_TRUE(re != NULL);
Prog* prog = re->CompileToProg(0);
EXPECT_TRUE(prog != NULL);
EXPECT_EQ(prog->bytemap_range(), arraysize(latin1ranges));
for (int i = 0; i < arraysize(latin1ranges); i++)
for (int j = latin1ranges[i].lo; j <= latin1ranges[i].hi; j++)
EXPECT_EQ(prog->bytemap()[j], i) << " byte " << j;
delete prog;
re->Decref();
}
// The distinct byte ranges involved in the UTF-8 dot ([^\n]).
// Once, erroneously split between 0x3f and 0x40 because it is
// a 6-bit boundary.
static struct UTF8ByteRange {
int lo;
int hi;
} utf8ranges[] = {
{ 0x00, 0x09 },
{ 0x0A, 0x0A },
{ 0x0B, 0x7F },
{ 0x80, 0x8F },
{ 0x90, 0x9F },
{ 0xA0, 0xBF },
{ 0xC0, 0xC1 },
{ 0xC2, 0xDF },
{ 0xE0, 0xE0 },
{ 0xE1, 0xEF },
{ 0xF0, 0xF0 },
{ 0xF1, 0xF3 },
{ 0xF4, 0xF4 },
{ 0xF5, 0xFF },
};
TEST(TestCompile, UTF8Ranges) {
Regexp* re = Regexp::Parse(".", Regexp::PerlX, NULL);
EXPECT_TRUE(re != NULL);
Prog* prog = re->CompileToProg(0);
EXPECT_TRUE(prog != NULL);
EXPECT_EQ(prog->bytemap_range(), arraysize(utf8ranges));
for (int i = 0; i < arraysize(utf8ranges); i++)
for (int j = utf8ranges[i].lo; j <= utf8ranges[i].hi; j++)
EXPECT_EQ(prog->bytemap()[j], i) << " byte " << j;
delete prog;
re->Decref();
}
TEST(TestCompile, InsufficientMemory) {
Regexp* re = Regexp::Parse(
"^(?P<name1>[^\\s]+)\\s+(?P<name2>[^\\s]+)\\s+(?P<name3>.+)$",
Regexp::LikePerl, NULL);
EXPECT_TRUE(re != NULL);
Prog* prog = re->CompileToProg(920);
// If the memory budget has been exhausted, compilation should fail
// and return NULL instead of trying to do anything with NoMatch().
EXPECT_TRUE(prog == NULL);
re->Decref();
}
static void Dump(StringPiece pattern, Regexp::ParseFlags flags,
string* forward, string* reverse) {
Regexp* re = Regexp::Parse(pattern, flags, NULL);
EXPECT_TRUE(re != NULL);
if (forward != NULL) {
Prog* prog = re->CompileToProg(0);
EXPECT_TRUE(prog != NULL);
*forward = prog->Dump();
delete prog;
}
if (reverse != NULL) {
Prog* prog = re->CompileToReverseProg(0);
EXPECT_TRUE(prog != NULL);
*reverse = prog->Dump();
delete prog;
}
re->Decref();
}
TEST(TestCompile, Bug26705922) {
// Bug in the compiler caused inefficient bytecode to be generated for Unicode
// groups: common suffixes were cached, but common prefixes were not factored.
string forward, reverse;
Dump("[\\x{10000}\\x{10010}]", Regexp::LikePerl, &forward, &reverse);
EXPECT_EQ("3. byte [f0-f0] -> 4\n"
"4. byte [90-90] -> 5\n"
"5. byte [80-80] -> 6\n"
"6+ byte [80-80] -> 8\n"
"7. byte [90-90] -> 8\n"
"8. match! 0\n",
forward);
EXPECT_EQ("3+ byte [80-80] -> 5\n"
"4. byte [90-90] -> 5\n"
"5. byte [80-80] -> 6\n"
"6. byte [90-90] -> 7\n"
"7. byte [f0-f0] -> 8\n"
"8. match! 0\n",
reverse);
Dump("[\\x{8000}-\\x{10FFF}]", Regexp::LikePerl, &forward, &reverse);
EXPECT_EQ("3+ byte [e8-ef] -> 5\n"
"4. byte [f0-f0] -> 8\n"
"5. byte [80-bf] -> 6\n"
"6. byte [80-bf] -> 7\n"
"7. match! 0\n"
"8. byte [90-90] -> 5\n",
forward);
EXPECT_EQ("3. byte [80-bf] -> 4\n"
"4. byte [80-bf] -> 5\n"
"5+ byte [e8-ef] -> 7\n"
"6. byte [90-90] -> 8\n"
"7. match! 0\n"
"8. byte [f0-f0] -> 7\n",
reverse);
Dump("[\\x{80}-\\x{10FFFF}]", Regexp::LikePerl, NULL, &reverse);
EXPECT_EQ("3. byte [80-bf] -> 4\n"
"4+ byte [c2-df] -> 7\n"
"5+ byte [a0-bf] -> 8\n"
"6. byte [80-bf] -> 9\n"
"7. match! 0\n"
"8. byte [e0-e0] -> 7\n"
"9+ byte [e1-ef] -> 7\n"
"10+ byte [90-bf] -> 13\n"
"11+ byte [80-bf] -> 14\n"
"12. byte [80-8f] -> 15\n"
"13. byte [f0-f0] -> 7\n"
"14. byte [f1-f3] -> 7\n"
"15. byte [f4-f4] -> 7\n",
reverse);
}
} // namespace re2
<commit_msg>Make the bytemap tests use DumpByteMap().<commit_after>// Copyright 2007 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test prog.cc, compile.cc
#include <string>
#include <vector>
#include "util/test.h"
#include "re2/regexp.h"
#include "re2/prog.h"
DEFINE_string(show, "", "regular expression to compile and dump");
namespace re2 {
// Simple input/output tests checking that
// the regexp compiles to the expected code.
// These are just to sanity check the basic implementation.
// The real confidence tests happen by testing the NFA/DFA
// that run the compiled code.
struct Test {
const char* regexp;
const char* code;
};
static Test tests[] = {
{ "a",
"3. byte [61-61] -> 4\n"
"4. match! 0\n" },
{ "ab",
"3. byte [61-61] -> 4\n"
"4. byte [62-62] -> 5\n"
"5. match! 0\n" },
{ "a|c",
"3+ byte [61-61] -> 5\n"
"4. byte [63-63] -> 5\n"
"5. match! 0\n" },
{ "a|b",
"3. byte [61-62] -> 4\n"
"4. match! 0\n" },
{ "[ab]",
"3. byte [61-62] -> 4\n"
"4. match! 0\n" },
{ "a+",
"3. byte [61-61] -> 4\n"
"4+ nop -> 3\n"
"5. match! 0\n" },
{ "a+?",
"3. byte [61-61] -> 4\n"
"4+ match! 0\n"
"5. nop -> 3\n" },
{ "a*",
"3+ byte [61-61] -> 3\n"
"4. match! 0\n" },
{ "a*?",
"3+ match! 0\n"
"4. byte [61-61] -> 3\n" },
{ "a?",
"3+ byte [61-61] -> 5\n"
"4. nop -> 5\n"
"5. match! 0\n" },
{ "a??",
"3+ nop -> 5\n"
"4. byte [61-61] -> 5\n"
"5. match! 0\n" },
{ "a{4}",
"3. byte [61-61] -> 4\n"
"4. byte [61-61] -> 5\n"
"5. byte [61-61] -> 6\n"
"6. byte [61-61] -> 7\n"
"7. match! 0\n" },
{ "(a)",
"3. capture 2 -> 4\n"
"4. byte [61-61] -> 5\n"
"5. capture 3 -> 6\n"
"6. match! 0\n" },
{ "(?:a)",
"3. byte [61-61] -> 4\n"
"4. match! 0\n" },
{ "",
"3. match! 0\n" },
{ ".",
"3+ byte [00-09] -> 5\n"
"4. byte [0b-ff] -> 5\n"
"5. match! 0\n" },
{ "[^ab]",
"3+ byte [00-09] -> 6\n"
"4+ byte [0b-60] -> 6\n"
"5. byte [63-ff] -> 6\n"
"6. match! 0\n" },
{ "[Aa]",
"3. byte/i [61-61] -> 4\n"
"4. match! 0\n" },
{ "\\C+",
"3. byte [00-ff] -> 4\n"
"4+ altmatch -> 5 | 6\n"
"5+ nop -> 3\n"
"6. match! 0\n" },
{ "\\C*",
"3+ altmatch -> 4 | 5\n"
"4+ byte [00-ff] -> 3\n"
"5. match! 0\n" },
{ "\\C?",
"3+ byte [00-ff] -> 5\n"
"4. nop -> 5\n"
"5. match! 0\n" },
// Issue 20992936
{ "[[-`]",
"3. byte [5b-60] -> 4\n"
"4. match! 0\n" },
};
TEST(TestRegexpCompileToProg, Simple) {
int failed = 0;
for (int i = 0; i < arraysize(tests); i++) {
const re2::Test& t = tests[i];
Regexp* re = Regexp::Parse(t.regexp, Regexp::PerlX|Regexp::Latin1, NULL);
if (re == NULL) {
LOG(ERROR) << "Cannot parse: " << t.regexp;
failed++;
continue;
}
Prog* prog = re->CompileToProg(0);
if (prog == NULL) {
LOG(ERROR) << "Cannot compile: " << t.regexp;
re->Decref();
failed++;
continue;
}
CHECK(re->CompileToProg(1) == NULL);
string s = prog->Dump();
if (s != t.code) {
LOG(ERROR) << "Incorrect compiled code for: " << t.regexp;
LOG(ERROR) << "Want:\n" << t.code;
LOG(ERROR) << "Got:\n" << s;
failed++;
}
delete prog;
re->Decref();
}
EXPECT_EQ(failed, 0);
}
static void DumpByteMap(StringPiece pattern, Regexp::ParseFlags flags,
string* bytemap) {
Regexp* re = Regexp::Parse(pattern, flags, NULL);
EXPECT_TRUE(re != NULL);
Prog* prog = re->CompileToProg(0);
EXPECT_TRUE(prog != NULL);
*bytemap = prog->DumpByteMap();
delete prog;
re->Decref();
}
TEST(TestCompile, Latin1Ranges) {
// The distinct byte ranges involved in the Latin-1 dot ([^\n]).
string bytemap;
DumpByteMap(".", Regexp::PerlX|Regexp::Latin1, &bytemap);
EXPECT_EQ("[00-09] -> 0\n"
"[0a-0a] -> 1\n"
"[0b-ff] -> 2\n",
bytemap);
}
TEST(TestCompile, UTF8Ranges) {
// The distinct byte ranges involved in the UTF-8 dot ([^\n]).
// Once, erroneously split between 0x3f and 0x40 because it is
// a 6-bit boundary.
string bytemap;
DumpByteMap(".", Regexp::PerlX, &bytemap);
EXPECT_EQ("[00-09] -> 0\n"
"[0a-0a] -> 1\n"
"[0b-7f] -> 2\n"
"[80-8f] -> 3\n"
"[90-9f] -> 4\n"
"[a0-bf] -> 5\n"
"[c0-c1] -> 6\n"
"[c2-df] -> 7\n"
"[e0-e0] -> 8\n"
"[e1-ef] -> 9\n"
"[f0-f0] -> 10\n"
"[f1-f3] -> 11\n"
"[f4-f4] -> 12\n"
"[f5-ff] -> 13\n",
bytemap);
}
TEST(TestCompile, InsufficientMemory) {
Regexp* re = Regexp::Parse(
"^(?P<name1>[^\\s]+)\\s+(?P<name2>[^\\s]+)\\s+(?P<name3>.+)$",
Regexp::LikePerl, NULL);
EXPECT_TRUE(re != NULL);
Prog* prog = re->CompileToProg(920);
// If the memory budget has been exhausted, compilation should fail
// and return NULL instead of trying to do anything with NoMatch().
EXPECT_TRUE(prog == NULL);
re->Decref();
}
static void Dump(StringPiece pattern, Regexp::ParseFlags flags,
string* forward, string* reverse) {
Regexp* re = Regexp::Parse(pattern, flags, NULL);
EXPECT_TRUE(re != NULL);
if (forward != NULL) {
Prog* prog = re->CompileToProg(0);
EXPECT_TRUE(prog != NULL);
*forward = prog->Dump();
delete prog;
}
if (reverse != NULL) {
Prog* prog = re->CompileToReverseProg(0);
EXPECT_TRUE(prog != NULL);
*reverse = prog->Dump();
delete prog;
}
re->Decref();
}
TEST(TestCompile, Bug26705922) {
// Bug in the compiler caused inefficient bytecode to be generated for Unicode
// groups: common suffixes were cached, but common prefixes were not factored.
string forward, reverse;
Dump("[\\x{10000}\\x{10010}]", Regexp::LikePerl, &forward, &reverse);
EXPECT_EQ("3. byte [f0-f0] -> 4\n"
"4. byte [90-90] -> 5\n"
"5. byte [80-80] -> 6\n"
"6+ byte [80-80] -> 8\n"
"7. byte [90-90] -> 8\n"
"8. match! 0\n",
forward);
EXPECT_EQ("3+ byte [80-80] -> 5\n"
"4. byte [90-90] -> 5\n"
"5. byte [80-80] -> 6\n"
"6. byte [90-90] -> 7\n"
"7. byte [f0-f0] -> 8\n"
"8. match! 0\n",
reverse);
Dump("[\\x{8000}-\\x{10FFF}]", Regexp::LikePerl, &forward, &reverse);
EXPECT_EQ("3+ byte [e8-ef] -> 5\n"
"4. byte [f0-f0] -> 8\n"
"5. byte [80-bf] -> 6\n"
"6. byte [80-bf] -> 7\n"
"7. match! 0\n"
"8. byte [90-90] -> 5\n",
forward);
EXPECT_EQ("3. byte [80-bf] -> 4\n"
"4. byte [80-bf] -> 5\n"
"5+ byte [e8-ef] -> 7\n"
"6. byte [90-90] -> 8\n"
"7. match! 0\n"
"8. byte [f0-f0] -> 7\n",
reverse);
Dump("[\\x{80}-\\x{10FFFF}]", Regexp::LikePerl, NULL, &reverse);
EXPECT_EQ("3. byte [80-bf] -> 4\n"
"4+ byte [c2-df] -> 7\n"
"5+ byte [a0-bf] -> 8\n"
"6. byte [80-bf] -> 9\n"
"7. match! 0\n"
"8. byte [e0-e0] -> 7\n"
"9+ byte [e1-ef] -> 7\n"
"10+ byte [90-bf] -> 13\n"
"11+ byte [80-bf] -> 14\n"
"12. byte [80-8f] -> 15\n"
"13. byte [f0-f0] -> 7\n"
"14. byte [f1-f3] -> 7\n"
"15. byte [f4-f4] -> 7\n",
reverse);
}
} // namespace re2
<|endoftext|> |
<commit_before>AliAnalysisTaskJetSpectrum2 *AddTaskJetSpectrum2(const char* bRec = "jets",const char* bGen = "jetsAODMC_UA104",const char* bBkg="",UInt_t filterMask = 32, Int_t iPhysicsSelection = 1,UInt_t iEventSelectionMask = 0,Bool_t kBackground=kTRUE,Int_t iFillCorrBkg = 0);
AliAnalysisTaskJetSpectrum2 *AddTaskJetSpectrum2Delta(UInt_t filterMask = 32,Bool_t kUseAODMC = kFALSE,Int_t iPhysicsSelection = 1,UInt_t iFlag = 0xfffffff, UInt_t iEventSelectionMask = 0,Bool_t kBackground = kTRUE){
AliAnalysisTaskJetSpectrum2 *js = 0;
TString cBack = ""; //
if(kUseAODMC){
if(iFlag&(1<<0)){ // UA104
js = AddTaskJetSpectrum2("jets","jetsAODMC_UA104",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jets","jetsAODMC2_UA104",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<1)){ // ANTIKT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC2_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
// cross check MC only background subtration
js = AddTaskJetSpectrum2("jetsAODMC2_FASTJET04","jetsAODMC_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<2)){ // KT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","jetsAODMC_FASTKT04",cBack.Data(),filterMask,iPhysicsSelection,iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","jetsAODMC2_FASTKT04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<3)){ // SISCONE 04
js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","jetsAODMC_SISCONE04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","jetsAODMC2_SISCONE04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
// here can go other radii
}
else { // only the data ... no MC
if(iFlag&(1<<0)){ // UA104
js = AddTaskJetSpectrum2("jets","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<1)){ // ANTIKT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<2)){ // KT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","",cBack.Data(),filterMask,iPhysicsSelection,iEventSelectionMask,kBackground);
}
if(iFlag&(1<<3)){ // SISCONE 04
js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
}
/*
if(iFlag&(1<<7))js = AddTaskJetSpectrum2("jets","jetsAOD_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<8))js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<9))js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<10))js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<11)){
js = AddTaskJetSpectrum2("jetsAOD_UA107","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
if(iFlag&(1<<12)){
js = AddTaskJetSpectrum2("jetsAOD_FASTJET07","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
if(iFlag&(1<<13)){
js = AddTaskJetSpectrum2("jetsAOD_FASTKT07","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
if(iFlag&(1<<14)){
js = AddTaskJetSpectrum2("jetsAOD_SISCONE07","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
*/
return js;
}
AliAnalysisTaskJetSpectrum2 *AddTaskJetSpectrum2(const char* bRec,const char* bGen ,const char* bBkg,UInt_t filterMask,Int_t iPhysicsSelection,UInt_t iEventSelectionMask,Bool_t kBackground,Int_t iFillCorrBkg)
{
// Creates a jet fider task, configures it and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskJetSpectrum2", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskJetSpectrum2", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType();
TString typeRec(bRec);
TString typeGen(bGen);
typeGen.ToUpper();
typeRec.ToUpper();
TString bBkgName = bBkg;
if(kBackground&&bBkgName.Length()==0){
if(typeGen.Contains("AODMC2"))bBkgName = "jeteventbackground_clustersAODMC2_KT06";
else bBkgName = "jeteventbackground_clustersAOD_KT06";
}
// Create the task and configure it.
//===========================================================================
if(iFillCorrBkg)bGen = Form("SubBkg%d",iFillCorrBkg);
AliAnalysisTaskJetSpectrum2* pwg4spec = new AliAnalysisTaskJetSpectrum2(Form("JetSpectrum2%s-%s_%010d",bRec,bGen,iEventSelectionMask));
// or a config file
// pwg4spec->SetAnalysisType(AliAnalysisTaskJetSpectrum2::kAnaMC);
// if(iAODanalysis)pwg4spec->SetAODInput(kTRUE);
// pwg4spec->SetDebugLevel(11);
if(iFillCorrBkg)pwg4spec->SetBranchGen("");
else pwg4spec->SetBranchGen(bGen);
pwg4spec->SetBranchRec(bRec);
if(bBkgName.Length()>0)pwg4spec->SetBranchBkg(bBkgName.Data());
pwg4spec->SetFilterMask(filterMask);
pwg4spec->SetUseGlobalSelection(kTRUE);
pwg4spec->SetMinJetPt(5.);
pwg4spec->SetBkgSubtraction(kBackground);
if(type == "AOD"){
// Assume all jet are produced already
pwg4spec->SetAODJetInput(kTRUE);
pwg4spec->SetAODTrackInput(kTRUE);
pwg4spec->SetAODMCInput(kTRUE);
}
else{
if(mgr->GetMCtruthEventHandler()){
pwg4spec-> SetAnalysisType(AliAnalysisTaskJetSpectrum2::kAnaMCESD);
}
}
if(typeRec.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAODMCChargedAcceptance);
}
else if (typeRec.Contains("AODMC2")){
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAODMCCharged);
}
else if (typeRec.Contains("AODMC")){
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAODMCAll);
}
else { // catch akk use AOD
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAOD);
}
if(typeGen.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAODMCChargedAcceptance);
}
else if (typeGen.Contains("AODMC2")){
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAODMCCharged);
}
else if (typeGen.Contains("AODMC")){
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAODMCAll);
}
else if (typeGen.Length()>0){ // catch all use AOD
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAOD);
}
if(iPhysicsSelection)pwg4spec->SelectCollisionCandidates();
if(iEventSelectionMask)pwg4spec->SetEventSelectionMask(iEventSelectionMask);
mgr->AddTask(pwg4spec);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
AliAnalysisDataContainer *coutput1_Spec = mgr->CreateContainer(Form("pwg4spec2_%s_%s_%010d",bRec,bGen,iEventSelectionMask),TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:PWG4_spec2_%s_%s_%010d",AliAnalysisManager::GetCommonFileName(),bRec,bGen,iEventSelectionMask));
mgr->ConnectInput (pwg4spec, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (pwg4spec, 0, mgr->GetCommonOutputContainer());
mgr->ConnectOutput (pwg4spec, 1, coutput1_Spec );
return pwg4spec;
}
<commit_msg>fixed typo gen -> rec<commit_after>AliAnalysisTaskJetSpectrum2 *AddTaskJetSpectrum2(const char* bRec = "jets",const char* bGen = "jetsAODMC_UA104",const char* bBkg="",UInt_t filterMask = 32, Int_t iPhysicsSelection = 1,UInt_t iEventSelectionMask = 0,Bool_t kBackground=kTRUE,Int_t iFillCorrBkg = 0);
AliAnalysisTaskJetSpectrum2 *AddTaskJetSpectrum2Delta(UInt_t filterMask = 32,Bool_t kUseAODMC = kFALSE,Int_t iPhysicsSelection = 1,UInt_t iFlag = 0xfffffff, UInt_t iEventSelectionMask = 0,Bool_t kBackground = kTRUE){
AliAnalysisTaskJetSpectrum2 *js = 0;
TString cBack = ""; //
if(kUseAODMC){
if(iFlag&(1<<0)){ // UA104
js = AddTaskJetSpectrum2("jets","jetsAODMC_UA104",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jets","jetsAODMC2_UA104",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<1)){ // ANTIKT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC2_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
// cross check MC only background subtration
js = AddTaskJetSpectrum2("jetsAODMC2_FASTJET04","jetsAODMC_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<2)){ // KT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","jetsAODMC_FASTKT04",cBack.Data(),filterMask,iPhysicsSelection,iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","jetsAODMC2_FASTKT04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<3)){ // SISCONE 04
js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","jetsAODMC_SISCONE04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","jetsAODMC2_SISCONE04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
// here can go other radii
}
else { // only the data ... no MC
if(iFlag&(1<<0)){ // UA104
js = AddTaskJetSpectrum2("jets","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<1)){ // ANTIKT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
if(iFlag&(1<<2)){ // KT 04
js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","",cBack.Data(),filterMask,iPhysicsSelection,iEventSelectionMask,kBackground);
}
if(iFlag&(1<<3)){ // SISCONE 04
js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
}
}
/*
if(iFlag&(1<<7))js = AddTaskJetSpectrum2("jets","jetsAOD_FASTJET04",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<8))js = AddTaskJetSpectrum2("jetsAOD_FASTJET04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<9))js = AddTaskJetSpectrum2("jetsAOD_FASTKT04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<10))js = AddTaskJetSpectrum2("jetsAOD_SISCONE04","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
if(iFlag&(1<<11)){
js = AddTaskJetSpectrum2("jetsAOD_UA107","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
if(iFlag&(1<<12)){
js = AddTaskJetSpectrum2("jetsAOD_FASTJET07","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
if(iFlag&(1<<13)){
js = AddTaskJetSpectrum2("jetsAOD_FASTKT07","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
if(iFlag&(1<<14)){
js = AddTaskJetSpectrum2("jetsAOD_SISCONE07","",cBack.Data(),filterMask,iPhysicsSelection, iEventSelectionMask,kBackground);
js->SetRecEtaWindow(0.2);
}
*/
return js;
}
AliAnalysisTaskJetSpectrum2 *AddTaskJetSpectrum2(const char* bRec,const char* bGen ,const char* bBkg,UInt_t filterMask,Int_t iPhysicsSelection,UInt_t iEventSelectionMask,Bool_t kBackground,Int_t iFillCorrBkg)
{
// Creates a jet fider task, configures it and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskJetSpectrum2", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskJetSpectrum2", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType();
TString typeRec(bRec);
TString typeGen(bGen);
typeGen.ToUpper();
typeRec.ToUpper();
TString bBkgName = bBkg;
if(kBackground&&bBkgName.Length()==0){
if(typeRec.Contains("AODMC2"))bBkgName = "jeteventbackground_clustersAODMC2_KT06";
else bBkgName = "jeteventbackground_clustersAOD_KT06";
}
// Create the task and configure it.
//===========================================================================
if(iFillCorrBkg)bGen = Form("SubBkg%d",iFillCorrBkg);
AliAnalysisTaskJetSpectrum2* pwg4spec = new AliAnalysisTaskJetSpectrum2(Form("JetSpectrum2%s-%s_%010d",bRec,bGen,iEventSelectionMask));
pwg4spec->SetFillCorrBkg(iFillCorrBkg);
// or a config file
// pwg4spec->SetAnalysisType(AliAnalysisTaskJetSpectrum2::kAnaMC);
// if(iAODanalysis)pwg4spec->SetAODInput(kTRUE);
// pwg4spec->SetDebugLevel(11);
if(iFillCorrBkg)pwg4spec->SetBranchGen("");
else pwg4spec->SetBranchGen(bGen);
pwg4spec->SetBranchRec(bRec);
if(bBkgName.Length()>0)pwg4spec->SetBranchBkg(bBkgName.Data());
pwg4spec->SetFilterMask(filterMask);
pwg4spec->SetUseGlobalSelection(kTRUE);
pwg4spec->SetMinJetPt(5.);
pwg4spec->SetBkgSubtraction(kBackground);
if(type == "AOD"){
// Assume all jet are produced already
pwg4spec->SetAODJetInput(kTRUE);
pwg4spec->SetAODTrackInput(kTRUE);
pwg4spec->SetAODMCInput(kTRUE);
}
else{
if(mgr->GetMCtruthEventHandler()){
pwg4spec-> SetAnalysisType(AliAnalysisTaskJetSpectrum2::kAnaMCESD);
}
}
if(typeRec.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAODMCChargedAcceptance);
}
else if (typeRec.Contains("AODMC2")){
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAODMCCharged);
}
else if (typeRec.Contains("AODMC")){
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAODMCAll);
}
else { // catch akk use AOD
pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetSpectrum2::kTrackAOD);
}
if(typeGen.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAODMCChargedAcceptance);
}
else if (typeGen.Contains("AODMC2")){
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAODMCCharged);
}
else if (typeGen.Contains("AODMC")){
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAODMCAll);
}
else if (typeGen.Length()>0){ // catch all use AOD
pwg4spec->SetTrackTypeGen(AliAnalysisTaskJetSpectrum2::kTrackAOD);
}
if(iPhysicsSelection)pwg4spec->SelectCollisionCandidates();
if(iEventSelectionMask)pwg4spec->SetEventSelectionMask(iEventSelectionMask);
mgr->AddTask(pwg4spec);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
AliAnalysisDataContainer *coutput1_Spec = mgr->CreateContainer(Form("pwg4spec2_%s_%s_%010d",bRec,bGen,iEventSelectionMask),TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:PWG4_spec2_%s_%s_%010d",AliAnalysisManager::GetCommonFileName(),bRec,bGen,iEventSelectionMask));
mgr->ConnectInput (pwg4spec, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (pwg4spec, 0, mgr->GetCommonOutputContainer());
mgr->ConnectOutput (pwg4spec, 1, coutput1_Spec );
return pwg4spec;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperInputImageListParameter.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
InputImageListParameter::InputImageListParameter()
: m_InputImageParameterVector(),
m_ImageList(FloatVectorImageListType::New())
{
this->SetName("Input Image List");
this->SetKey("inList");
}
InputImageListParameter::~InputImageListParameter()
{
}
bool
InputImageListParameter::SetListFromFileName(const std::vector<std::string> & filenames)
{
// First clear previous file chosen
this->ClearValue();
bool isOk = true;
for(unsigned int i=0; i<filenames.size(); i++)
{
const std::string filename = filenames[i];
// TODO : when the logger will be available, redirect the exception
// in the logger (like what is done in MsgReporter)
// File existence checked by the reader
if (!filename.empty())
{
// Try to build a new ParameterInputImage
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetFromFileName(filename);
if(!tmpInputImageParameter->HasValue())
{
// If loading failed
this->ClearValue();
isOk = false;
break;
}
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
}
}
if( !isOk )
{
return false;
}
SetActive(true);
this->Modified();
return true;
}
void
InputImageListParameter::AddNullElement()
{
m_InputImageParameterVector.push_back(ITK_NULLPTR);
m_ImageList->PushBack(ITK_NULLPTR);
SetActive(false);
this->Modified();
}
bool
InputImageListParameter::AddFromFileName(const std::string & filename)
{
// TODO : when the logger will be available, redirect the exception
// in the logger (like what is done in MsgReporter)
// File existence checked by the reader
if (!filename.empty())
{
// Try to build a new ParameterInputImage
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetFromFileName(filename);
if(!tmpInputImageParameter->HasValue())
{
// If loading failed
this->ClearValue();
return false;
}
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
SetActive(true);
this->Modified();
return true;
}
return false;
}
bool
InputImageListParameter::SetNthFileName( const unsigned int id, const std::string & filename )
{
if( m_InputImageParameterVector.size()<id )
{
itkExceptionMacro(<< "No image "<<id<<". Only "<<m_InputImageParameterVector.size()<<" images available.");
}
// TODO : when the logger will be available, redirect the exception
// in the logger (like what is done in MsgReporter)
// File existence checked by the reader
if (!filename.empty())
{
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetFromFileName(filename);
if(!tmpInputImageParameter->HasValue())
{
this->ClearValue();
return false;
}
m_InputImageParameterVector[id] = tmpInputImageParameter;
m_ImageList->SetNthElement(id,tmpInputImageParameter->GetFloatVectorImage());
this->Modified();
SetActive(true);
return true;
}
return false;
}
std::vector<std::string>
InputImageListParameter::GetFileNameList() const
{
std::vector<std::string> filenames;
for(InputImageParameterVectorType::const_iterator it = m_InputImageParameterVector.begin();
it!=m_InputImageParameterVector.end();++it)
{
filenames.push_back( (*it)->GetFileName() );
}
return filenames;
}
std::string
InputImageListParameter::GetNthFileName( unsigned int i ) const
{
if(m_InputImageParameterVector.size()<i)
{
itkExceptionMacro(<< "No image "<<i<<". Only "<<m_InputImageParameterVector.size()<<" images available.");
}
return m_InputImageParameterVector[i]->GetFileName();
}
FloatVectorImageListType*
InputImageListParameter::GetImageList() const
{
return m_ImageList;
}
FloatVectorImageType*
InputImageListParameter::GetNthImage(unsigned int i) const
{
if(m_ImageList->Size()<i)
{
itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ImageList->Size()<<" images available.");
}
return m_ImageList->GetNthElement(i);
}
void
InputImageListParameter::SetImageList(FloatVectorImageListType* imList)
{
// Check input availability
for(unsigned int i = 0; i < imList->Size(); i++)
{
imList->GetNthElement(i)->UpdateOutputInformation();
}
// Clear previous values
this->ClearValue();
for(unsigned int i = 0; i<imList->Size(); i++)
{
// Try to build a new ParameterInputImage
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetImage(imList->GetNthElement(i));
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
}
SetActive(true);
this->Modified();
}
void InputImageListParameter::SetNthImage(unsigned int i, ImageBaseType * img)
{
if(m_ImageList->Size()<i)
{
itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ImageList->Size()<<" images available.");
}
// Check input availability
img->UpdateOutputInformation();
// Try to build a new ParameterInputImage
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetImage(img);
m_InputImageParameterVector[i] = tmpInputImageParameter;
m_ImageList->SetNthElement(i,tmpInputImageParameter->GetFloatVectorImage());
}
void
InputImageListParameter::AddImage(ImageBaseType* image)
{
// Check input availability
image->UpdateOutputInformation();
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetImage(image);
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
this->Modified();
}
bool
InputImageListParameter::HasValue() const
{
if(m_ImageList->Size() == 0)
{
return false;
}
bool res(true);
unsigned int i(0);
while(i < m_ImageList->Size() && res == true)
{
res = m_ImageList->GetNthElement(i).IsNotNull();
i++;
}
return res;
}
void
InputImageListParameter::Erase( unsigned int id )
{
if(m_ImageList->Size()<id)
{
itkExceptionMacro(<< "No image "<<id<<". Only "<<m_ImageList->Size()<<" images available.");
}
m_ImageList->Erase( id );
m_InputImageParameterVector.erase(m_InputImageParameterVector.begin()+id);
this->Modified();
}
unsigned int
InputImageListParameter::Size() const
{
return m_InputImageParameterVector.size();
}
void
InputImageListParameter::ClearValue()
{
m_ImageList->Clear();
m_InputImageParameterVector.clear();
SetActive(false);
this->Modified();
}
}
}
<commit_msg>RFC-91: Remove dead code<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperInputImageListParameter.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
InputImageListParameter::InputImageListParameter()
: m_InputImageParameterVector(),
m_ImageList(FloatVectorImageListType::New())
{
this->SetName("Input Image List");
this->SetKey("inList");
}
InputImageListParameter::~InputImageListParameter()
{
}
bool
InputImageListParameter::SetListFromFileName(const std::vector<std::string> & filenames)
{
// First clear previous file chosen
this->ClearValue();
for(unsigned int i=0; i<filenames.size(); i++)
{
const std::string filename = filenames[i];
// File existence checked by the reader
if (!filename.empty())
{
// Try to build a new ParameterInputImage
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetFromFileName(filename);
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
}
}
this->Modified();
SetActive(true);
return true;
}
void
InputImageListParameter::AddNullElement()
{
m_InputImageParameterVector.push_back(ITK_NULLPTR);
m_ImageList->PushBack(ITK_NULLPTR);
SetActive(false);
this->Modified();
}
bool
InputImageListParameter::AddFromFileName(const std::string & filename)
{
// File existence checked by the reader
if (!filename.empty())
{
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetFromFileName(filename);
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
this->Modified();
SetActive(true);
return true;
}
return false;
}
bool
InputImageListParameter::SetNthFileName( const unsigned int id, const std::string & filename )
{
if( m_InputImageParameterVector.size()<id )
{
itkExceptionMacro(<< "No image "<<id<<". Only "<<m_InputImageParameterVector.size()<<" images available.");
}
// File existence checked by the reader
if (!filename.empty())
{
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetFromFileName(filename);
m_InputImageParameterVector[id] = tmpInputImageParameter;
m_ImageList->SetNthElement(id,tmpInputImageParameter->GetFloatVectorImage());
this->Modified();
SetActive(true);
return true;
}
return false;
}
std::vector<std::string>
InputImageListParameter::GetFileNameList() const
{
std::vector<std::string> filenames;
for(InputImageParameterVectorType::const_iterator it = m_InputImageParameterVector.begin();
it!=m_InputImageParameterVector.end();++it)
{
filenames.push_back( (*it)->GetFileName() );
}
return filenames;
}
std::string
InputImageListParameter::GetNthFileName( unsigned int i ) const
{
if(m_InputImageParameterVector.size()<i)
{
itkExceptionMacro(<< "No image "<<i<<". Only "<<m_InputImageParameterVector.size()<<" images available.");
}
return m_InputImageParameterVector[i]->GetFileName();
}
FloatVectorImageListType*
InputImageListParameter::GetImageList() const
{
return m_ImageList;
}
FloatVectorImageType*
InputImageListParameter::GetNthImage(unsigned int i) const
{
if(m_ImageList->Size()<i)
{
itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ImageList->Size()<<" images available.");
}
return m_ImageList->GetNthElement(i);
}
void
InputImageListParameter::SetImageList(FloatVectorImageListType* imList)
{
// Check input availability
for(unsigned int i = 0; i < imList->Size(); i++)
{
imList->GetNthElement(i)->UpdateOutputInformation();
}
// Clear previous values
this->ClearValue();
for(unsigned int i = 0; i<imList->Size(); i++)
{
// Try to build a new ParameterInputImage
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetImage(imList->GetNthElement(i));
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
}
SetActive(true);
this->Modified();
}
void InputImageListParameter::SetNthImage(unsigned int i, ImageBaseType * img)
{
if(m_ImageList->Size()<i)
{
itkExceptionMacro(<< "No image "<<i<<". Only "<<m_ImageList->Size()<<" images available.");
}
// Check input availability
img->UpdateOutputInformation();
// Try to build a new ParameterInputImage
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetImage(img);
m_InputImageParameterVector[i] = tmpInputImageParameter;
m_ImageList->SetNthElement(i,tmpInputImageParameter->GetFloatVectorImage());
}
void
InputImageListParameter::AddImage(ImageBaseType* image)
{
// Check input availability
image->UpdateOutputInformation();
InputImageParameter::Pointer tmpInputImageParameter = InputImageParameter::New();
tmpInputImageParameter->SetImage(image);
m_InputImageParameterVector.push_back(tmpInputImageParameter);
m_ImageList->PushBack(tmpInputImageParameter->GetFloatVectorImage());
this->Modified();
}
bool
InputImageListParameter::HasValue() const
{
if(m_ImageList->Size() == 0)
{
return false;
}
bool res(true);
unsigned int i(0);
while(i < m_ImageList->Size() && res == true)
{
res = m_ImageList->GetNthElement(i).IsNotNull();
i++;
}
return res;
}
void
InputImageListParameter::Erase( unsigned int id )
{
if(m_ImageList->Size()<id)
{
itkExceptionMacro(<< "No image "<<id<<". Only "<<m_ImageList->Size()<<" images available.");
}
m_ImageList->Erase( id );
m_InputImageParameterVector.erase(m_InputImageParameterVector.begin()+id);
this->Modified();
}
unsigned int
InputImageListParameter::Size() const
{
return m_InputImageParameterVector.size();
}
void
InputImageListParameter::ClearValue()
{
m_ImageList->Clear();
m_InputImageParameterVector.clear();
SetActive(false);
this->Modified();
}
}
}
<|endoftext|> |
<commit_before>//==============================================================================
#include <cloud.hpp>
#include <bullet.hpp>
#include <engine.hpp>
#include <entity_manager.hpp>
#include <game.hpp>
#include <hgesprite.h>
#include <sqlite3.h>
#include <Database.h>
#include <Query.h>
#include <hgeparticle.h>
#include <hgeresource.h>
//------------------------------------------------------------------------------
namespace
{
const char * WHITE [] = {
"white_sheep_32",
"white_sheep_64",
"white_sheep_128",
"white_sheep_256",
"white_sheep_512",
};
const char * BLACK [] = {
"black_sheep_32",
"black_sheep_64",
"black_sheep_128",
"black_sheep_256",
"black_sheep_512",
};
const float DAMAGE[] = {
10.0f,
8.0f,
4.0f,
2.0f,
1.0f
};
const float SPEED[] = {
20.0f,
30.0f,
20.0f,
10.0f,
5.0f
};
};
//==============================================================================
Cloud::Cloud( float scale )
:
Entity( scale ),
Damageable( 99.0f ),
m_size( 0 ),
m_friend( false ),
m_life( 4.0f )
{
}
//------------------------------------------------------------------------------
Cloud::~Cloud()
{
}
//------------------------------------------------------------------------------
void
Cloud::collide( Entity * entity, b2ContactPoint * point )
{
if ( getFriend() || entity->getType() != Bullet::TYPE )
{
return;
}
if ( entity->getBlack() != getBlack() || m_size == 0 )
{
takeDamage( DAMAGE[ m_size ] );
}
else if ( m_size > 0 )
{
addStrength( DAMAGE[ m_size ] );
}
entity->destroy();
}
//------------------------------------------------------------------------------
void
Cloud::persistToDatabase()
{
char * rows[] = { "x", "%f", "y", "%f", "angle", "%f", "scale", "%f",
"sprite_id", "%d" };
m_id = Engine::em()->persistToDatabase( this, rows, m_body->GetPosition().x,
m_body->GetPosition().y,
m_body->GetAngle(),
m_scale, m_sprite_id );
}
//------------------------------------------------------------------------------
int
Cloud::getSize() const
{
return m_size;
}
//------------------------------------------------------------------------------
void
Cloud::setSize( int size )
{
m_size = size;
}
//------------------------------------------------------------------------------
bool
Cloud::isHarmful() const
{
return m_life > 3.0f;
}
//------------------------------------------------------------------------------
bool
Cloud::getFriend() const
{
return m_friend;
}
//------------------------------------------------------------------------------
void
Cloud::setFriend( bool b_friend )
{
m_friend = b_friend;
}
//------------------------------------------------------------------------------
// static:
//------------------------------------------------------------------------------
void
Cloud::registerEntity()
{
Engine::em()->registerEntity( Cloud::TYPE, Cloud::factory, "clouds",
"id, x, y, angle, scale, sprite_id" );
}
//------------------------------------------------------------------------------
// protected:
//------------------------------------------------------------------------------
void
Cloud::doInit()
{
if ( m_black )
{
m_sprite = Engine::rm()->GetSprite( BLACK[m_size] );
}
else
{
m_sprite = Engine::rm()->GetSprite( WHITE[m_size] );
}
m_zoom = 0;
m_life = 4.0f;
b2BodyDef bodyDef;
bodyDef.userData = static_cast<void*> (this);
m_body = Engine::b2d()->CreateDynamicBody(&bodyDef);
b2CircleDef shapeDef;
shapeDef.radius = 0.5f * 0.95f * m_sprite->GetWidth() * m_scale;
shapeDef.density = 10.0f;
shapeDef.friction = 0.0f;
shapeDef.restitution = 1.0f;
if ( m_size == 0 )
{
shapeDef.density = 0.001f;
}
m_body->CreateShape(&shapeDef);
m_body->SetMassFromShapes();
m_body->m_linearDamping = 0.0f;
if ( m_size == 0 )
{
m_body->m_linearDamping = 0.99f;
m_body->m_angularDamping = 0.8f;
}
m_body->m_angularDamping = 0.0f;
float spin( 5.0f / static_cast<float>(m_size + 1.0f) );
m_body->SetAngularVelocity( Engine::hge()->Random_Float( -spin, spin ) );
float speed( SPEED[m_size] );
b2Vec2 velocity( Engine::hge()->Random_Float( -speed, speed ),
Engine::hge()->Random_Float( -speed, speed ) );
m_body->SetLinearVelocity( velocity );
}
//------------------------------------------------------------------------------
void
Cloud::doUpdate( float dt )
{
m_life += dt;
if ( m_size == 0 )
{
setBlack( static_cast<Game *>( Engine::instance()->getContext() )->getBlack() );
}
updateDamageable( dt );
if ( m_black )
{
m_sprite = Engine::rm()->GetSprite( BLACK[m_size] );
}
else
{
m_sprite = Engine::rm()->GetSprite( WHITE[m_size] );
}
if ( isDestroyed() )
{
if ( m_size > 0 )
{
for ( int i = 0; i < 3; ++i )
{
Entity* entity = Engine::em()->factory( Cloud::TYPE );
if ( getBlack() )
{
entity->setBlack( 0 );
}
else
{
entity->setBlack( 1 );
}
entity->setScale( 0.1f );
static_cast< Cloud * >( entity )->setSize( m_size - 1 );
entity->init();
entity->getBody()->SetXForm( m_body->GetPosition(),
m_body->GetAngle() );
}
}
destroy();
}
else if ( isHealthy() && m_size < 4 )
{
Entity* entity = Engine::em()->factory( Cloud::TYPE );
if ( getBlack() )
{
entity->setBlack( 0 );
}
else
{
entity->setBlack( 1 );
}
entity->setScale( 0.1f );
static_cast< Cloud * >( entity )->setSize( m_size + 1 );
entity->init();
entity->getBody()->SetXForm( m_body->GetPosition(),
m_body->GetAngle() );
destroy();
}
if ( getFriend() )
{
b2Vec2 velocity( 0.0f, 0.0f );
m_body->SetAngularVelocity( 0.0f );
m_body->SetLinearVelocity( velocity );
}
}
//------------------------------------------------------------------------------
void
Cloud::doRender( float scale )
{
b2Vec2 position( m_body->GetPosition() );
float angle( m_body->GetAngle() );
if ( m_life < 3.0f )
{
if ( static_cast<int>( m_life * 10 ) % 2 == 0 )
{
m_sprite->RenderEx( position.x, position.y, angle, m_scale );
}
}
else
{
m_sprite->SetColor( 0xFFFFFFFF );
m_sprite->RenderEx( position.x, position.y, angle, m_scale );
}
}
//------------------------------------------------------------------------------
void
Cloud::initFromQuery( Query & query )
{
b2Vec2 position( 0.0f, 0.0f );
float angle( 0.0f );
m_id = static_cast< sqlite_int64 >( query.getnum() );
position.x = static_cast< float >( query.getnum() );
position.y = static_cast< float >( query.getnum() );
angle = static_cast< float >( query.getnum() );
m_scale = static_cast< float >( query.getnum() );
setSpriteID( static_cast< sqlite_int64 >( query.getnum() ) );
init();
m_body->SetXForm( position, angle );
}
//==============================================================================
<commit_msg>Improved damage and strength addition.<commit_after>//==============================================================================
#include <cloud.hpp>
#include <bullet.hpp>
#include <engine.hpp>
#include <entity_manager.hpp>
#include <game.hpp>
#include <hgesprite.h>
#include <sqlite3.h>
#include <Database.h>
#include <Query.h>
#include <hgeparticle.h>
#include <hgeresource.h>
//------------------------------------------------------------------------------
namespace
{
const char * WHITE [] = {
"white_sheep_32",
"white_sheep_64",
"white_sheep_128",
"white_sheep_256",
"white_sheep_512",
};
const char * BLACK [] = {
"black_sheep_32",
"black_sheep_64",
"black_sheep_128",
"black_sheep_256",
"black_sheep_512",
};
const float DAMAGE[] = {
1.0f,
20.0f,
10.0f,
5.0f,
2.0f
};
const float SPEED[] = {
20.0f,
30.0f,
20.0f,
10.0f,
5.0f
};
};
//==============================================================================
Cloud::Cloud( float scale )
:
Entity( scale ),
Damageable( 99.0f ),
m_size( 0 ),
m_friend( false ),
m_life( 4.0f )
{
}
//------------------------------------------------------------------------------
Cloud::~Cloud()
{
}
//------------------------------------------------------------------------------
void
Cloud::collide( Entity * entity, b2ContactPoint * point )
{
if ( getFriend() || entity->getType() != Bullet::TYPE )
{
return;
}
if ( entity->getBlack() != getBlack() || m_size == 0 )
{
takeDamage( DAMAGE[ m_size ] );
}
else if ( m_size > 0 && m_size < 4 )
{
addStrength( DAMAGE[ m_size + 1 ] );
}
entity->destroy();
}
//------------------------------------------------------------------------------
void
Cloud::persistToDatabase()
{
char * rows[] = { "x", "%f", "y", "%f", "angle", "%f", "scale", "%f",
"sprite_id", "%d" };
m_id = Engine::em()->persistToDatabase( this, rows, m_body->GetPosition().x,
m_body->GetPosition().y,
m_body->GetAngle(),
m_scale, m_sprite_id );
}
//------------------------------------------------------------------------------
int
Cloud::getSize() const
{
return m_size;
}
//------------------------------------------------------------------------------
void
Cloud::setSize( int size )
{
m_size = size;
}
//------------------------------------------------------------------------------
bool
Cloud::isHarmful() const
{
return m_life > 3.0f;
}
//------------------------------------------------------------------------------
bool
Cloud::getFriend() const
{
return m_friend;
}
//------------------------------------------------------------------------------
void
Cloud::setFriend( bool b_friend )
{
m_friend = b_friend;
}
//------------------------------------------------------------------------------
// static:
//------------------------------------------------------------------------------
void
Cloud::registerEntity()
{
Engine::em()->registerEntity( Cloud::TYPE, Cloud::factory, "clouds",
"id, x, y, angle, scale, sprite_id" );
}
//------------------------------------------------------------------------------
// protected:
//------------------------------------------------------------------------------
void
Cloud::doInit()
{
if ( m_black )
{
m_sprite = Engine::rm()->GetSprite( BLACK[m_size] );
}
else
{
m_sprite = Engine::rm()->GetSprite( WHITE[m_size] );
}
m_zoom = 0;
m_life = 4.0f;
b2BodyDef bodyDef;
bodyDef.userData = static_cast<void*> (this);
m_body = Engine::b2d()->CreateDynamicBody(&bodyDef);
b2CircleDef shapeDef;
shapeDef.radius = 0.5f * 0.95f * m_sprite->GetWidth() * m_scale;
shapeDef.density = 10.0f;
shapeDef.friction = 0.0f;
shapeDef.restitution = 1.0f;
if ( m_size == 0 )
{
shapeDef.density = 0.001f;
}
m_body->CreateShape(&shapeDef);
m_body->SetMassFromShapes();
m_body->m_linearDamping = 0.0f;
if ( m_size == 0 )
{
m_body->m_linearDamping = 0.99f;
m_body->m_angularDamping = 0.8f;
}
m_body->m_angularDamping = 0.0f;
float spin( 5.0f / static_cast<float>(m_size + 1.0f) );
m_body->SetAngularVelocity( Engine::hge()->Random_Float( -spin, spin ) );
float speed( SPEED[m_size] );
b2Vec2 velocity( Engine::hge()->Random_Float( -speed, speed ),
Engine::hge()->Random_Float( -speed, speed ) );
m_body->SetLinearVelocity( velocity );
}
//------------------------------------------------------------------------------
void
Cloud::doUpdate( float dt )
{
m_life += dt;
if ( m_size == 0 )
{
setBlack( static_cast<Game *>( Engine::instance()->getContext() )->getBlack() );
}
updateDamageable( dt );
if ( m_black )
{
m_sprite = Engine::rm()->GetSprite( BLACK[m_size] );
}
else
{
m_sprite = Engine::rm()->GetSprite( WHITE[m_size] );
}
if ( isDestroyed() )
{
if ( m_size > 0 )
{
for ( int i = 0; i < 3; ++i )
{
Entity* entity = Engine::em()->factory( Cloud::TYPE );
if ( getBlack() )
{
entity->setBlack( 0 );
}
else
{
entity->setBlack( 1 );
}
entity->setScale( 0.1f );
static_cast< Cloud * >( entity )->setSize( m_size - 1 );
entity->init();
entity->getBody()->SetXForm( m_body->GetPosition(),
m_body->GetAngle() );
}
}
destroy();
}
else if ( isHealthy() && m_size < 4 )
{
Entity* entity = Engine::em()->factory( Cloud::TYPE );
if ( getBlack() )
{
entity->setBlack( 0 );
}
else
{
entity->setBlack( 1 );
}
entity->setScale( 0.1f );
static_cast< Cloud * >( entity )->setSize( m_size + 1 );
entity->init();
entity->getBody()->SetXForm( m_body->GetPosition(),
m_body->GetAngle() );
destroy();
}
if ( getFriend() )
{
b2Vec2 velocity( 0.0f, 0.0f );
m_body->SetAngularVelocity( 0.0f );
m_body->SetLinearVelocity( velocity );
}
}
//------------------------------------------------------------------------------
void
Cloud::doRender( float scale )
{
b2Vec2 position( m_body->GetPosition() );
float angle( m_body->GetAngle() );
if ( m_life < 3.0f )
{
if ( static_cast<int>( m_life * 10 ) % 2 == 0 )
{
m_sprite->RenderEx( position.x, position.y, angle, m_scale );
}
}
else
{
m_sprite->SetColor( 0xFFFFFFFF );
m_sprite->RenderEx( position.x, position.y, angle, m_scale );
}
}
//------------------------------------------------------------------------------
void
Cloud::initFromQuery( Query & query )
{
b2Vec2 position( 0.0f, 0.0f );
float angle( 0.0f );
m_id = static_cast< sqlite_int64 >( query.getnum() );
position.x = static_cast< float >( query.getnum() );
position.y = static_cast< float >( query.getnum() );
angle = static_cast< float >( query.getnum() );
m_scale = static_cast< float >( query.getnum() );
setSpriteID( static_cast< sqlite_int64 >( query.getnum() ) );
init();
m_body->SetXForm( position, angle );
}
//==============================================================================
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DropDownFieldDialog.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:56:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FLDMGR_HXX
#include <fldmgr.hxx>
#endif
#ifndef _MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SW_DROPDOWNFIELDDIALOG_HXX
#include <DropDownFieldDialog.hxx>
#endif
#ifndef _FLDDROPDOWN_HXX
#include <flddropdown.hxx>
#endif
#ifndef _FLDUI_HRC
#include <fldui.hrc>
#endif
#ifndef _SW_DROPDOWNFIELDDIALOG_HRC
#include <DropDownFieldDialog.hrc>
#endif
using com::sun::star::uno::Sequence;
/*--------------------------------------------------------------------
Beschreibung: Feldeinfuegen bearbeiten
--------------------------------------------------------------------*/
sw::DropDownFieldDialog::DropDownFieldDialog( Window *pParent, SwWrtShell &rS,
SwField* pField, BOOL bNextButton ) :
SvxStandardDialog(pParent, SW_RES(DLG_FLD_DROPDOWN)),
aItemsFL( this, ResId( FL_ITEMS )),
aListItemsLB( this, ResId( LB_LISTITEMS )),
aOKPB( this, ResId( PB_OK )),
aCancelPB( this, ResId( PB_CANCEL )),
aNextPB( this, ResId( PB_NEXT )),
aHelpPB( this, ResId( PB_HELP )),
aEditPB( this, ResId( PB_EDIT )),
pDropField(0),
rSh( rS )
{
Link aButtonLk = LINK(this, DropDownFieldDialog, ButtonHdl);
aEditPB.SetClickHdl(aButtonLk);
if( bNextButton )
{
aNextPB.Show();
aNextPB.SetClickHdl(aButtonLk);
}
else
{
long nDiff = aCancelPB.GetPosPixel().Y() - aOKPB.GetPosPixel().Y();
Point aPos = aHelpPB.GetPosPixel();
aPos.Y() -= nDiff;
aHelpPB.SetPosPixel(aPos);
}
if( RES_DROPDOWN == pField->GetTyp()->Which() )
{
//
pDropField = (SwDropDownField*)pField;
String sTitle = GetText();
sTitle += pDropField->GetPar2();
SetText(sTitle);
Sequence<rtl::OUString> aItems = pDropField->GetItemSequence();
const rtl::OUString* pArray = aItems.getConstArray();
for(sal_Int32 i = 0; i < aItems.getLength(); i++)
aListItemsLB.InsertEntry(pArray[i]);
aListItemsLB.SelectEntry(pDropField->GetSelectedItem());
}
BOOL bEnable = !rSh.IsCrsrReadonly();
aOKPB.Enable( bEnable );
aListItemsLB.GrabFocus();
FreeResource();
}
sw::DropDownFieldDialog::~DropDownFieldDialog()
{
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
void sw::DropDownFieldDialog::Apply()
{
if(pDropField)
{
String sSelect = aListItemsLB.GetSelectEntry();
if(pDropField->GetPar1() != sSelect)
{
rSh.StartAllAction();
SwDropDownField * pCopy = (SwDropDownField *) pDropField->Copy();
pCopy->SetPar1(sSelect);
rSh.SwEditShell::UpdateFlds(*pCopy);
delete pCopy;
rSh.SetUndoNoResetModified();
rSh.EndAllAction();
}
}
}
/* -----------------17.06.2003 10:50-----------------
--------------------------------------------------*/
IMPL_LINK(sw::DropDownFieldDialog, ButtonHdl, PushButton*, pButton)
{
EndDialog(&aNextPB == pButton ? RET_OK : RET_YES );
return 0;
}
<commit_msg>INTEGRATION: CWS residcleanup (1.6.240); FILE MERGED 2007/03/04 17:03:02 pl 1.6.240.1: #i73635# ResId cleanup<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DropDownFieldDialog.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2007-04-26 09:09:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FLDMGR_HXX
#include <fldmgr.hxx>
#endif
#ifndef _MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SW_DROPDOWNFIELDDIALOG_HXX
#include <DropDownFieldDialog.hxx>
#endif
#ifndef _FLDDROPDOWN_HXX
#include <flddropdown.hxx>
#endif
#ifndef _FLDUI_HRC
#include <fldui.hrc>
#endif
#ifndef _SW_DROPDOWNFIELDDIALOG_HRC
#include <DropDownFieldDialog.hrc>
#endif
using com::sun::star::uno::Sequence;
/*--------------------------------------------------------------------
Beschreibung: Feldeinfuegen bearbeiten
--------------------------------------------------------------------*/
sw::DropDownFieldDialog::DropDownFieldDialog( Window *pParent, SwWrtShell &rS,
SwField* pField, BOOL bNextButton ) :
SvxStandardDialog(pParent, SW_RES(DLG_FLD_DROPDOWN)),
aItemsFL( this, SW_RES( FL_ITEMS )),
aListItemsLB( this, SW_RES( LB_LISTITEMS )),
aOKPB( this, SW_RES( PB_OK )),
aCancelPB( this, SW_RES( PB_CANCEL )),
aNextPB( this, SW_RES( PB_NEXT )),
aHelpPB( this, SW_RES( PB_HELP )),
aEditPB( this, SW_RES( PB_EDIT )),
pDropField(0),
rSh( rS )
{
Link aButtonLk = LINK(this, DropDownFieldDialog, ButtonHdl);
aEditPB.SetClickHdl(aButtonLk);
if( bNextButton )
{
aNextPB.Show();
aNextPB.SetClickHdl(aButtonLk);
}
else
{
long nDiff = aCancelPB.GetPosPixel().Y() - aOKPB.GetPosPixel().Y();
Point aPos = aHelpPB.GetPosPixel();
aPos.Y() -= nDiff;
aHelpPB.SetPosPixel(aPos);
}
if( RES_DROPDOWN == pField->GetTyp()->Which() )
{
//
pDropField = (SwDropDownField*)pField;
String sTitle = GetText();
sTitle += pDropField->GetPar2();
SetText(sTitle);
Sequence<rtl::OUString> aItems = pDropField->GetItemSequence();
const rtl::OUString* pArray = aItems.getConstArray();
for(sal_Int32 i = 0; i < aItems.getLength(); i++)
aListItemsLB.InsertEntry(pArray[i]);
aListItemsLB.SelectEntry(pDropField->GetSelectedItem());
}
BOOL bEnable = !rSh.IsCrsrReadonly();
aOKPB.Enable( bEnable );
aListItemsLB.GrabFocus();
FreeResource();
}
sw::DropDownFieldDialog::~DropDownFieldDialog()
{
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
void sw::DropDownFieldDialog::Apply()
{
if(pDropField)
{
String sSelect = aListItemsLB.GetSelectEntry();
if(pDropField->GetPar1() != sSelect)
{
rSh.StartAllAction();
SwDropDownField * pCopy = (SwDropDownField *) pDropField->Copy();
pCopy->SetPar1(sSelect);
rSh.SwEditShell::UpdateFlds(*pCopy);
delete pCopy;
rSh.SetUndoNoResetModified();
rSh.EndAllAction();
}
}
}
/* -----------------17.06.2003 10:50-----------------
--------------------------------------------------*/
IMPL_LINK(sw::DropDownFieldDialog, ButtonHdl, PushButton*, pButton)
{
EndDialog(&aNextPB == pButton ? RET_OK : RET_YES );
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <iterator>
#include <tuple>
#include <set>
#include <vector>
#include <utility>
#include <iomanip>
using ull = unsigned long long;
class LogEntry {
public:
LogEntry ()
: endtime(0), starttime(0), bitrate(0), duration(0), streamed(0), prev_streamed(0) {}
ull endtime, starttime;
unsigned int bitrate, prev_bitrate;
double streamed, prev_streamed, duration;
};
using LogEntries = std::vector<LogEntry>;
LogEntries reorder(const LogEntries&);
LogEntries extract_ranges(const LogEntries&);
void repl(const LogEntries&, int);
bool compare(const LogEntry&, const LogEntry&);
std::istream &operator >> (std::istream&, LogEntry&);
#ifdef DEBUG
std::ostream &operator << (std::ostream&, const LogEntry&);
template <typename F, typename S>
std::ostream &operator << (std::ostream&, const std::pair<F, S>&);
#endif
int main() {
LogEntries logEntries;
int logsize;
std::cin >> logsize;
std::copy_n(std::istream_iterator<LogEntry>(std::cin), logsize,
std::back_inserter(logEntries));
#ifdef DEBUG
std::cout << "\n";
for (auto& ent : logEntries) {
std::cout << ent << '\n';
}
std::cout << "\n\n";
#endif
logEntries = reorder(logEntries);
#ifdef DEBUG
std::cout << "\n";
for (auto& ent : logEntries) {
std::cout << ent << '\n';
}
std::cout << "\n\n";
#endif
std::cin >> logsize;
repl(logEntries, logsize);
return 0;
}
/**
* @brief Reads time ranges and sells lambourghinis'
* @details The repl stands for READ-EVALUATE-PRINT-LOOP.
* This method in particular will read any time range given, determine which log entries
* fall under this time range. It will then take the streams available under this
* time range and print what percentage of those streams were fully contained
* within the range given
*
* @param entries The collection of logs. This must have gone through the reorder
* function before it can be used here
* @param count The number of queries to expect
*/
void repl(const LogEntries& entries, int count) {
ull start, end;
LogEntries::const_iterator hi, lo;
LogEntry query;
std::cout.precision(3);
std::cout.setf(std::ios_base::fixed);
for (std::cin >> query.starttime >> query.endtime; count--;
std::cin >> query.starttime >> query.endtime) {
std::tie(lo, hi) = std::equal_range(entries.begin(), entries.end(),
query, compare);
hi--;
if (query.starttime < lo->starttime) {
query.starttime = lo->starttime;
}
if (query.endtime > hi->endtime) {
query.endtime = hi->endtime;
}
query.streamed = (hi->prev_streamed - lo->prev_streamed - lo->streamed) +
((lo->endtime - query.starttime) / lo->duration * lo->streamed) +
((query.endtime - hi->starttime) / hi->duration * hi->streamed);
std::cout << query.streamed << '\n';
}
}
/**
* @brief Aranges the logs into non overlapping ranges for easier usage
* @details The logs are taken one by one and we cut them up into smaller
* logs which do not overlap. By doing this, it is easier to work with ranges
* because you don't have to worry about anything they overlap
*
* @param entries The initial entries we got as input
*/
LogEntries reorder(const LogEntries &entries) {
LogEntries ranges = extract_ranges(entries);
LogEntries::iterator hi, lo;
for (auto &entry : entries) {
std::tie(lo, hi) = std::equal_range(ranges.begin(), ranges.end(),
entry, compare);
std::for_each(lo, hi, [&](LogEntry& val) {
val.bitrate += entry.bitrate;
});
}
ranges[0].streamed = ranges[0].duration / 1000 * ranges[0].bitrate;
for (int t = 1; t < ranges.size(); t++) {
ranges[t].streamed = ranges[t].duration / 1000 * ranges[t].bitrate;
ranges[t].prev_streamed = ranges[t - 1].streamed + ranges[t - 1].prev_streamed;
}
return ranges;
}
/**
* @brief Extract the non-overlapping ranges from the given log entries
* @details The method ...
*
* @param entries The vector of log entries from which to extract non
* overlapping ranges from
* @return A vector of Log Entries where all the entries are non overlapping
*/
LogEntries extract_ranges(const LogEntries& entries) {
// Use a set to avoid duplicates and make the entries sorted 2 birds one set
std::set<ull> times;
std::set<ull>::const_iterator iter;
for (int t = 0; t < entries.size(); t++) {
times.insert(entries[t].starttime);
times.insert(entries[t].endtime);
}
LogEntries merged;
LogEntry range;
for (iter = times.begin(); iter != times.end();) {
range.starttime = *iter++;
if (iter != times.end()) {
range.endtime = *iter;
range.duration = range.endtime - range.starttime;
merged.push_back(range);
}
}
return merged;
}
inline bool compare(const LogEntry& lhs, const LogEntry& rhs) {
return lhs.endtime <= rhs.starttime;
}
std::istream &operator >> (std::istream& iss, LogEntry& entry) {
iss >> entry.endtime >> entry.duration >> entry.bitrate;
entry.starttime = entry.endtime - entry.duration;
return iss;
}
std::ostream &operator << (std::ostream& oss, const LogEntry& entry) {
oss << "start=" << entry.starttime << ", end=" << entry.endtime
<< ", bitrate(s)=" << entry.bitrate << ", streamed(kb)="
<< std::setprecision(3) << std::fixed << entry.streamed;
return oss;
}
template <typename F, typename S>
std::ostream &operator << (std::ostream& oss, const std::pair<F, S> &p) {
return oss << "(First=>" << p.first << ", second=>" << p.second << ")";
}
<commit_msg>Implementing a caching system<commit_after>#include <iostream>
#include <algorithm>
#include <iterator>
#include <tuple>
#include <set>
#include <vector>
#include <utility>
#include <iomanip>
// #include <bits/stdc++.h>
using ull = unsigned long long;
constexpr double CACHE_SIZE_FACTOR = 1.0 / 10 * 10 * 10; // size of the range between each cache
class LogEntry {
public:
LogEntry () : endtime(0), starttime(0), bitrate(0), streamed(0), prev_streamed(0), duration(0) {}
ull endtime, starttime;
unsigned int bitrate;
double streamed, prev_streamed, duration;
};
using LogEntries = std::vector<LogEntry>;
using LogCache = std::vector<std::pair<const std::size_t, const std::size_t>>;
LogEntries reorder(const LogEntries&, LogCache&);
void repl(const LogEntries&, int);
bool compare(const LogEntry&, const LogEntry&);
std::istream &operator >> (std::istream&, LogEntry&);
#ifdef DEBUG
std::ostream &operator << (std::ostream&, const LogEntry&);
template <typename F, typename S>
std::ostream &operator << (std::ostream&, const std::pair<F, S>&);
#endif
int main() {
// Remove synchronization between cstdio and iostream
std::ios_base::sync_with_stdio(false);
// Prevent flushing of output stream before each io operation
std::cin.tie(nullptr);
LogEntries logEntries;
int logsize;
std::cin >> logsize;
std::copy_n(std::istream_iterator<LogEntry>(std::cin), logsize,
std::back_inserter(logEntries));
#ifdef DEBUG
std::cout << "\n";
for (auto& ent : logEntries) {
std::cout << ent << '\n';
}
std::cout << "\n\n";
#endif
LogCache cache;
logEntries = reorder(logEntries, cache);
#ifdef DEBUG
std::cout << "\n";
for (auto& ent : logEntries) {
std::cout << ent << '\n';
}
std::cout << "\n\n";
#endif
std::cin >> logsize;
repl(logEntries, logsize);
return 0;
}
/**
* @brief Reads time ranges and sells lambourghinis'
* @details The repl stands for READ-EVALUATE-PRINT-LOOP.
* This method in particular will read any time range given, determine which log entries
* fall under this time range. It will then take the streams available under this
* time range and print what percentage of those streams were fully contained
* within the range given
*
* @param entries The collection of logs. This must have gone through the reorder
* function before it can be used here
* @param count The number of queries to expect
*/
void repl(const LogEntries& entries, int count) {
LogEntries::const_iterator hi, lo;
LogEntry query;
std::cout.precision(3);
std::cout.setf(std::ios_base::fixed);
for (std::cin >> query.starttime >> query.endtime; count--;
std::cin >> query.starttime >> query.endtime) {
std::tie(lo, hi) = std::equal_range(entries.begin(), entries.end(),
query, compare);
hi--;
if (query.starttime < lo->starttime) {
query.starttime = lo->starttime;
}
if (query.endtime > hi->endtime) {
query.endtime = hi->endtime;
}
query.streamed = (hi->prev_streamed - lo->prev_streamed - lo->streamed) +
((lo->endtime - query.starttime) / lo->duration * lo->streamed) +
((query.endtime - hi->starttime) / hi->duration * hi->streamed);
std::cout << query.streamed << '\n';
}
}
/**
* @brief Extract the non-overlapping ranges from the given log entries
* @details The method ...
*
* @param entries The vector of log entries from which to extract non
* overlapping ranges from
* @return A vector of Log Entries where all the entries are non overlapping
*/
LogEntries extract_ranges(const LogEntries& entries) {
// Use a set to avoid duplicates and make the entries sorted 2 birds one set
std::set<ull> times;
std::set<ull>::const_iterator iter;
for (std::size_t t = 0; t < entries.size(); t++) {
times.insert(entries[t].starttime);
times.insert(entries[t].endtime);
}
LogEntries merged;
LogEntry range;
for (iter = times.begin(); iter != times.end();) {
range.starttime = *iter++;
if (iter != times.end()) {
range.endtime = *iter;
range.duration = range.endtime - range.starttime;
merged.push_back(range);
}
}
return merged;
}
/**
* @brief Aranges the logs into non overlapping ranges for easier usage
* @details The logs are taken one by one and we cut them up into smaller
* logs which do not overlap. By doing this, it is easier to work with ranges
* because you don't have to worry about anything they overlap
*
* @param entries The initial entries we got as input
*/
LogEntries reorder(const LogEntries &entries, LogCache& cache) {
LogEntries ranges = extract_ranges(entries);
LogEntries::iterator hi, lo;
// compute the cache size (atleast size 1)
std::size_t num_buckets = static_cast<double>(ranges.size()) * CACHE_SIZE_FACTOR + 1;
cache.reserve(num_buckets);
// The max time interval maintained within each range in the cache
const ull max_interval = (ranges.back().endtime - ranges[0].starttime + num_buckets) / num_buckets;
for (auto &entry : entries) {
std::tie(lo, hi) = std::equal_range(ranges.begin(), ranges.end(),
entry, compare);
std::for_each(lo, hi, [&entry](LogEntry& val) {
val.bitrate += entry.bitrate;
});
}
LogEntries::iterator beg = ranges.begin(), curr;
beg->streamed = beg->duration / 1000 * beg->bitrate;
ull start_time = beg->starttime;
for (curr = beg + 1; curr != ranges.end(); curr++) {
curr->streamed = curr->duration / 1000 * curr->bitrate;
curr->prev_streamed = (curr - 1)->streamed + (curr - 1)->prev_streamed;
if (curr->starttime - start_time > max_interval) {
cache.emplace_back(std::distance(ranges.begin(), beg), std::distance(ranges.begin(), curr));
beg = curr;
start_time = curr->starttime;
}
}
cache.emplace_back(std::distance(ranges.begin(), beg), std::distance(ranges.begin(), curr));
return ranges;
}
inline bool compare(const LogEntry& lhs, const LogEntry& rhs) {
return lhs.endtime <= rhs.starttime;
}
std::istream &operator >> (std::istream& iss, LogEntry& entry) {
iss >> entry.endtime >> entry.duration >> entry.bitrate;
entry.starttime = entry.endtime - entry.duration;
return iss;
}
std::ostream &operator << (std::ostream& oss, const LogEntry& entry) {
oss << "start=" << entry.starttime << ", end=" << entry.endtime
<< ", bitrate(s)=" << entry.bitrate << ", streamed(kb)="
<< std::setprecision(3) << std::fixed << entry.streamed;
return oss;
}
template <typename F, typename S>
std::ostream &operator << (std::ostream& oss, const std::pair<F, S> &p) {
return oss << "(First=>" << p.first << ", second=>" << p.second << ")";
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Intel Corporation. All rights reserved.
// Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/application/browser/application_security_policy.h"
#include <map>
#include <string>
#include "base/numerics/safe_conversions.h"
#include "content/public/browser/render_process_host.h"
#include "xwalk/application/browser/application.h"
#include "xwalk/application/common/application_data.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/csp_handler.h"
#include "xwalk/application/common/manifest_handlers/warp_handler.h"
#include "xwalk/runtime/common/xwalk_common_messages.h"
namespace xwalk {
namespace keys = application_manifest_keys;
namespace widget_keys = application_widget_keys;
namespace application {
namespace {
const char kAsterisk[] = "*";
const char kDirectiveValueSelf[] = "'self'";
const char kDirectiveValueNone[] = "'none'";
const char kDirectiveNameDefault[] = "default-src";
const char kDirectiveNameScript[] = "script-src";
const char kDirectiveNameStyle[] = "style-src";
const char kDirectiveNameObject[] = "object-src";
// By default:
// default-src * ; script-src 'self' ; style-src 'self' ; object-src 'none'
CSPInfo* GetDefaultCSPInfo() {
static CSPInfo default_csp_info;
if (default_csp_info.GetDirectives().empty()) {
std::vector<std::string> directive_all;
std::vector<std::string> directive_self;
std::vector<std::string> directive_none;
directive_all.push_back(kAsterisk);
directive_self.push_back(kDirectiveValueSelf);
directive_none.push_back(kDirectiveValueNone);
default_csp_info.SetDirective(kDirectiveNameDefault, directive_all);
default_csp_info.SetDirective(kDirectiveNameScript, directive_self);
default_csp_info.SetDirective(kDirectiveNameStyle, directive_self);
default_csp_info.SetDirective(kDirectiveNameObject, directive_none);
}
return (new CSPInfo(default_csp_info));
}
} // namespace
ApplicationSecurityPolicy::WhitelistEntry::WhitelistEntry(
const GURL& url, bool subdomains)
: url(url),
subdomains(subdomains) {
}
scoped_ptr<ApplicationSecurityPolicy> ApplicationSecurityPolicy::
Create(scoped_refptr<ApplicationData> app_data) {
scoped_ptr<ApplicationSecurityPolicy> security_policy;
// CSP policy takes precedence over WARP.
if (app_data->HasCSPDefined())
security_policy.reset(new ApplicationSecurityPolicyCSP(app_data));
else if (app_data->manifest_type() == Manifest::TYPE_WIDGET)
security_policy.reset(new ApplicationSecurityPolicyWARP(app_data));
if (security_policy)
security_policy->InitEntries();
return security_policy;
}
ApplicationSecurityPolicy::ApplicationSecurityPolicy(
scoped_refptr<ApplicationData> app_data, SecurityMode mode)
: app_data_(app_data),
mode_(mode),
enabled_(false) {
}
ApplicationSecurityPolicy::~ApplicationSecurityPolicy() {
}
bool ApplicationSecurityPolicy::IsAccessAllowed(const GURL& url) const {
if (!enabled_)
return true;
// Accessing own resources in W3C Widget is always allowed.
if (app_data_->manifest_type() == Manifest::TYPE_WIDGET &&
url.SchemeIs(kApplicationScheme) && url.host() == app_data_->ID())
return true;
for (const WhitelistEntry& entry : whitelist_entries_) {
const GURL& policy = entry.url;
bool subdomains = entry.subdomains;
bool is_host_matched = subdomains ?
url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
if (url.scheme() == policy.scheme() && is_host_matched &&
base::StartsWith(url.path(), policy.path(),
base::CompareCase::INSENSITIVE_ASCII))
return true;
}
return false;
}
void ApplicationSecurityPolicy::EnforceForRenderer(
content::RenderProcessHost* rph) const {
DCHECK(rph);
if (!enabled_)
return;
DCHECK(!whitelist_entries_.empty());
const GURL& app_url = app_data_->URL();
for (const WhitelistEntry& entry : whitelist_entries_) {
rph->Send(new ViewMsg_SetAccessWhiteList(
app_url, entry.url, entry.subdomains));
}
rph->Send(new ViewMsg_EnableSecurityMode(app_url, mode_));
}
void ApplicationSecurityPolicy::AddWhitelistEntry(
const GURL& url, bool subdomains) {
WhitelistEntry entry = WhitelistEntry(url, subdomains);
auto it =
std::find(whitelist_entries_.begin(), whitelist_entries_.end(), entry);
if (it != whitelist_entries_.end())
return;
whitelist_entries_.push_back(entry);
}
ApplicationSecurityPolicyWARP::ApplicationSecurityPolicyWARP(
scoped_refptr<ApplicationData> app_data)
: ApplicationSecurityPolicy(app_data, ApplicationSecurityPolicy::WARP) {
}
ApplicationSecurityPolicyWARP::~ApplicationSecurityPolicyWARP() {
}
void ApplicationSecurityPolicyWARP::InitEntries() {
const WARPInfo* info = static_cast<WARPInfo*>(
app_data_->GetManifestData(widget_keys::kAccessKey));
if (!info) {
enabled_ = true;
return;
}
const base::ListValue* whitelist = info->GetWARP();
for (base::ListValue::const_iterator it = whitelist->begin();
it != whitelist->end(); ++it) {
base::DictionaryValue* value = nullptr;
(*it)->GetAsDictionary(&value);
std::string dest;
if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
dest.empty())
continue;
if (dest == "*") {
enabled_ = false;
break;
}
GURL dest_url(dest);
// The default subdomains attribute should be "false".
std::string subdomains = "false";
value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
AddWhitelistEntry(dest_url, (subdomains == "true"));
enabled_ = true;
}
}
ApplicationSecurityPolicyCSP::ApplicationSecurityPolicyCSP(
scoped_refptr<ApplicationData> app_data)
: ApplicationSecurityPolicy(app_data, ApplicationSecurityPolicy::CSP) {
}
ApplicationSecurityPolicyCSP::~ApplicationSecurityPolicyCSP() {
}
void ApplicationSecurityPolicyCSP::InitEntries() {
Manifest::Type manifest_type = app_data_->manifest_type();
const char* scp_key = GetCSPKey(manifest_type);
CSPInfo* csp_info = static_cast<CSPInfo*>(
app_data_->GetManifestData(scp_key));
if (manifest_type != Manifest::TYPE_WIDGET) {
if (csp_info && !csp_info->GetDirectives().empty()) {
enabled_ = true;
const std::map<std::string, std::vector<std::string> >& policies =
csp_info->GetDirectives();
for (const auto& directive : policies) {
for (const auto& it : directive.second) {
GURL url(it);
if (url.is_valid())
AddWhitelistEntry(url, false);
}
}
}
// scope
std::string scope;
GURL internalUrl = app_data_->URL();
if (app_data_->GetManifest()->GetString(keys::kScopeKey, &scope) &&
!scope.empty()) {
enabled_ = true;
url::Replacements<char> replacements;
replacements.SetPath(
scope.c_str(),
url::Component(0, base::checked_cast<int>(scope.length())));
internalUrl = internalUrl.ReplaceComponents(replacements);
}
if (internalUrl.is_valid())
// All links out of whitelist will be opened in system default web
// browser.
AddWhitelistEntry(internalUrl, false);
else
LOG(INFO) << "URL " << internalUrl.spec() << " is wrong.";
}
}
} // namespace application
} // namespace xwalk
<commit_msg>Remove GetDefaultCSPInfo().<commit_after>// Copyright (c) 2014 Intel Corporation. All rights reserved.
// Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/application/browser/application_security_policy.h"
#include <map>
#include <string>
#include "base/numerics/safe_conversions.h"
#include "content/public/browser/render_process_host.h"
#include "xwalk/application/browser/application.h"
#include "xwalk/application/common/application_data.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/csp_handler.h"
#include "xwalk/application/common/manifest_handlers/warp_handler.h"
#include "xwalk/runtime/common/xwalk_common_messages.h"
namespace xwalk {
namespace keys = application_manifest_keys;
namespace widget_keys = application_widget_keys;
namespace application {
ApplicationSecurityPolicy::WhitelistEntry::WhitelistEntry(
const GURL& url, bool subdomains)
: url(url),
subdomains(subdomains) {
}
scoped_ptr<ApplicationSecurityPolicy> ApplicationSecurityPolicy::
Create(scoped_refptr<ApplicationData> app_data) {
scoped_ptr<ApplicationSecurityPolicy> security_policy;
// CSP policy takes precedence over WARP.
if (app_data->HasCSPDefined())
security_policy.reset(new ApplicationSecurityPolicyCSP(app_data));
else if (app_data->manifest_type() == Manifest::TYPE_WIDGET)
security_policy.reset(new ApplicationSecurityPolicyWARP(app_data));
if (security_policy)
security_policy->InitEntries();
return security_policy;
}
ApplicationSecurityPolicy::ApplicationSecurityPolicy(
scoped_refptr<ApplicationData> app_data, SecurityMode mode)
: app_data_(app_data),
mode_(mode),
enabled_(false) {
}
ApplicationSecurityPolicy::~ApplicationSecurityPolicy() {
}
bool ApplicationSecurityPolicy::IsAccessAllowed(const GURL& url) const {
if (!enabled_)
return true;
// Accessing own resources in W3C Widget is always allowed.
if (app_data_->manifest_type() == Manifest::TYPE_WIDGET &&
url.SchemeIs(kApplicationScheme) && url.host() == app_data_->ID())
return true;
for (const WhitelistEntry& entry : whitelist_entries_) {
const GURL& policy = entry.url;
bool subdomains = entry.subdomains;
bool is_host_matched = subdomains ?
url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
if (url.scheme() == policy.scheme() && is_host_matched &&
base::StartsWith(url.path(), policy.path(),
base::CompareCase::INSENSITIVE_ASCII))
return true;
}
return false;
}
void ApplicationSecurityPolicy::EnforceForRenderer(
content::RenderProcessHost* rph) const {
DCHECK(rph);
if (!enabled_)
return;
DCHECK(!whitelist_entries_.empty());
const GURL& app_url = app_data_->URL();
for (const WhitelistEntry& entry : whitelist_entries_) {
rph->Send(new ViewMsg_SetAccessWhiteList(
app_url, entry.url, entry.subdomains));
}
rph->Send(new ViewMsg_EnableSecurityMode(app_url, mode_));
}
void ApplicationSecurityPolicy::AddWhitelistEntry(
const GURL& url, bool subdomains) {
WhitelistEntry entry = WhitelistEntry(url, subdomains);
auto it =
std::find(whitelist_entries_.begin(), whitelist_entries_.end(), entry);
if (it != whitelist_entries_.end())
return;
whitelist_entries_.push_back(entry);
}
ApplicationSecurityPolicyWARP::ApplicationSecurityPolicyWARP(
scoped_refptr<ApplicationData> app_data)
: ApplicationSecurityPolicy(app_data, ApplicationSecurityPolicy::WARP) {
}
ApplicationSecurityPolicyWARP::~ApplicationSecurityPolicyWARP() {
}
void ApplicationSecurityPolicyWARP::InitEntries() {
const WARPInfo* info = static_cast<WARPInfo*>(
app_data_->GetManifestData(widget_keys::kAccessKey));
if (!info) {
enabled_ = true;
return;
}
const base::ListValue* whitelist = info->GetWARP();
for (base::ListValue::const_iterator it = whitelist->begin();
it != whitelist->end(); ++it) {
base::DictionaryValue* value = nullptr;
(*it)->GetAsDictionary(&value);
std::string dest;
if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
dest.empty())
continue;
if (dest == "*") {
enabled_ = false;
break;
}
GURL dest_url(dest);
// The default subdomains attribute should be "false".
std::string subdomains = "false";
value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
AddWhitelistEntry(dest_url, (subdomains == "true"));
enabled_ = true;
}
}
ApplicationSecurityPolicyCSP::ApplicationSecurityPolicyCSP(
scoped_refptr<ApplicationData> app_data)
: ApplicationSecurityPolicy(app_data, ApplicationSecurityPolicy::CSP) {
}
ApplicationSecurityPolicyCSP::~ApplicationSecurityPolicyCSP() {
}
void ApplicationSecurityPolicyCSP::InitEntries() {
Manifest::Type manifest_type = app_data_->manifest_type();
const char* scp_key = GetCSPKey(manifest_type);
CSPInfo* csp_info = static_cast<CSPInfo*>(
app_data_->GetManifestData(scp_key));
if (manifest_type != Manifest::TYPE_WIDGET) {
if (csp_info && !csp_info->GetDirectives().empty()) {
enabled_ = true;
const std::map<std::string, std::vector<std::string> >& policies =
csp_info->GetDirectives();
for (const auto& directive : policies) {
for (const auto& it : directive.second) {
GURL url(it);
if (url.is_valid())
AddWhitelistEntry(url, false);
}
}
}
// scope
std::string scope;
GURL internalUrl = app_data_->URL();
if (app_data_->GetManifest()->GetString(keys::kScopeKey, &scope) &&
!scope.empty()) {
enabled_ = true;
url::Replacements<char> replacements;
replacements.SetPath(
scope.c_str(),
url::Component(0, base::checked_cast<int>(scope.length())));
internalUrl = internalUrl.ReplaceComponents(replacements);
}
if (internalUrl.is_valid())
// All links out of whitelist will be opened in system default web
// browser.
AddWhitelistEntry(internalUrl, false);
else
LOG(INFO) << "URL " << internalUrl.spec() << " is wrong.";
}
}
} // namespace application
} // namespace xwalk
<|endoftext|> |
<commit_before>/* Copyright 2017 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/contrib/tensorboard/db/schema.h"
#include "tensorflow/contrib/tensorboard/db/summary_db_writer.h"
#include "tensorflow/contrib/tensorboard/db/summary_file_writer.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/lib/db/sqlite.h"
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
REGISTER_KERNEL_BUILDER(Name("SummaryWriter").Device(DEVICE_CPU),
ResourceHandleOp<SummaryWriterInterface>);
class CreateSummaryFileWriterOp : public OpKernel {
public:
explicit CreateSummaryFileWriterOp(OpKernelConstruction* ctx)
: OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("logdir", &tmp));
const string logdir = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("max_queue", &tmp));
const int32 max_queue = tmp->scalar<int32>()();
OP_REQUIRES_OK(ctx, ctx->input("flush_millis", &tmp));
const int32 flush_millis = tmp->scalar<int32>()();
OP_REQUIRES_OK(ctx, ctx->input("filename_suffix", &tmp));
const string filename_suffix = tmp->scalar<string>()();
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx,
CreateSummaryFileWriter(max_queue, flush_millis, logdir,
filename_suffix, ctx->env(), &s));
OP_REQUIRES_OK(ctx, CreateResource(ctx, HandleFromInput(ctx, 0), s));
}
};
REGISTER_KERNEL_BUILDER(Name("CreateSummaryFileWriter").Device(DEVICE_CPU),
CreateSummaryFileWriterOp);
class CreateSummaryDbWriterOp : public OpKernel {
public:
explicit CreateSummaryDbWriterOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("db_uri", &tmp));
const string db_uri = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("experiment_name", &tmp));
const string experiment_name = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("run_name", &tmp));
const string run_name = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("user_name", &tmp));
const string user_name = tmp->scalar<string>()();
SummaryWriterInterface* s;
Sqlite* db;
OP_REQUIRES_OK(ctx, Sqlite::Open(db_uri,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
&db));
core::ScopedUnref unref(db);
OP_REQUIRES_OK(ctx, SetupTensorboardSqliteDb(db));
OP_REQUIRES_OK(
ctx, CreateSummaryDbWriter(db, experiment_name,
run_name, user_name, ctx->env(), &s));
OP_REQUIRES_OK(ctx, CreateResource(ctx, HandleFromInput(ctx, 0), s));
}
};
REGISTER_KERNEL_BUILDER(Name("CreateSummaryDbWriter").Device(DEVICE_CPU),
CreateSummaryDbWriterOp);
class FlushSummaryWriterOp : public OpKernel {
public:
explicit FlushSummaryWriterOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
OP_REQUIRES_OK(ctx, s->Flush());
}
};
REGISTER_KERNEL_BUILDER(Name("FlushSummaryWriter").Device(DEVICE_CPU),
FlushSummaryWriterOp);
class CloseSummaryWriterOp : public OpKernel {
public:
explicit CloseSummaryWriterOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
OP_REQUIRES_OK(ctx, DeleteResource<SummaryWriterInterface>(
ctx, HandleFromInput(ctx, 0)));
}
};
REGISTER_KERNEL_BUILDER(Name("CloseSummaryWriter").Device(DEVICE_CPU),
CloseSummaryWriterOp);
class WriteSummaryOp : public OpKernel {
public:
explicit WriteSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("summary_metadata", &tmp));
const string& serialized_metadata = tmp->scalar<string>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
OP_REQUIRES_OK(ctx, s->WriteTensor(step, *t, tag, serialized_metadata));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteSummary").Device(DEVICE_CPU),
WriteSummaryOp);
class ImportEventOp : public OpKernel {
public:
explicit ImportEventOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("event", &t));
std::unique_ptr<Event> event{new Event};
if (!ParseProtoUnlimited(event.get(), t->scalar<string>()())) {
ctx->CtxFailureWithWarning(
errors::DataLoss("Bad tf.Event binary proto tensor string"));
return;
}
OP_REQUIRES_OK(ctx, s->WriteEvent(std::move(event)));
}
};
REGISTER_KERNEL_BUILDER(Name("ImportEvent").Device(DEVICE_CPU), ImportEventOp);
class WriteScalarSummaryOp : public OpKernel {
public:
explicit WriteScalarSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("value", &t));
OP_REQUIRES_OK(ctx, s->WriteScalar(step, *t, tag));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteScalarSummary").Device(DEVICE_CPU),
WriteScalarSummaryOp);
class WriteHistogramSummaryOp : public OpKernel {
public:
explicit WriteHistogramSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("values", &t));
OP_REQUIRES_OK(ctx, s->WriteHistogram(step, *t, tag));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteHistogramSummary").Device(DEVICE_CPU),
WriteHistogramSummaryOp);
class WriteImageSummaryOp : public OpKernel {
public:
explicit WriteImageSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
int64 max_images_tmp;
OP_REQUIRES_OK(ctx, ctx->GetAttr("max_images", &max_images_tmp));
OP_REQUIRES(ctx, max_images_tmp < (1LL << 31),
errors::InvalidArgument("max_images must be < 2^31"));
max_images_ = static_cast<int32>(max_images_tmp);
}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
const Tensor* bad_color;
OP_REQUIRES_OK(ctx, ctx->input("bad_color", &bad_color));
OP_REQUIRES(
ctx, TensorShapeUtils::IsVector(bad_color->shape()),
errors::InvalidArgument("bad_color must be a vector, got shape ",
bad_color->shape().DebugString()));
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
OP_REQUIRES_OK(ctx, s->WriteImage(step, *t, tag, max_images_, *bad_color));
}
private:
int32 max_images_;
};
REGISTER_KERNEL_BUILDER(Name("WriteImageSummary").Device(DEVICE_CPU),
WriteImageSummaryOp);
class WriteAudioSummaryOp : public OpKernel {
public:
explicit WriteAudioSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("max_outputs", &max_outputs_));
OP_REQUIRES(ctx, max_outputs_ > 0,
errors::InvalidArgument("max_outputs must be > 0"));
}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("sample_rate", &tmp));
const float sample_rate = tmp->scalar<float>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
OP_REQUIRES_OK(ctx,
s->WriteAudio(step, *t, tag, max_outputs_, sample_rate));
}
private:
int max_outputs_;
bool has_sample_rate_attr_;
float sample_rate_attr_;
};
REGISTER_KERNEL_BUILDER(Name("WriteAudioSummary").Device(DEVICE_CPU),
WriteAudioSummaryOp);
class WriteGraphSummaryOp : public OpKernel {
public:
explicit WriteGraphSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("step", &t));
const int64 step = t->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
std::unique_ptr<GraphDef> graph{new GraphDef};
if (!ParseProtoUnlimited(graph.get(), t->scalar<string>()())) {
ctx->CtxFailureWithWarning(
errors::DataLoss("Bad tf.GraphDef binary proto tensor string"));
return;
}
OP_REQUIRES_OK(ctx, s->WriteGraph(step, std::move(graph)));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteGraphSummary").Device(DEVICE_CPU),
WriteGraphSummaryOp);
} // namespace tensorflow
<commit_msg>Use LookupOrCreateResource when creating summary writers. The resource may already exist because it's associated with the device.<commit_after>/* Copyright 2017 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/contrib/tensorboard/db/schema.h"
#include "tensorflow/contrib/tensorboard/db/summary_db_writer.h"
#include "tensorflow/contrib/tensorboard/db/summary_file_writer.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/lib/db/sqlite.h"
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
REGISTER_KERNEL_BUILDER(Name("SummaryWriter").Device(DEVICE_CPU),
ResourceHandleOp<SummaryWriterInterface>);
class CreateSummaryFileWriterOp : public OpKernel {
public:
explicit CreateSummaryFileWriterOp(OpKernelConstruction* ctx)
: OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("logdir", &tmp));
const string logdir = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("max_queue", &tmp));
const int32 max_queue = tmp->scalar<int32>()();
OP_REQUIRES_OK(ctx, ctx->input("flush_millis", &tmp));
const int32 flush_millis = tmp->scalar<int32>()();
OP_REQUIRES_OK(ctx, ctx->input("filename_suffix", &tmp));
const string filename_suffix = tmp->scalar<string>()();
SummaryWriterInterface* s = nullptr;
OP_REQUIRES_OK(ctx, LookupOrCreateResource<SummaryWriterInterface>(
ctx, HandleFromInput(ctx, 0), &s,
[max_queue, flush_millis, logdir, filename_suffix,
ctx](SummaryWriterInterface** s) {
return CreateSummaryFileWriter(
max_queue, flush_millis, logdir,
filename_suffix, ctx->env(), s);
}));
}
};
REGISTER_KERNEL_BUILDER(Name("CreateSummaryFileWriter").Device(DEVICE_CPU),
CreateSummaryFileWriterOp);
class CreateSummaryDbWriterOp : public OpKernel {
public:
explicit CreateSummaryDbWriterOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("db_uri", &tmp));
const string db_uri = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("experiment_name", &tmp));
const string experiment_name = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("run_name", &tmp));
const string run_name = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("user_name", &tmp));
const string user_name = tmp->scalar<string>()();
SummaryWriterInterface* s = nullptr;
OP_REQUIRES_OK(
ctx,
LookupOrCreateResource<SummaryWriterInterface>(
ctx, HandleFromInput(ctx, 0), &s,
[db_uri, experiment_name, run_name, user_name,
ctx](SummaryWriterInterface** s) {
Sqlite* db;
TF_RETURN_IF_ERROR(Sqlite::Open(
db_uri, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, &db));
core::ScopedUnref unref(db);
TF_RETURN_IF_ERROR(SetupTensorboardSqliteDb(db));
TF_RETURN_IF_ERROR(CreateSummaryDbWriter(
db, experiment_name, run_name, user_name, ctx->env(), s));
return Status::OK();
}));
}
};
REGISTER_KERNEL_BUILDER(Name("CreateSummaryDbWriter").Device(DEVICE_CPU),
CreateSummaryDbWriterOp);
class FlushSummaryWriterOp : public OpKernel {
public:
explicit FlushSummaryWriterOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
OP_REQUIRES_OK(ctx, s->Flush());
}
};
REGISTER_KERNEL_BUILDER(Name("FlushSummaryWriter").Device(DEVICE_CPU),
FlushSummaryWriterOp);
class CloseSummaryWriterOp : public OpKernel {
public:
explicit CloseSummaryWriterOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
OP_REQUIRES_OK(ctx, DeleteResource<SummaryWriterInterface>(
ctx, HandleFromInput(ctx, 0)));
}
};
REGISTER_KERNEL_BUILDER(Name("CloseSummaryWriter").Device(DEVICE_CPU),
CloseSummaryWriterOp);
class WriteSummaryOp : public OpKernel {
public:
explicit WriteSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("summary_metadata", &tmp));
const string& serialized_metadata = tmp->scalar<string>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
OP_REQUIRES_OK(ctx, s->WriteTensor(step, *t, tag, serialized_metadata));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteSummary").Device(DEVICE_CPU),
WriteSummaryOp);
class ImportEventOp : public OpKernel {
public:
explicit ImportEventOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("event", &t));
std::unique_ptr<Event> event{new Event};
if (!ParseProtoUnlimited(event.get(), t->scalar<string>()())) {
ctx->CtxFailureWithWarning(
errors::DataLoss("Bad tf.Event binary proto tensor string"));
return;
}
OP_REQUIRES_OK(ctx, s->WriteEvent(std::move(event)));
}
};
REGISTER_KERNEL_BUILDER(Name("ImportEvent").Device(DEVICE_CPU), ImportEventOp);
class WriteScalarSummaryOp : public OpKernel {
public:
explicit WriteScalarSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("value", &t));
OP_REQUIRES_OK(ctx, s->WriteScalar(step, *t, tag));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteScalarSummary").Device(DEVICE_CPU),
WriteScalarSummaryOp);
class WriteHistogramSummaryOp : public OpKernel {
public:
explicit WriteHistogramSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("values", &t));
OP_REQUIRES_OK(ctx, s->WriteHistogram(step, *t, tag));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteHistogramSummary").Device(DEVICE_CPU),
WriteHistogramSummaryOp);
class WriteImageSummaryOp : public OpKernel {
public:
explicit WriteImageSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
int64 max_images_tmp;
OP_REQUIRES_OK(ctx, ctx->GetAttr("max_images", &max_images_tmp));
OP_REQUIRES(ctx, max_images_tmp < (1LL << 31),
errors::InvalidArgument("max_images must be < 2^31"));
max_images_ = static_cast<int32>(max_images_tmp);
}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
const Tensor* bad_color;
OP_REQUIRES_OK(ctx, ctx->input("bad_color", &bad_color));
OP_REQUIRES(
ctx, TensorShapeUtils::IsVector(bad_color->shape()),
errors::InvalidArgument("bad_color must be a vector, got shape ",
bad_color->shape().DebugString()));
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
OP_REQUIRES_OK(ctx, s->WriteImage(step, *t, tag, max_images_, *bad_color));
}
private:
int32 max_images_;
};
REGISTER_KERNEL_BUILDER(Name("WriteImageSummary").Device(DEVICE_CPU),
WriteImageSummaryOp);
class WriteAudioSummaryOp : public OpKernel {
public:
explicit WriteAudioSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("max_outputs", &max_outputs_));
OP_REQUIRES(ctx, max_outputs_ > 0,
errors::InvalidArgument("max_outputs must be > 0"));
}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* tmp;
OP_REQUIRES_OK(ctx, ctx->input("step", &tmp));
const int64 step = tmp->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tag", &tmp));
const string& tag = tmp->scalar<string>()();
OP_REQUIRES_OK(ctx, ctx->input("sample_rate", &tmp));
const float sample_rate = tmp->scalar<float>()();
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
OP_REQUIRES_OK(ctx,
s->WriteAudio(step, *t, tag, max_outputs_, sample_rate));
}
private:
int max_outputs_;
bool has_sample_rate_attr_;
float sample_rate_attr_;
};
REGISTER_KERNEL_BUILDER(Name("WriteAudioSummary").Device(DEVICE_CPU),
WriteAudioSummaryOp);
class WriteGraphSummaryOp : public OpKernel {
public:
explicit WriteGraphSummaryOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
SummaryWriterInterface* s;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &s));
core::ScopedUnref unref(s);
const Tensor* t;
OP_REQUIRES_OK(ctx, ctx->input("step", &t));
const int64 step = t->scalar<int64>()();
OP_REQUIRES_OK(ctx, ctx->input("tensor", &t));
std::unique_ptr<GraphDef> graph{new GraphDef};
if (!ParseProtoUnlimited(graph.get(), t->scalar<string>()())) {
ctx->CtxFailureWithWarning(
errors::DataLoss("Bad tf.GraphDef binary proto tensor string"));
return;
}
OP_REQUIRES_OK(ctx, s->WriteGraph(step, std::move(graph)));
}
};
REGISTER_KERNEL_BUILDER(Name("WriteGraphSummary").Device(DEVICE_CPU),
WriteGraphSummaryOp);
} // namespace tensorflow
<|endoftext|> |
<commit_before>/*
*
* Filename: test2.cc
*
* Author: Haibo Hao
* Email : haohaibo@ncic.ac.cn
* Description: ---
* Create: 2017-08-14 19:47:42
* Last Modified: 2017-08-14 19:47:42
**/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
// compile : g++ test2.cc -std=c++11
// pre-process: g++ -E test2.cc -o test2.i
[[gnu::noreturn]] void failed_abort(const char* msg, const char* file, int line)
{
printf("FAILED: %s: %s:%i\n", msg, file, line);
std::abort();
}
#define EXPECT(...) \
if(!(__VA_ARGS__)) \
failed_abort(#__VA_ARGS__,__FILE__,__LINE__)
int main()
{
int n = 100;
EXPECT(n == 100);
return 0;
}
<commit_msg>add construct type<commit_after>/*
*
* Filename: test2.cc
*
* Author: Haibo Hao
* Email : haohaibo@ncic.ac.cn
* Description: ---
* Create: 2017-08-14 19:47:42
* Last Modified: 2017-08-14 19:47:42
**/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
// compile : g++ test2.cc -std=c++11
// pre-process: g++ -E test2.cc -o test2.i
[[gnu::noreturn]] void failed_abort(const char* msg, const char* file, int line)
{
printf("FAILED: %s: %s:%i\n", msg, file, line);
std::abort();
}
#define EXPECT(...) \
if(!(__VA_ARGS__)) \
failed_abort(#__VA_ARGS__,__FILE__,__LINE__)
/* Constructs type name from a struct */
#define MIOPEN_DECLARE_OBJECT(name) \
struct name \
{ \
}; \
typedef struct name* name##_t;
int main()
{
int n = 100;
EXPECT(n == 100);
/* Create miopenTensorDescriptor_t type */
MIOPEN_DECLARE_OBJECT(miopenTensorDescriptor);
miopenTensorDescriptor_t t;
return 0;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/* This benchmark exists to ensure that the benchmark integration is
* working */
#include <sstream>
#include <grpc++/support/channel_arguments.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
extern "C" {
#include "src/core/ext/client_channel/client_channel.h"
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/compress_filter.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/channel/deadline_filter.h"
#include "src/core/lib/channel/http_client_filter.h"
#include "src/core/lib/channel/http_server_filter.h"
#include "src/core/lib/channel/message_size_filter.h"
#include "src/core/lib/transport/transport_impl.h"
}
#include "third_party/benchmark/include/benchmark/benchmark.h"
static struct Init {
Init() { grpc_init(); }
~Init() { grpc_shutdown(); }
} g_init;
static void BM_InsecureChannelWithDefaults(benchmark::State &state) {
grpc_channel *channel =
grpc_insecure_channel_create("localhost:12345", NULL, NULL);
grpc_completion_queue *cq = grpc_completion_queue_create(NULL);
grpc_slice method = grpc_slice_from_static_string("/foo/bar");
gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
while (state.KeepRunning()) {
grpc_call_destroy(grpc_channel_create_call(channel, NULL,
GRPC_PROPAGATE_DEFAULTS, cq,
method, NULL, deadline, NULL));
}
grpc_channel_destroy(channel);
}
BENCHMARK(BM_InsecureChannelWithDefaults);
static void FilterDestroy(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
gpr_free(arg);
}
static void DoNothing(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) {}
class FakeClientChannelFactory : public grpc_client_channel_factory {
public:
FakeClientChannelFactory() { vtable = &vtable_; }
private:
static void NoRef(grpc_client_channel_factory *factory) {}
static void NoUnref(grpc_exec_ctx *exec_ctx,
grpc_client_channel_factory *factory) {}
static grpc_subchannel *CreateSubchannel(grpc_exec_ctx *exec_ctx,
grpc_client_channel_factory *factory,
const grpc_subchannel_args *args) {
return nullptr;
}
static grpc_channel *CreateClientChannel(grpc_exec_ctx *exec_ctx,
grpc_client_channel_factory *factory,
const char *target,
grpc_client_channel_type type,
const grpc_channel_args *args) {
return nullptr;
}
static const grpc_client_channel_factory_vtable vtable_;
};
const grpc_client_channel_factory_vtable FakeClientChannelFactory::vtable_ = {
NoRef, NoUnref, CreateSubchannel, CreateClientChannel};
static grpc_arg StringArg(const char *key, const char *value) {
grpc_arg a;
a.type = GRPC_ARG_STRING;
a.key = const_cast<char *>(key);
a.value.string = const_cast<char *>(value);
return a;
}
enum FixtureFlags : uint32_t {
CHECKS_NOT_LAST = 1,
REQUIRES_TRANSPORT = 2,
};
template <const grpc_channel_filter *kFilter, uint32_t kFlags>
struct Fixture {
const grpc_channel_filter *filter = kFilter;
const uint32_t flags = kFlags;
};
namespace dummy_filter {
static void StartTransportStreamOp(grpc_exec_ctx *exec_ctx,
grpc_call_element *elem,
grpc_transport_stream_op *op) {}
static void StartTransportOp(grpc_exec_ctx *exec_ctx,
grpc_channel_element *elem,
grpc_transport_op *op) {}
static grpc_error *InitCallElem(grpc_exec_ctx *exec_ctx,
grpc_call_element *elem,
const grpc_call_element_args *args) {
return GRPC_ERROR_NONE;
}
static void SetPollsetOrPollsetSet(grpc_exec_ctx *exec_ctx,
grpc_call_element *elem,
grpc_polling_entity *pollent) {}
static void DestroyCallElem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem,
const grpc_call_final_info *final_info,
void *and_free_memory) {}
grpc_error *InitChannelElem(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem,
grpc_channel_element_args *args) {
return GRPC_ERROR_NONE;
}
void DestroyChannelElem(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem) {}
char *GetPeer(grpc_exec_ctx *exec_ctx, grpc_call_element *elem) {
return gpr_strdup("peer");
}
void GetChannelInfo(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem,
const grpc_channel_info *channel_info) {}
static const grpc_channel_filter dummy_filter = {StartTransportStreamOp,
StartTransportOp,
0,
InitCallElem,
SetPollsetOrPollsetSet,
DestroyCallElem,
0,
InitChannelElem,
DestroyChannelElem,
GetPeer,
GetChannelInfo,
"dummy_filter"};
} // namespace dummy_filter
namespace dummy_transport {
/* Memory required for a single stream element - this is allocated by upper
layers and initialized by the transport */
size_t sizeof_stream; /* = sizeof(transport stream) */
/* name of this transport implementation */
const char *name;
/* implementation of grpc_transport_init_stream */
int InitStream(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_stream_refcount *refcount,
const void *server_data) {
return 0;
}
/* implementation of grpc_transport_set_pollset */
void SetPollset(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_pollset *pollset) {}
/* implementation of grpc_transport_set_pollset */
void SetPollsetSet(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_pollset_set *pollset_set) {}
/* implementation of grpc_transport_perform_stream_op */
void PerformStreamOp(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_transport_stream_op *op) {}
/* implementation of grpc_transport_perform_op */
void PerformOp(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_transport_op *op) {}
/* implementation of grpc_transport_destroy_stream */
void DestroyStream(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, void *and_free_memory) {}
/* implementation of grpc_transport_destroy */
void Destroy(grpc_exec_ctx *exec_ctx, grpc_transport *self) {}
/* implementation of grpc_transport_get_peer */
char *GetPeer(grpc_exec_ctx *exec_ctx, grpc_transport *self) {
return gpr_strdup("transport_peer");
}
/* implementation of grpc_transport_get_endpoint */
grpc_endpoint *GetEndpoint(grpc_exec_ctx *exec_ctx, grpc_transport *self) {
return nullptr;
}
static const grpc_transport_vtable dummy_transport_vtable = {
0, "dummy_http2", InitStream,
SetPollset, SetPollsetSet, PerformStreamOp,
PerformOp, DestroyStream, Destroy,
GetPeer, GetEndpoint};
static grpc_transport dummy_transport = {&dummy_transport_vtable};
} // namespace dummy_transport
template <class Fixture>
static void BM_FilterInitDestroy(benchmark::State &state) {
Fixture fixture;
std::ostringstream label;
std::vector<grpc_arg> args;
FakeClientChannelFactory fake_client_channel_factory;
args.push_back(grpc_client_channel_factory_create_channel_arg(
&fake_client_channel_factory));
args.push_back(StringArg(GRPC_ARG_SERVER_URI, "localhost"));
grpc_channel_args channel_args = {args.size(), &args[0]};
std::vector<const grpc_channel_filter *> filters;
if (fixture.filter != nullptr) {
filters.push_back(fixture.filter);
}
if (fixture.flags & CHECKS_NOT_LAST) {
filters.push_back(&dummy_filter::dummy_filter);
label << " has_dummy_filter";
}
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
size_t channel_size = grpc_channel_stack_size(&filters[0], filters.size());
grpc_channel_stack *channel_stack =
static_cast<grpc_channel_stack *>(gpr_malloc(channel_size));
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"call_stack_init",
grpc_channel_stack_init(&exec_ctx, 1, FilterDestroy, channel_stack,
&filters[0], filters.size(), &channel_args,
fixture.flags & REQUIRES_TRANSPORT
? &dummy_transport::dummy_transport
: nullptr,
"CHANNEL", channel_stack)));
grpc_exec_ctx_flush(&exec_ctx);
grpc_call_stack *call_stack = static_cast<grpc_call_stack *>(
gpr_malloc(channel_stack->call_stack_size));
gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
gpr_timespec start_time = gpr_now(GPR_CLOCK_MONOTONIC);
grpc_slice method = grpc_slice_from_static_string("/foo/bar");
grpc_call_final_info final_info;
while (state.KeepRunning()) {
GRPC_ERROR_UNREF(grpc_call_stack_init(&exec_ctx, channel_stack, 1,
DoNothing, NULL, NULL, NULL, method,
start_time, deadline, call_stack));
grpc_call_stack_destroy(&exec_ctx, call_stack, &final_info, NULL);
grpc_exec_ctx_flush(&exec_ctx);
}
grpc_channel_stack_destroy(&exec_ctx, channel_stack);
grpc_exec_ctx_finish(&exec_ctx);
state.SetLabel(label.str());
}
typedef Fixture<nullptr, 0> NoFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, NoFilter);
typedef Fixture<&dummy_filter::dummy_filter, 0> DummyFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, DummyFilter);
typedef Fixture<&grpc_client_channel_filter, 0> ClientChannelFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, ClientChannelFilter);
typedef Fixture<&grpc_compress_filter, CHECKS_NOT_LAST> CompressFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, CompressFilter);
typedef Fixture<&grpc_client_deadline_filter, CHECKS_NOT_LAST>
ClientDeadlineFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, ClientDeadlineFilter);
typedef Fixture<&grpc_server_deadline_filter, CHECKS_NOT_LAST>
ServerDeadlineFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, ServerDeadlineFilter);
typedef Fixture<&grpc_http_client_filter, CHECKS_NOT_LAST | REQUIRES_TRANSPORT>
HttpClientFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, HttpClientFilter);
typedef Fixture<&grpc_http_server_filter, CHECKS_NOT_LAST> HttpServerFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, HttpServerFilter);
typedef Fixture<&grpc_message_size_filter, CHECKS_NOT_LAST> MessageSizeFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, MessageSizeFilter);
BENCHMARK_MAIN();
<commit_msg>Add load reporting<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/* This benchmark exists to ensure that the benchmark integration is
* working */
#include <sstream>
#include <grpc++/support/channel_arguments.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
extern "C" {
#include "src/core/ext/client_channel/client_channel.h"
#include "src/core/ext/load_reporting/load_reporting_filter.h"
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/compress_filter.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/channel/deadline_filter.h"
#include "src/core/lib/channel/http_client_filter.h"
#include "src/core/lib/channel/http_server_filter.h"
#include "src/core/lib/channel/message_size_filter.h"
#include "src/core/lib/transport/transport_impl.h"
}
#include "third_party/benchmark/include/benchmark/benchmark.h"
static struct Init {
Init() { grpc_init(); }
~Init() { grpc_shutdown(); }
} g_init;
static void BM_InsecureChannelWithDefaults(benchmark::State &state) {
grpc_channel *channel =
grpc_insecure_channel_create("localhost:12345", NULL, NULL);
grpc_completion_queue *cq = grpc_completion_queue_create(NULL);
grpc_slice method = grpc_slice_from_static_string("/foo/bar");
gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
while (state.KeepRunning()) {
grpc_call_destroy(grpc_channel_create_call(channel, NULL,
GRPC_PROPAGATE_DEFAULTS, cq,
method, NULL, deadline, NULL));
}
grpc_channel_destroy(channel);
}
BENCHMARK(BM_InsecureChannelWithDefaults);
static void FilterDestroy(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
gpr_free(arg);
}
static void DoNothing(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) {}
class FakeClientChannelFactory : public grpc_client_channel_factory {
public:
FakeClientChannelFactory() { vtable = &vtable_; }
private:
static void NoRef(grpc_client_channel_factory *factory) {}
static void NoUnref(grpc_exec_ctx *exec_ctx,
grpc_client_channel_factory *factory) {}
static grpc_subchannel *CreateSubchannel(grpc_exec_ctx *exec_ctx,
grpc_client_channel_factory *factory,
const grpc_subchannel_args *args) {
return nullptr;
}
static grpc_channel *CreateClientChannel(grpc_exec_ctx *exec_ctx,
grpc_client_channel_factory *factory,
const char *target,
grpc_client_channel_type type,
const grpc_channel_args *args) {
return nullptr;
}
static const grpc_client_channel_factory_vtable vtable_;
};
const grpc_client_channel_factory_vtable FakeClientChannelFactory::vtable_ = {
NoRef, NoUnref, CreateSubchannel, CreateClientChannel};
static grpc_arg StringArg(const char *key, const char *value) {
grpc_arg a;
a.type = GRPC_ARG_STRING;
a.key = const_cast<char *>(key);
a.value.string = const_cast<char *>(value);
return a;
}
enum FixtureFlags : uint32_t {
CHECKS_NOT_LAST = 1,
REQUIRES_TRANSPORT = 2,
};
template <const grpc_channel_filter *kFilter, uint32_t kFlags>
struct Fixture {
const grpc_channel_filter *filter = kFilter;
const uint32_t flags = kFlags;
};
namespace dummy_filter {
static void StartTransportStreamOp(grpc_exec_ctx *exec_ctx,
grpc_call_element *elem,
grpc_transport_stream_op *op) {}
static void StartTransportOp(grpc_exec_ctx *exec_ctx,
grpc_channel_element *elem,
grpc_transport_op *op) {}
static grpc_error *InitCallElem(grpc_exec_ctx *exec_ctx,
grpc_call_element *elem,
const grpc_call_element_args *args) {
return GRPC_ERROR_NONE;
}
static void SetPollsetOrPollsetSet(grpc_exec_ctx *exec_ctx,
grpc_call_element *elem,
grpc_polling_entity *pollent) {}
static void DestroyCallElem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem,
const grpc_call_final_info *final_info,
void *and_free_memory) {}
grpc_error *InitChannelElem(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem,
grpc_channel_element_args *args) {
return GRPC_ERROR_NONE;
}
void DestroyChannelElem(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem) {}
char *GetPeer(grpc_exec_ctx *exec_ctx, grpc_call_element *elem) {
return gpr_strdup("peer");
}
void GetChannelInfo(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem,
const grpc_channel_info *channel_info) {}
static const grpc_channel_filter dummy_filter = {StartTransportStreamOp,
StartTransportOp,
0,
InitCallElem,
SetPollsetOrPollsetSet,
DestroyCallElem,
0,
InitChannelElem,
DestroyChannelElem,
GetPeer,
GetChannelInfo,
"dummy_filter"};
} // namespace dummy_filter
namespace dummy_transport {
/* Memory required for a single stream element - this is allocated by upper
layers and initialized by the transport */
size_t sizeof_stream; /* = sizeof(transport stream) */
/* name of this transport implementation */
const char *name;
/* implementation of grpc_transport_init_stream */
int InitStream(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_stream_refcount *refcount,
const void *server_data) {
return 0;
}
/* implementation of grpc_transport_set_pollset */
void SetPollset(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_pollset *pollset) {}
/* implementation of grpc_transport_set_pollset */
void SetPollsetSet(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_pollset_set *pollset_set) {}
/* implementation of grpc_transport_perform_stream_op */
void PerformStreamOp(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, grpc_transport_stream_op *op) {}
/* implementation of grpc_transport_perform_op */
void PerformOp(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_transport_op *op) {}
/* implementation of grpc_transport_destroy_stream */
void DestroyStream(grpc_exec_ctx *exec_ctx, grpc_transport *self,
grpc_stream *stream, void *and_free_memory) {}
/* implementation of grpc_transport_destroy */
void Destroy(grpc_exec_ctx *exec_ctx, grpc_transport *self) {}
/* implementation of grpc_transport_get_peer */
char *GetPeer(grpc_exec_ctx *exec_ctx, grpc_transport *self) {
return gpr_strdup("transport_peer");
}
/* implementation of grpc_transport_get_endpoint */
grpc_endpoint *GetEndpoint(grpc_exec_ctx *exec_ctx, grpc_transport *self) {
return nullptr;
}
static const grpc_transport_vtable dummy_transport_vtable = {
0, "dummy_http2", InitStream,
SetPollset, SetPollsetSet, PerformStreamOp,
PerformOp, DestroyStream, Destroy,
GetPeer, GetEndpoint};
static grpc_transport dummy_transport = {&dummy_transport_vtable};
} // namespace dummy_transport
template <class Fixture>
static void BM_FilterInitDestroy(benchmark::State &state) {
Fixture fixture;
std::ostringstream label;
std::vector<grpc_arg> args;
FakeClientChannelFactory fake_client_channel_factory;
args.push_back(grpc_client_channel_factory_create_channel_arg(
&fake_client_channel_factory));
args.push_back(StringArg(GRPC_ARG_SERVER_URI, "localhost"));
grpc_channel_args channel_args = {args.size(), &args[0]};
std::vector<const grpc_channel_filter *> filters;
if (fixture.filter != nullptr) {
filters.push_back(fixture.filter);
}
if (fixture.flags & CHECKS_NOT_LAST) {
filters.push_back(&dummy_filter::dummy_filter);
label << " has_dummy_filter";
}
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
size_t channel_size = grpc_channel_stack_size(&filters[0], filters.size());
grpc_channel_stack *channel_stack =
static_cast<grpc_channel_stack *>(gpr_malloc(channel_size));
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"call_stack_init",
grpc_channel_stack_init(&exec_ctx, 1, FilterDestroy, channel_stack,
&filters[0], filters.size(), &channel_args,
fixture.flags & REQUIRES_TRANSPORT
? &dummy_transport::dummy_transport
: nullptr,
"CHANNEL", channel_stack)));
grpc_exec_ctx_flush(&exec_ctx);
grpc_call_stack *call_stack = static_cast<grpc_call_stack *>(
gpr_malloc(channel_stack->call_stack_size));
gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
gpr_timespec start_time = gpr_now(GPR_CLOCK_MONOTONIC);
grpc_slice method = grpc_slice_from_static_string("/foo/bar");
grpc_call_final_info final_info;
while (state.KeepRunning()) {
GRPC_ERROR_UNREF(grpc_call_stack_init(&exec_ctx, channel_stack, 1,
DoNothing, NULL, NULL, NULL, method,
start_time, deadline, call_stack));
grpc_call_stack_destroy(&exec_ctx, call_stack, &final_info, NULL);
grpc_exec_ctx_flush(&exec_ctx);
}
grpc_channel_stack_destroy(&exec_ctx, channel_stack);
grpc_exec_ctx_finish(&exec_ctx);
state.SetLabel(label.str());
}
typedef Fixture<nullptr, 0> NoFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, NoFilter);
typedef Fixture<&dummy_filter::dummy_filter, 0> DummyFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, DummyFilter);
typedef Fixture<&grpc_client_channel_filter, 0> ClientChannelFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, ClientChannelFilter);
typedef Fixture<&grpc_compress_filter, CHECKS_NOT_LAST> CompressFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, CompressFilter);
typedef Fixture<&grpc_client_deadline_filter, CHECKS_NOT_LAST>
ClientDeadlineFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, ClientDeadlineFilter);
typedef Fixture<&grpc_server_deadline_filter, CHECKS_NOT_LAST>
ServerDeadlineFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, ServerDeadlineFilter);
typedef Fixture<&grpc_http_client_filter, CHECKS_NOT_LAST | REQUIRES_TRANSPORT>
HttpClientFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, HttpClientFilter);
typedef Fixture<&grpc_http_server_filter, CHECKS_NOT_LAST> HttpServerFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, HttpServerFilter);
typedef Fixture<&grpc_message_size_filter, CHECKS_NOT_LAST> MessageSizeFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, MessageSizeFilter);
typedef Fixture<&grpc_load_reporting_filter, CHECKS_NOT_LAST>
LoadReportingFilter;
BENCHMARK_TEMPLATE(BM_FilterInitDestroy, LoadReportingFilter);
BENCHMARK_MAIN();
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2022 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; withexpected even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "common/BayerPhase.h"
#include <algorithm> // for fill, min, copy, equal, fill_n, max
#include <array> // for array
#include <cassert> // for assert
#include <cstddef> // for size_t
#include <cstdint> // for uint8_t, uint16_t
#include <gtest/gtest.h> // for ParamIteratorInterface, ParamGeneratorInt...
#include <limits> // for numeric_limits
#include <memory> // for allocator, make_unique, unique_ptr
#include <string> // for basic_string, string, operator==
#include <tuple> // for make_tuple, get, tuple
#include <type_traits> // for __strip_reference_wrapper<>::__type
#include <vector> // for vector, vector<>::iterator, vector<>::val...
using rawspeed::BayerPhase;
using rawspeed::CFAColor;
using rawspeed::ColorFilterArray;
namespace rawspeed {
::std::ostream& operator<<(::std::ostream& os, const BayerPhase p) {
switch (p) {
case BayerPhase::RGGB:
return os << "RGGB";
case BayerPhase::GRBG:
return os << "GRBG";
case BayerPhase::GBRG:
return os << "GBRG";
case BayerPhase::BGGR:
return os << "BGGR";
}
}
} // namespace rawspeed
namespace rawspeed_test {
auto AllKnownCFAColors =
::testing::Values(CFAColor::RED, CFAColor::GREEN, CFAColor::BLUE,
CFAColor::CYAN, CFAColor::MAGENTA, CFAColor::YELLOW,
CFAColor::WHITE, CFAColor::FUJI_GREEN, CFAColor::UNKNOWN);
auto AllKnownBayerPhases = ::testing::Values(
BayerPhase::RGGB, BayerPhase::GRBG, BayerPhase::GBRG, BayerPhase::BGGR);
auto AllPossible2x2CFAs = ::testing::Combine(
AllKnownCFAColors, AllKnownCFAColors, AllKnownCFAColors, AllKnownCFAColors);
auto AllPossibleBayerPhaseShifts =
::testing::Combine(AllKnownBayerPhases, AllKnownBayerPhases);
static const std::map<std::array<CFAColor, 4>, BayerPhase> KnownBayerCFAs = {
{{CFAColor::RED, CFAColor::GREEN, CFAColor::GREEN, CFAColor::BLUE},
BayerPhase::RGGB},
{{CFAColor::GREEN, CFAColor::RED, CFAColor::BLUE, CFAColor::GREEN},
BayerPhase::GRBG},
{{CFAColor::GREEN, CFAColor::BLUE, CFAColor::RED, CFAColor::GREEN},
BayerPhase::GBRG},
{{CFAColor::BLUE, CFAColor::GREEN, CFAColor::GREEN, CFAColor::RED},
BayerPhase::BGGR},
};
template <typename tuple_t>
constexpr auto get_array_from_tuple(tuple_t&& tuple) {
constexpr auto get_array = [](auto&&... x) {
return std::array{std::forward<decltype(x)>(x)...};
};
return std::apply(get_array, std::forward<tuple_t>(tuple));
}
class BayerPhaseFromCFATest
: public ::testing::TestWithParam<
std::tuple<CFAColor, CFAColor, CFAColor, CFAColor>> {
protected:
BayerPhaseFromCFATest() = default;
virtual void SetUp() {
in = get_array_from_tuple(GetParam());
if (auto it = KnownBayerCFAs.find(in); it != KnownBayerCFAs.end())
expected = it->second;
cfa.setCFA({2, 2}, in[0], in[1], in[2], in[3]);
}
std::array<CFAColor, 4> in;
std::optional<BayerPhase> expected;
ColorFilterArray cfa;
};
INSTANTIATE_TEST_CASE_P(All2x2CFAs, BayerPhaseFromCFATest, AllPossible2x2CFAs);
TEST_P(BayerPhaseFromCFATest, getAsBayerPhaseTest) {
EXPECT_EQ(expected, rawspeed::getAsBayerPhase(cfa));
}
class BayerPhaseToCFATest : public ::testing::TestWithParam<BayerPhase> {
protected:
BayerPhaseToCFATest() = default;
virtual void SetUp() {
for (auto it : KnownBayerCFAs) {
if (it.second == GetParam()) {
in = it.second;
expected = it.first;
break;
}
}
assert(in.has_value());
}
std::optional<BayerPhase> in;
std::array<CFAColor, 4> expected;
};
INSTANTIATE_TEST_CASE_P(AllBayerPhases, BayerPhaseToCFATest,
AllKnownBayerPhases);
TEST_P(BayerPhaseToCFATest, getAsCFAColorsTest) {
EXPECT_EQ(expected, rawspeed::getAsCFAColors(*in));
}
class BayerPhaseShifTest
: public ::testing::TestWithParam<std::tuple<BayerPhase, BayerPhase>> {
protected:
BayerPhaseShifTest() = default;
virtual void SetUp() {
src = std::get<0>(GetParam());
tgt = std::get<1>(GetParam());
}
BayerPhase src;
BayerPhase tgt;
};
INSTANTIATE_TEST_CASE_P(AllBayerPhaseShifts, BayerPhaseShifTest,
AllPossibleBayerPhaseShifts);
struct AbstractElement {};
struct TopLeftElement final : AbstractElement {};
struct TopRightElement final : AbstractElement {};
struct BottomLeftElement final : AbstractElement {};
struct BottomRightElement final : AbstractElement {};
static const TopLeftElement e00;
static const TopRightElement e01;
static const BottomLeftElement e10;
static const BottomRightElement e11;
::std::ostream& operator<<(::std::ostream& os, const AbstractElement* e) {
if (&e00 == e)
return os << "e00";
if (&e01 == e)
return os << "e01";
if (&e10 == e)
return os << "e10";
if (&e11 == e)
return os << "e11";
__builtin_unreachable();
}
static const std::map<BayerPhase, std::array<const AbstractElement*, 4>>
ExpectedBayerPhaseShifts = {
{BayerPhase::RGGB, {&e00, &e01, &e10, &e11}}, // baseline
{BayerPhase::GRBG, {&e01, &e00, &e11, &e10}}, // swap columns
{BayerPhase::GBRG, {&e10, &e11, &e00, &e01}}, // swap rows
{BayerPhase::BGGR, {&e11, &e10, &e01, &e00}}, // swap rows and columns
};
TEST_P(BayerPhaseShifTest, applyPhaseShiftTest) {
EXPECT_EQ(
ExpectedBayerPhaseShifts.at(tgt),
rawspeed::applyPhaseShift(ExpectedBayerPhaseShifts.at(src), src, tgt));
}
struct AbstractColorElement {};
struct RedElement final : AbstractColorElement {};
struct FirstGreenElement final : AbstractColorElement {};
struct SecondGreenElement final : AbstractColorElement {};
struct BlueElement final : AbstractColorElement {};
static const RedElement eR;
static const FirstGreenElement eG0;
static const SecondGreenElement eG1;
static const BlueElement eB;
::std::ostream& operator<<(::std::ostream& os, const AbstractColorElement* e) {
if (&eR == e)
return os << "eR";
if (&eG0 == e)
return os << "eG0";
if (&eG1 == e)
return os << "eG1";
if (&eB == e)
return os << "eB";
__builtin_unreachable();
}
static const std::map<BayerPhase, std::array<const AbstractColorElement*, 4>>
ExpectedBayerStablePhaseShifts = {
{BayerPhase::RGGB, {&eR, &eG0, &eG1, &eB}}, // baseline
{BayerPhase::GRBG, {&eG0, &eR, &eB, &eG1}}, // swap columns
{BayerPhase::GBRG, {&eG0, &eB, &eR, &eG1}}, // swap rows
{BayerPhase::BGGR, {&eB, &eG0, &eG1, &eR}}, // swap rows and columns
};
TEST_P(BayerPhaseShifTest, applyStablePhaseShiftTest) {
EXPECT_EQ(ExpectedBayerStablePhaseShifts.at(tgt),
rawspeed::applyStablePhaseShift(
ExpectedBayerStablePhaseShifts.at(src), src, tgt));
}
} // namespace rawspeed_test
<commit_msg>Fix GCC build. Filed https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107763<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2022 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; withexpected even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "common/BayerPhase.h"
#include <algorithm> // for fill, min, copy, equal, fill_n, max
#include <array> // for array
#include <cassert> // for assert
#include <cstddef> // for size_t
#include <cstdint> // for uint8_t, uint16_t
#include <gtest/gtest.h> // for ParamIteratorInterface, ParamGeneratorInt...
#include <limits> // for numeric_limits
#include <memory> // for allocator, make_unique, unique_ptr
#include <string> // for basic_string, string, operator==
#include <tuple> // for make_tuple, get, tuple
#include <type_traits> // for __strip_reference_wrapper<>::__type
#include <vector> // for vector, vector<>::iterator, vector<>::val...
using rawspeed::BayerPhase;
using rawspeed::CFAColor;
using rawspeed::ColorFilterArray;
namespace rawspeed {
::std::ostream& operator<<(::std::ostream& os, const BayerPhase p) {
switch (p) {
case BayerPhase::RGGB:
return os << "RGGB";
case BayerPhase::GRBG:
return os << "GRBG";
case BayerPhase::GBRG:
return os << "GBRG";
case BayerPhase::BGGR:
return os << "BGGR";
}
__builtin_unreachable();
}
} // namespace rawspeed
namespace rawspeed_test {
auto AllKnownCFAColors =
::testing::Values(CFAColor::RED, CFAColor::GREEN, CFAColor::BLUE,
CFAColor::CYAN, CFAColor::MAGENTA, CFAColor::YELLOW,
CFAColor::WHITE, CFAColor::FUJI_GREEN, CFAColor::UNKNOWN);
auto AllKnownBayerPhases = ::testing::Values(
BayerPhase::RGGB, BayerPhase::GRBG, BayerPhase::GBRG, BayerPhase::BGGR);
auto AllPossible2x2CFAs = ::testing::Combine(
AllKnownCFAColors, AllKnownCFAColors, AllKnownCFAColors, AllKnownCFAColors);
auto AllPossibleBayerPhaseShifts =
::testing::Combine(AllKnownBayerPhases, AllKnownBayerPhases);
static const std::map<std::array<CFAColor, 4>, BayerPhase> KnownBayerCFAs = {
{{CFAColor::RED, CFAColor::GREEN, CFAColor::GREEN, CFAColor::BLUE},
BayerPhase::RGGB},
{{CFAColor::GREEN, CFAColor::RED, CFAColor::BLUE, CFAColor::GREEN},
BayerPhase::GRBG},
{{CFAColor::GREEN, CFAColor::BLUE, CFAColor::RED, CFAColor::GREEN},
BayerPhase::GBRG},
{{CFAColor::BLUE, CFAColor::GREEN, CFAColor::GREEN, CFAColor::RED},
BayerPhase::BGGR},
};
template <typename tuple_t>
constexpr auto get_array_from_tuple(tuple_t&& tuple) {
constexpr auto get_array = [](auto&&... x) {
return std::array{std::forward<decltype(x)>(x)...};
};
return std::apply(get_array, std::forward<tuple_t>(tuple));
}
class BayerPhaseFromCFATest
: public ::testing::TestWithParam<
std::tuple<CFAColor, CFAColor, CFAColor, CFAColor>> {
protected:
BayerPhaseFromCFATest() = default;
virtual void SetUp() {
in = get_array_from_tuple(GetParam());
if (auto it = KnownBayerCFAs.find(in); it != KnownBayerCFAs.end())
expected = it->second;
cfa.setCFA({2, 2}, in[0], in[1], in[2], in[3]);
}
std::array<CFAColor, 4> in;
std::optional<BayerPhase> expected;
ColorFilterArray cfa;
};
INSTANTIATE_TEST_CASE_P(All2x2CFAs, BayerPhaseFromCFATest, AllPossible2x2CFAs);
TEST_P(BayerPhaseFromCFATest, getAsBayerPhaseTest) {
EXPECT_EQ(expected, rawspeed::getAsBayerPhase(cfa));
}
class BayerPhaseToCFATest : public ::testing::TestWithParam<BayerPhase> {
protected:
BayerPhaseToCFATest() = default;
virtual void SetUp() {
for (auto it : KnownBayerCFAs) {
if (it.second == GetParam()) {
in = it.second;
expected = it.first;
break;
}
}
assert(in.has_value());
}
std::optional<BayerPhase> in;
std::array<CFAColor, 4> expected;
};
INSTANTIATE_TEST_CASE_P(AllBayerPhases, BayerPhaseToCFATest,
AllKnownBayerPhases);
TEST_P(BayerPhaseToCFATest, getAsCFAColorsTest) {
EXPECT_EQ(expected, rawspeed::getAsCFAColors(*in));
}
class BayerPhaseShifTest
: public ::testing::TestWithParam<std::tuple<BayerPhase, BayerPhase>> {
protected:
BayerPhaseShifTest() = default;
virtual void SetUp() {
src = std::get<0>(GetParam());
tgt = std::get<1>(GetParam());
}
BayerPhase src;
BayerPhase tgt;
};
INSTANTIATE_TEST_CASE_P(AllBayerPhaseShifts, BayerPhaseShifTest,
AllPossibleBayerPhaseShifts);
struct AbstractElement {};
struct TopLeftElement final : AbstractElement {};
struct TopRightElement final : AbstractElement {};
struct BottomLeftElement final : AbstractElement {};
struct BottomRightElement final : AbstractElement {};
static const TopLeftElement e00;
static const TopRightElement e01;
static const BottomLeftElement e10;
static const BottomRightElement e11;
::std::ostream& operator<<(::std::ostream& os, const AbstractElement* e) {
if (&e00 == e)
return os << "e00";
if (&e01 == e)
return os << "e01";
if (&e10 == e)
return os << "e10";
if (&e11 == e)
return os << "e11";
__builtin_unreachable();
}
static const std::map<BayerPhase, std::array<const AbstractElement*, 4>>
ExpectedBayerPhaseShifts = {
{BayerPhase::RGGB, {&e00, &e01, &e10, &e11}}, // baseline
{BayerPhase::GRBG, {&e01, &e00, &e11, &e10}}, // swap columns
{BayerPhase::GBRG, {&e10, &e11, &e00, &e01}}, // swap rows
{BayerPhase::BGGR, {&e11, &e10, &e01, &e00}}, // swap rows and columns
};
TEST_P(BayerPhaseShifTest, applyPhaseShiftTest) {
EXPECT_EQ(
ExpectedBayerPhaseShifts.at(tgt),
rawspeed::applyPhaseShift(ExpectedBayerPhaseShifts.at(src), src, tgt));
}
struct AbstractColorElement {};
struct RedElement final : AbstractColorElement {};
struct FirstGreenElement final : AbstractColorElement {};
struct SecondGreenElement final : AbstractColorElement {};
struct BlueElement final : AbstractColorElement {};
static const RedElement eR;
static const FirstGreenElement eG0;
static const SecondGreenElement eG1;
static const BlueElement eB;
::std::ostream& operator<<(::std::ostream& os, const AbstractColorElement* e) {
if (&eR == e)
return os << "eR";
if (&eG0 == e)
return os << "eG0";
if (&eG1 == e)
return os << "eG1";
if (&eB == e)
return os << "eB";
__builtin_unreachable();
}
static const std::map<BayerPhase, std::array<const AbstractColorElement*, 4>>
ExpectedBayerStablePhaseShifts = {
{BayerPhase::RGGB, {&eR, &eG0, &eG1, &eB}}, // baseline
{BayerPhase::GRBG, {&eG0, &eR, &eB, &eG1}}, // swap columns
{BayerPhase::GBRG, {&eG0, &eB, &eR, &eG1}}, // swap rows
{BayerPhase::BGGR, {&eB, &eG0, &eG1, &eR}}, // swap rows and columns
};
TEST_P(BayerPhaseShifTest, applyStablePhaseShiftTest) {
EXPECT_EQ(ExpectedBayerStablePhaseShifts.at(tgt),
rawspeed::applyStablePhaseShift(
ExpectedBayerStablePhaseShifts.at(src), src, tgt));
}
} // namespace rawspeed_test
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google 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 "font_collection.h"
#include <algorithm>
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "font_skia.h"
#include "txt/platform.h"
#include "txt/text_style.h"
namespace txt {
namespace {
const std::shared_ptr<minikin::FontFamily> g_null_family;
} // anonymous namespace
FontCollection::FamilyKey::FamilyKey(const std::vector<std::string>& families,
const std::string& loc) {
locale = loc;
std::stringstream stream;
for_each(families.begin(), families.end(),
[&stream](const std::string& str) { stream << str << ','; });
font_families = stream.str();
}
bool FontCollection::FamilyKey::operator==(
const FontCollection::FamilyKey& other) const {
return font_families == other.font_families && locale == other.locale;
}
size_t FontCollection::FamilyKey::Hasher::operator()(
const FontCollection::FamilyKey& key) const {
return std::hash<std::string>()(key.font_families) ^
std::hash<std::string>()(key.locale);
}
class TxtFallbackFontProvider
: public minikin::FontCollection::FallbackFontProvider {
public:
TxtFallbackFontProvider(std::shared_ptr<FontCollection> font_collection)
: font_collection_(font_collection) {}
virtual const std::shared_ptr<minikin::FontFamily>& matchFallbackFont(
uint32_t ch,
std::string locale) {
std::shared_ptr<FontCollection> fc = font_collection_.lock();
if (fc) {
return fc->MatchFallbackFont(ch, locale);
} else {
return g_null_family;
}
}
private:
std::weak_ptr<FontCollection> font_collection_;
};
FontCollection::FontCollection() : enable_font_fallback_(true) {}
FontCollection::~FontCollection() = default;
size_t FontCollection::GetFontManagersCount() const {
return GetFontManagerOrder().size();
}
void FontCollection::SetupDefaultFontManager() {
default_font_manager_ = GetDefaultFontManager();
}
void FontCollection::SetDefaultFontManager(sk_sp<SkFontMgr> font_manager) {
default_font_manager_ = font_manager;
}
void FontCollection::SetAssetFontManager(sk_sp<SkFontMgr> font_manager) {
asset_font_manager_ = font_manager;
}
void FontCollection::SetDynamicFontManager(sk_sp<SkFontMgr> font_manager) {
dynamic_font_manager_ = font_manager;
}
void FontCollection::SetTestFontManager(sk_sp<SkFontMgr> font_manager) {
test_font_manager_ = font_manager;
}
// Return the available font managers in the order they should be queried.
std::vector<sk_sp<SkFontMgr>> FontCollection::GetFontManagerOrder() const {
std::vector<sk_sp<SkFontMgr>> order;
if (dynamic_font_manager_)
order.push_back(dynamic_font_manager_);
if (asset_font_manager_)
order.push_back(asset_font_manager_);
if (test_font_manager_)
order.push_back(test_font_manager_);
if (default_font_manager_)
order.push_back(default_font_manager_);
return order;
}
void FontCollection::DisableFontFallback() {
enable_font_fallback_ = false;
}
std::shared_ptr<minikin::FontCollection>
FontCollection::GetMinikinFontCollectionForFamilies(
const std::vector<std::string>& font_families,
const std::string& locale) {
// Look inside the font collections cache first.
FamilyKey family_key(font_families, locale);
auto cached = font_collections_cache_.find(family_key);
if (cached != font_collections_cache_.end()) {
return cached->second;
}
std::vector<std::shared_ptr<minikin::FontFamily>> minikin_families;
// Search for all user provided font families.
for (size_t fallback_index = 0; fallback_index < font_families.size();
fallback_index++) {
std::shared_ptr<minikin::FontFamily> minikin_family =
FindFontFamilyInManagers(font_families[fallback_index]);
if (minikin_family != nullptr) {
minikin_families.push_back(minikin_family);
}
}
// Search for default font family if no user font families were found.
if (minikin_families.empty()) {
const auto default_font_family = GetDefaultFontFamily();
std::shared_ptr<minikin::FontFamily> minikin_family =
FindFontFamilyInManagers(default_font_family);
if (minikin_family != nullptr) {
minikin_families.push_back(minikin_family);
}
}
// Default font family also not found. We fail to get a FontCollection.
if (minikin_families.empty()) {
font_collections_cache_[family_key] = nullptr;
return nullptr;
}
if (enable_font_fallback_) {
for (std::string fallback_family : fallback_fonts_for_locale_[locale]) {
auto it = fallback_fonts_.find(fallback_family);
if (it != fallback_fonts_.end()) {
minikin_families.push_back(it->second);
}
}
}
// Create the minikin font collection.
auto font_collection =
std::make_shared<minikin::FontCollection>(std::move(minikin_families));
if (enable_font_fallback_) {
font_collection->set_fallback_font_provider(
std::make_unique<TxtFallbackFontProvider>(shared_from_this()));
}
// Cache the font collection for future queries.
font_collections_cache_[family_key] = font_collection;
return font_collection;
}
std::shared_ptr<minikin::FontFamily> FontCollection::FindFontFamilyInManagers(
const std::string& family_name) {
TRACE_EVENT0("flutter", "FontCollection::FindFontFamilyInManagers");
// Search for the font family in each font manager.
for (sk_sp<SkFontMgr>& manager : GetFontManagerOrder()) {
std::shared_ptr<minikin::FontFamily> minikin_family =
CreateMinikinFontFamily(manager, family_name);
if (!minikin_family)
continue;
return minikin_family;
}
return nullptr;
}
std::shared_ptr<minikin::FontFamily> FontCollection::CreateMinikinFontFamily(
const sk_sp<SkFontMgr>& manager,
const std::string& family_name) {
TRACE_EVENT1("flutter", "FontCollection::CreateMinikinFontFamily",
"family_name", family_name.c_str());
sk_sp<SkFontStyleSet> font_style_set(
manager->matchFamily(family_name.c_str()));
if (font_style_set == nullptr || font_style_set->count() == 0) {
return nullptr;
}
std::vector<minikin::Font> minikin_fonts;
// Add fonts to the Minikin font family.
for (int i = 0; i < font_style_set->count(); ++i) {
TRACE_EVENT0("flutter", "CreateMinikinFont");
// Create the skia typeface.
sk_sp<SkTypeface> skia_typeface(
sk_sp<SkTypeface>(font_style_set->createTypeface(i)));
if (skia_typeface == nullptr) {
continue;
}
// Create the minikin font from the skia typeface.
// Divide by 100 because the weights are given as "100", "200", etc.
minikin::Font minikin_font(
std::make_shared<FontSkia>(skia_typeface),
minikin::FontStyle{skia_typeface->fontStyle().weight() / 100,
skia_typeface->isItalic()});
minikin_fonts.emplace_back(std::move(minikin_font));
}
return std::make_shared<minikin::FontFamily>(std::move(minikin_fonts));
}
const std::shared_ptr<minikin::FontFamily>& FontCollection::MatchFallbackFont(
uint32_t ch,
std::string locale) {
// Check if the ch's matched font has been cached. We cache the results of
// this method as repeated matchFamilyStyleCharacter calls can become
// extremely laggy when typing a large number of complex emojis.
auto lookup = fallback_match_cache_.find(ch);
if (lookup != fallback_match_cache_.end()) {
return *lookup->second;
}
const std::shared_ptr<minikin::FontFamily>* match =
&DoMatchFallbackFont(ch, locale);
fallback_match_cache_.insert(std::make_pair(ch, match));
return *match;
}
const std::shared_ptr<minikin::FontFamily>& FontCollection::DoMatchFallbackFont(
uint32_t ch,
std::string locale) {
for (const sk_sp<SkFontMgr>& manager : GetFontManagerOrder()) {
std::vector<const char*> bcp47;
if (!locale.empty())
bcp47.push_back(locale.c_str());
sk_sp<SkTypeface> typeface(manager->matchFamilyStyleCharacter(
0, SkFontStyle(), bcp47.data(), bcp47.size(), ch));
if (!typeface)
continue;
SkString sk_family_name;
typeface->getFamilyName(&sk_family_name);
std::string family_name(sk_family_name.c_str());
fallback_fonts_for_locale_[locale].insert(family_name);
return GetFallbackFontFamily(manager, family_name);
}
return g_null_family;
}
const std::shared_ptr<minikin::FontFamily>&
FontCollection::GetFallbackFontFamily(const sk_sp<SkFontMgr>& manager,
const std::string& family_name) {
TRACE_EVENT0("flutter", "FontCollection::GetFallbackFontFamily");
auto fallback_it = fallback_fonts_.find(family_name);
if (fallback_it != fallback_fonts_.end()) {
return fallback_it->second;
}
std::shared_ptr<minikin::FontFamily> minikin_family =
CreateMinikinFontFamily(manager, family_name);
if (!minikin_family)
return g_null_family;
auto insert_it =
fallback_fonts_.insert(std::make_pair(family_name, minikin_family));
// Clear the cache to force creation of new font collections that will
// include this fallback font.
font_collections_cache_.clear();
return insert_it.first->second;
}
void FontCollection::ClearFontFamilyCache() {
font_collections_cache_.clear();
}
#if FLUTTER_ENABLE_SKSHAPER
sk_sp<skia::textlayout::FontCollection>
FontCollection::CreateSktFontCollection() {
sk_sp<skia::textlayout::FontCollection> skt_collection =
sk_make_sp<skia::textlayout::FontCollection>();
skt_collection->setDefaultFontManager(default_font_manager_,
GetDefaultFontFamily().c_str());
skt_collection->setAssetFontManager(asset_font_manager_);
skt_collection->setDynamicFontManager(dynamic_font_manager_);
skt_collection->setTestFontManager(test_font_manager_);
if (!enable_font_fallback_) {
skt_collection->disableFontFallback();
}
return skt_collection;
}
#endif // FLUTTER_ENABLE_SKSHAPER
} // namespace txt
<commit_msg>Sort the Skia typefaces in a font style set into a consistent order (#11056)<commit_after>/*
* Copyright 2017 Google 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 "font_collection.h"
#include <algorithm>
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "font_skia.h"
#include "txt/platform.h"
#include "txt/text_style.h"
namespace txt {
namespace {
const std::shared_ptr<minikin::FontFamily> g_null_family;
} // anonymous namespace
FontCollection::FamilyKey::FamilyKey(const std::vector<std::string>& families,
const std::string& loc) {
locale = loc;
std::stringstream stream;
for_each(families.begin(), families.end(),
[&stream](const std::string& str) { stream << str << ','; });
font_families = stream.str();
}
bool FontCollection::FamilyKey::operator==(
const FontCollection::FamilyKey& other) const {
return font_families == other.font_families && locale == other.locale;
}
size_t FontCollection::FamilyKey::Hasher::operator()(
const FontCollection::FamilyKey& key) const {
return std::hash<std::string>()(key.font_families) ^
std::hash<std::string>()(key.locale);
}
class TxtFallbackFontProvider
: public minikin::FontCollection::FallbackFontProvider {
public:
TxtFallbackFontProvider(std::shared_ptr<FontCollection> font_collection)
: font_collection_(font_collection) {}
virtual const std::shared_ptr<minikin::FontFamily>& matchFallbackFont(
uint32_t ch,
std::string locale) {
std::shared_ptr<FontCollection> fc = font_collection_.lock();
if (fc) {
return fc->MatchFallbackFont(ch, locale);
} else {
return g_null_family;
}
}
private:
std::weak_ptr<FontCollection> font_collection_;
};
FontCollection::FontCollection() : enable_font_fallback_(true) {}
FontCollection::~FontCollection() = default;
size_t FontCollection::GetFontManagersCount() const {
return GetFontManagerOrder().size();
}
void FontCollection::SetupDefaultFontManager() {
default_font_manager_ = GetDefaultFontManager();
}
void FontCollection::SetDefaultFontManager(sk_sp<SkFontMgr> font_manager) {
default_font_manager_ = font_manager;
}
void FontCollection::SetAssetFontManager(sk_sp<SkFontMgr> font_manager) {
asset_font_manager_ = font_manager;
}
void FontCollection::SetDynamicFontManager(sk_sp<SkFontMgr> font_manager) {
dynamic_font_manager_ = font_manager;
}
void FontCollection::SetTestFontManager(sk_sp<SkFontMgr> font_manager) {
test_font_manager_ = font_manager;
}
// Return the available font managers in the order they should be queried.
std::vector<sk_sp<SkFontMgr>> FontCollection::GetFontManagerOrder() const {
std::vector<sk_sp<SkFontMgr>> order;
if (dynamic_font_manager_)
order.push_back(dynamic_font_manager_);
if (asset_font_manager_)
order.push_back(asset_font_manager_);
if (test_font_manager_)
order.push_back(test_font_manager_);
if (default_font_manager_)
order.push_back(default_font_manager_);
return order;
}
void FontCollection::DisableFontFallback() {
enable_font_fallback_ = false;
}
std::shared_ptr<minikin::FontCollection>
FontCollection::GetMinikinFontCollectionForFamilies(
const std::vector<std::string>& font_families,
const std::string& locale) {
// Look inside the font collections cache first.
FamilyKey family_key(font_families, locale);
auto cached = font_collections_cache_.find(family_key);
if (cached != font_collections_cache_.end()) {
return cached->second;
}
std::vector<std::shared_ptr<minikin::FontFamily>> minikin_families;
// Search for all user provided font families.
for (size_t fallback_index = 0; fallback_index < font_families.size();
fallback_index++) {
std::shared_ptr<minikin::FontFamily> minikin_family =
FindFontFamilyInManagers(font_families[fallback_index]);
if (minikin_family != nullptr) {
minikin_families.push_back(minikin_family);
}
}
// Search for default font family if no user font families were found.
if (minikin_families.empty()) {
const auto default_font_family = GetDefaultFontFamily();
std::shared_ptr<minikin::FontFamily> minikin_family =
FindFontFamilyInManagers(default_font_family);
if (minikin_family != nullptr) {
minikin_families.push_back(minikin_family);
}
}
// Default font family also not found. We fail to get a FontCollection.
if (minikin_families.empty()) {
font_collections_cache_[family_key] = nullptr;
return nullptr;
}
if (enable_font_fallback_) {
for (std::string fallback_family : fallback_fonts_for_locale_[locale]) {
auto it = fallback_fonts_.find(fallback_family);
if (it != fallback_fonts_.end()) {
minikin_families.push_back(it->second);
}
}
}
// Create the minikin font collection.
auto font_collection =
std::make_shared<minikin::FontCollection>(std::move(minikin_families));
if (enable_font_fallback_) {
font_collection->set_fallback_font_provider(
std::make_unique<TxtFallbackFontProvider>(shared_from_this()));
}
// Cache the font collection for future queries.
font_collections_cache_[family_key] = font_collection;
return font_collection;
}
std::shared_ptr<minikin::FontFamily> FontCollection::FindFontFamilyInManagers(
const std::string& family_name) {
TRACE_EVENT0("flutter", "FontCollection::FindFontFamilyInManagers");
// Search for the font family in each font manager.
for (sk_sp<SkFontMgr>& manager : GetFontManagerOrder()) {
std::shared_ptr<minikin::FontFamily> minikin_family =
CreateMinikinFontFamily(manager, family_name);
if (!minikin_family)
continue;
return minikin_family;
}
return nullptr;
}
std::shared_ptr<minikin::FontFamily> FontCollection::CreateMinikinFontFamily(
const sk_sp<SkFontMgr>& manager,
const std::string& family_name) {
TRACE_EVENT1("flutter", "FontCollection::CreateMinikinFontFamily",
"family_name", family_name.c_str());
sk_sp<SkFontStyleSet> font_style_set(
manager->matchFamily(family_name.c_str()));
if (font_style_set == nullptr || font_style_set->count() == 0) {
return nullptr;
}
std::vector<sk_sp<SkTypeface>> skia_typefaces;
for (int i = 0; i < font_style_set->count(); ++i) {
TRACE_EVENT0("flutter", "CreateSkiaTypeface");
sk_sp<SkTypeface> skia_typeface(
sk_sp<SkTypeface>(font_style_set->createTypeface(i)));
if (skia_typeface != nullptr) {
skia_typefaces.emplace_back(std::move(skia_typeface));
}
}
std::sort(skia_typefaces.begin(), skia_typefaces.end(),
[](const sk_sp<SkTypeface>& a, const sk_sp<SkTypeface>& b) {
SkFontStyle a_style = a->fontStyle();
SkFontStyle b_style = b->fontStyle();
return (a_style.weight() != b_style.weight())
? a_style.weight() < b_style.weight()
: a_style.slant() < b_style.slant();
});
std::vector<minikin::Font> minikin_fonts;
for (const sk_sp<SkTypeface>& skia_typeface : skia_typefaces) {
// Create the minikin font from the skia typeface.
// Divide by 100 because the weights are given as "100", "200", etc.
minikin_fonts.emplace_back(
std::make_shared<FontSkia>(skia_typeface),
minikin::FontStyle{skia_typeface->fontStyle().weight() / 100,
skia_typeface->isItalic()});
}
return std::make_shared<minikin::FontFamily>(std::move(minikin_fonts));
}
const std::shared_ptr<minikin::FontFamily>& FontCollection::MatchFallbackFont(
uint32_t ch,
std::string locale) {
// Check if the ch's matched font has been cached. We cache the results of
// this method as repeated matchFamilyStyleCharacter calls can become
// extremely laggy when typing a large number of complex emojis.
auto lookup = fallback_match_cache_.find(ch);
if (lookup != fallback_match_cache_.end()) {
return *lookup->second;
}
const std::shared_ptr<minikin::FontFamily>* match =
&DoMatchFallbackFont(ch, locale);
fallback_match_cache_.insert(std::make_pair(ch, match));
return *match;
}
const std::shared_ptr<minikin::FontFamily>& FontCollection::DoMatchFallbackFont(
uint32_t ch,
std::string locale) {
for (const sk_sp<SkFontMgr>& manager : GetFontManagerOrder()) {
std::vector<const char*> bcp47;
if (!locale.empty())
bcp47.push_back(locale.c_str());
sk_sp<SkTypeface> typeface(manager->matchFamilyStyleCharacter(
0, SkFontStyle(), bcp47.data(), bcp47.size(), ch));
if (!typeface)
continue;
SkString sk_family_name;
typeface->getFamilyName(&sk_family_name);
std::string family_name(sk_family_name.c_str());
fallback_fonts_for_locale_[locale].insert(family_name);
return GetFallbackFontFamily(manager, family_name);
}
return g_null_family;
}
const std::shared_ptr<minikin::FontFamily>&
FontCollection::GetFallbackFontFamily(const sk_sp<SkFontMgr>& manager,
const std::string& family_name) {
TRACE_EVENT0("flutter", "FontCollection::GetFallbackFontFamily");
auto fallback_it = fallback_fonts_.find(family_name);
if (fallback_it != fallback_fonts_.end()) {
return fallback_it->second;
}
std::shared_ptr<minikin::FontFamily> minikin_family =
CreateMinikinFontFamily(manager, family_name);
if (!minikin_family)
return g_null_family;
auto insert_it =
fallback_fonts_.insert(std::make_pair(family_name, minikin_family));
// Clear the cache to force creation of new font collections that will
// include this fallback font.
font_collections_cache_.clear();
return insert_it.first->second;
}
void FontCollection::ClearFontFamilyCache() {
font_collections_cache_.clear();
}
#if FLUTTER_ENABLE_SKSHAPER
sk_sp<skia::textlayout::FontCollection>
FontCollection::CreateSktFontCollection() {
sk_sp<skia::textlayout::FontCollection> skt_collection =
sk_make_sp<skia::textlayout::FontCollection>();
skt_collection->setDefaultFontManager(default_font_manager_,
GetDefaultFontFamily().c_str());
skt_collection->setAssetFontManager(asset_font_manager_);
skt_collection->setDynamicFontManager(dynamic_font_manager_);
skt_collection->setTestFontManager(test_font_manager_);
if (!enable_font_fallback_) {
skt_collection->disableFontFallback();
}
return skt_collection;
}
#endif // FLUTTER_ENABLE_SKSHAPER
} // namespace txt
<|endoftext|> |
<commit_before>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GLTestContext_angle.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "gl/GrGLDefines.h"
#include "gl/GrGLUtil.h"
#include "gl/GrGLInterface.h"
#include "gl/GrGLAssembleInterface.h"
#include "../ports/SkOSLibrary.h"
#include <EGL/egl.h>
#define EGL_PLATFORM_ANGLE_ANGLE 0x3202
#define EGL_PLATFORM_ANGLE_TYPE_ANGLE 0x3203
#define EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE 0x3207
#define EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE 0x3208
#define EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE 0x320D
using sk_gpu_test::ANGLEBackend;
using sk_gpu_test::ANGLEContextVersion;
namespace {
struct Libs {
void* fGLLib;
void* fEGLLib;
};
static GrGLFuncPtr angle_get_gl_proc(void* ctx, const char name[]) {
const Libs* libs = reinterpret_cast<const Libs*>(ctx);
GrGLFuncPtr proc = (GrGLFuncPtr) GetProcedureAddress(libs->fGLLib, name);
if (proc) {
return proc;
}
proc = (GrGLFuncPtr) GetProcedureAddress(libs->fEGLLib, name);
if (proc) {
return proc;
}
return eglGetProcAddress(name);
}
void* get_angle_egl_display(void* nativeDisplay, ANGLEBackend type) {
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT;
eglGetPlatformDisplayEXT =
(PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
// We expect ANGLE to support this extension
if (!eglGetPlatformDisplayEXT) {
return EGL_NO_DISPLAY;
}
EGLint typeNum = 0;
switch (type) {
case ANGLEBackend::kD3D9:
typeNum = EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE;
break;
case ANGLEBackend::kD3D11:
typeNum = EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE;
break;
case ANGLEBackend::kOpenGL:
typeNum = EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE;
break;
}
const EGLint attribs[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, typeNum, EGL_NONE };
return eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, nativeDisplay, attribs);
}
class ANGLEGLContext : public sk_gpu_test::GLTestContext {
public:
ANGLEGLContext(ANGLEBackend, ANGLEContextVersion, ANGLEGLContext* shareContext);
~ANGLEGLContext() override;
GrEGLImage texture2DToEGLImage(GrGLuint texID) const override;
void destroyEGLImage(GrEGLImage) const override;
GrGLuint eglImageToExternalTexture(GrEGLImage) const override;
std::unique_ptr<sk_gpu_test::GLTestContext> makeNew() const override;
private:
void destroyGLContext();
void onPlatformMakeCurrent() const override;
void onPlatformSwapBuffers() const override;
GrGLFuncPtr onPlatformGetProcAddress(const char* name) const override;
void* fContext;
void* fDisplay;
void* fSurface;
ANGLEBackend fType;
ANGLEContextVersion fVersion;
};
ANGLEGLContext::ANGLEGLContext(ANGLEBackend type, ANGLEContextVersion version,
ANGLEGLContext* shareContext)
: fContext(EGL_NO_CONTEXT)
, fDisplay(EGL_NO_DISPLAY)
, fSurface(EGL_NO_SURFACE)
, fType(type)
, fVersion(version) {
EGLint numConfigs;
static const EGLint configAttribs[] = {
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_NONE
};
fDisplay = get_angle_egl_display(EGL_DEFAULT_DISPLAY, type);
if (EGL_NO_DISPLAY == fDisplay) {
SkDebugf("Could not create EGL display!");
return;
}
EGLint majorVersion;
EGLint minorVersion;
eglInitialize(fDisplay, &majorVersion, &minorVersion);
EGLConfig surfaceConfig;
eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs);
int versionNum = ANGLEContextVersion::kES2 == version ? 2 : 3;
const EGLint contextAttribs[] = {
EGL_CONTEXT_CLIENT_VERSION, versionNum,
EGL_NONE
};
EGLContext eglShareContext = shareContext ? shareContext->fContext : nullptr;
fContext = eglCreateContext(fDisplay, surfaceConfig, eglShareContext, contextAttribs);
static const EGLint surfaceAttribs[] = {
EGL_WIDTH, 1,
EGL_HEIGHT, 1,
EGL_NONE
};
fSurface = eglCreatePbufferSurface(fDisplay, surfaceConfig, surfaceAttribs);
eglMakeCurrent(fDisplay, fSurface, fSurface, fContext);
sk_sp<const GrGLInterface> gl(sk_gpu_test::CreateANGLEGLInterface());
if (nullptr == gl.get()) {
SkDebugf("Could not create ANGLE GL interface!\n");
this->destroyGLContext();
return;
}
if (!gl->validate()) {
SkDebugf("Could not validate ANGLE GL interface!\n");
this->destroyGLContext();
return;
}
#ifdef SK_DEBUG
// Verify that the interface we requested was actuall returned to us
const GrGLubyte* rendererUByte;
GR_GL_CALL_RET(gl.get(), rendererUByte, GetString(GR_GL_RENDERER));
const char* renderer = reinterpret_cast<const char*>(rendererUByte);
switch (type) {
case ANGLEBackend::kD3D9:
SkASSERT(strstr(renderer, "Direct3D9"));
break;
case ANGLEBackend::kD3D11:
SkASSERT(strstr(renderer, "Direct3D11"));
break;
case ANGLEBackend::kOpenGL:
SkASSERT(strstr(renderer, "OpenGL"));
break;
}
#endif
this->init(gl.release());
}
ANGLEGLContext::~ANGLEGLContext() {
this->teardown();
this->destroyGLContext();
}
GrEGLImage ANGLEGLContext::texture2DToEGLImage(GrGLuint texID) const {
if (!this->gl()->hasExtension("EGL_KHR_gl_texture_2D_image")) {
return GR_EGL_NO_IMAGE;
}
GrEGLImage img;
GrEGLint attribs[] = { GR_EGL_GL_TEXTURE_LEVEL, 0,
GR_EGL_IMAGE_PRESERVED, GR_EGL_TRUE,
GR_EGL_NONE };
// 64 bit cast is to shut Visual C++ up about casting 32 bit value to a pointer.
GrEGLClientBuffer clientBuffer = reinterpret_cast<GrEGLClientBuffer>((uint64_t)texID);
GR_GL_CALL_RET(this->gl(), img,
EGLCreateImage(fDisplay, fContext, GR_EGL_GL_TEXTURE_2D, clientBuffer,
attribs));
return img;
}
void ANGLEGLContext::destroyEGLImage(GrEGLImage image) const {
GR_GL_CALL(this->gl(), EGLDestroyImage(fDisplay, image));
}
GrGLuint ANGLEGLContext::eglImageToExternalTexture(GrEGLImage image) const {
GrGLClearErr(this->gl());
if (!this->gl()->hasExtension("GL_OES_EGL_image_external")) {
return 0;
}
typedef GrGLvoid (EGLAPIENTRY *EGLImageTargetTexture2DProc)(GrGLenum, GrGLeglImage);
EGLImageTargetTexture2DProc glEGLImageTargetTexture2D =
(EGLImageTargetTexture2DProc)eglGetProcAddress("glEGLImageTargetTexture2DOES");
if (!glEGLImageTargetTexture2D) {
return 0;
}
GrGLuint texID;
GR_GL_CALL(this->gl(), GenTextures(1, &texID));
if (!texID) {
return 0;
}
GR_GL_CALL(this->gl(), BindTexture(GR_GL_TEXTURE_EXTERNAL, texID));
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
glEGLImageTargetTexture2D(GR_GL_TEXTURE_EXTERNAL, image);
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
return texID;
}
std::unique_ptr<sk_gpu_test::GLTestContext> ANGLEGLContext::makeNew() const {
std::unique_ptr<sk_gpu_test::GLTestContext> ctx =
sk_gpu_test::MakeANGLETestContext(fType, fVersion);
if (ctx) {
ctx->makeCurrent();
}
return ctx;
}
void ANGLEGLContext::destroyGLContext() {
if (fDisplay) {
eglMakeCurrent(fDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (fContext) {
eglDestroyContext(fDisplay, fContext);
fContext = EGL_NO_CONTEXT;
}
if (fSurface) {
eglDestroySurface(fDisplay, fSurface);
fSurface = EGL_NO_SURFACE;
}
if (EGL_NO_DISPLAY != fDisplay) {
eglTerminate(fDisplay);
fDisplay = EGL_NO_DISPLAY;
}
}
}
void ANGLEGLContext::onPlatformMakeCurrent() const {
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("Could not set the context.\n");
}
}
void ANGLEGLContext::onPlatformSwapBuffers() const {
if (!eglSwapBuffers(fDisplay, fSurface)) {
SkDebugf("Could not complete eglSwapBuffers.\n");
}
}
GrGLFuncPtr ANGLEGLContext::onPlatformGetProcAddress(const char* name) const {
return eglGetProcAddress(name);
}
} // anonymous namespace
namespace sk_gpu_test {
const GrGLInterface* CreateANGLEGLInterface() {
static Libs gLibs = { nullptr, nullptr };
if (nullptr == gLibs.fGLLib) {
// We load the ANGLE library and never let it go
#if defined _WIN32
gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dll");
gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dll");
#elif defined SK_BUILD_FOR_MAC
gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dylib");
gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dylib");
#else
gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.so");
gLibs.fEGLLib = DynamicLoadLibrary("libEGL.so");
#endif
}
if (nullptr == gLibs.fGLLib || nullptr == gLibs.fEGLLib) {
// We can't setup the interface correctly w/o the so
return nullptr;
}
return GrGLAssembleGLESInterface(&gLibs, angle_get_gl_proc);
}
std::unique_ptr<GLTestContext> MakeANGLETestContext(ANGLEBackend type, ANGLEContextVersion version,
GLTestContext* shareContext){
ANGLEGLContext* angleShareContext = reinterpret_cast<ANGLEGLContext*>(shareContext);
std::unique_ptr<GLTestContext> ctx(new ANGLEGLContext(type, version, angleShareContext));
if (!ctx->isValid()) {
return nullptr;
}
return ctx;
}
} // namespace sk_gpu_test
<commit_msg>Revert "Destroy ANGLE displays in destroyGLContext"<commit_after>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GLTestContext_angle.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "gl/GrGLDefines.h"
#include "gl/GrGLUtil.h"
#include "gl/GrGLInterface.h"
#include "gl/GrGLAssembleInterface.h"
#include "../ports/SkOSLibrary.h"
#include <EGL/egl.h>
#define EGL_PLATFORM_ANGLE_ANGLE 0x3202
#define EGL_PLATFORM_ANGLE_TYPE_ANGLE 0x3203
#define EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE 0x3207
#define EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE 0x3208
#define EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE 0x320D
using sk_gpu_test::ANGLEBackend;
using sk_gpu_test::ANGLEContextVersion;
namespace {
struct Libs {
void* fGLLib;
void* fEGLLib;
};
static GrGLFuncPtr angle_get_gl_proc(void* ctx, const char name[]) {
const Libs* libs = reinterpret_cast<const Libs*>(ctx);
GrGLFuncPtr proc = (GrGLFuncPtr) GetProcedureAddress(libs->fGLLib, name);
if (proc) {
return proc;
}
proc = (GrGLFuncPtr) GetProcedureAddress(libs->fEGLLib, name);
if (proc) {
return proc;
}
return eglGetProcAddress(name);
}
void* get_angle_egl_display(void* nativeDisplay, ANGLEBackend type) {
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT;
eglGetPlatformDisplayEXT =
(PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
// We expect ANGLE to support this extension
if (!eglGetPlatformDisplayEXT) {
return EGL_NO_DISPLAY;
}
EGLint typeNum = 0;
switch (type) {
case ANGLEBackend::kD3D9:
typeNum = EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE;
break;
case ANGLEBackend::kD3D11:
typeNum = EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE;
break;
case ANGLEBackend::kOpenGL:
typeNum = EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE;
break;
}
const EGLint attribs[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, typeNum, EGL_NONE };
return eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, nativeDisplay, attribs);
}
class ANGLEGLContext : public sk_gpu_test::GLTestContext {
public:
ANGLEGLContext(ANGLEBackend, ANGLEContextVersion, ANGLEGLContext* shareContext);
~ANGLEGLContext() override;
GrEGLImage texture2DToEGLImage(GrGLuint texID) const override;
void destroyEGLImage(GrEGLImage) const override;
GrGLuint eglImageToExternalTexture(GrEGLImage) const override;
std::unique_ptr<sk_gpu_test::GLTestContext> makeNew() const override;
private:
void destroyGLContext();
void onPlatformMakeCurrent() const override;
void onPlatformSwapBuffers() const override;
GrGLFuncPtr onPlatformGetProcAddress(const char* name) const override;
void* fContext;
void* fDisplay;
void* fSurface;
ANGLEBackend fType;
ANGLEContextVersion fVersion;
};
ANGLEGLContext::ANGLEGLContext(ANGLEBackend type, ANGLEContextVersion version,
ANGLEGLContext* shareContext)
: fContext(EGL_NO_CONTEXT)
, fDisplay(EGL_NO_DISPLAY)
, fSurface(EGL_NO_SURFACE)
, fType(type)
, fVersion(version) {
EGLint numConfigs;
static const EGLint configAttribs[] = {
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_NONE
};
fDisplay = get_angle_egl_display(EGL_DEFAULT_DISPLAY, type);
if (EGL_NO_DISPLAY == fDisplay) {
SkDebugf("Could not create EGL display!");
return;
}
EGLint majorVersion;
EGLint minorVersion;
eglInitialize(fDisplay, &majorVersion, &minorVersion);
EGLConfig surfaceConfig;
eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs);
int versionNum = ANGLEContextVersion::kES2 == version ? 2 : 3;
const EGLint contextAttribs[] = {
EGL_CONTEXT_CLIENT_VERSION, versionNum,
EGL_NONE
};
EGLContext eglShareContext = shareContext ? shareContext->fContext : nullptr;
fContext = eglCreateContext(fDisplay, surfaceConfig, eglShareContext, contextAttribs);
static const EGLint surfaceAttribs[] = {
EGL_WIDTH, 1,
EGL_HEIGHT, 1,
EGL_NONE
};
fSurface = eglCreatePbufferSurface(fDisplay, surfaceConfig, surfaceAttribs);
eglMakeCurrent(fDisplay, fSurface, fSurface, fContext);
sk_sp<const GrGLInterface> gl(sk_gpu_test::CreateANGLEGLInterface());
if (nullptr == gl.get()) {
SkDebugf("Could not create ANGLE GL interface!\n");
this->destroyGLContext();
return;
}
if (!gl->validate()) {
SkDebugf("Could not validate ANGLE GL interface!\n");
this->destroyGLContext();
return;
}
this->init(gl.release());
}
ANGLEGLContext::~ANGLEGLContext() {
this->teardown();
this->destroyGLContext();
}
GrEGLImage ANGLEGLContext::texture2DToEGLImage(GrGLuint texID) const {
if (!this->gl()->hasExtension("EGL_KHR_gl_texture_2D_image")) {
return GR_EGL_NO_IMAGE;
}
GrEGLImage img;
GrEGLint attribs[] = { GR_EGL_GL_TEXTURE_LEVEL, 0,
GR_EGL_IMAGE_PRESERVED, GR_EGL_TRUE,
GR_EGL_NONE };
// 64 bit cast is to shut Visual C++ up about casting 32 bit value to a pointer.
GrEGLClientBuffer clientBuffer = reinterpret_cast<GrEGLClientBuffer>((uint64_t)texID);
GR_GL_CALL_RET(this->gl(), img,
EGLCreateImage(fDisplay, fContext, GR_EGL_GL_TEXTURE_2D, clientBuffer,
attribs));
return img;
}
void ANGLEGLContext::destroyEGLImage(GrEGLImage image) const {
GR_GL_CALL(this->gl(), EGLDestroyImage(fDisplay, image));
}
GrGLuint ANGLEGLContext::eglImageToExternalTexture(GrEGLImage image) const {
GrGLClearErr(this->gl());
if (!this->gl()->hasExtension("GL_OES_EGL_image_external")) {
return 0;
}
typedef GrGLvoid (EGLAPIENTRY *EGLImageTargetTexture2DProc)(GrGLenum, GrGLeglImage);
EGLImageTargetTexture2DProc glEGLImageTargetTexture2D =
(EGLImageTargetTexture2DProc)eglGetProcAddress("glEGLImageTargetTexture2DOES");
if (!glEGLImageTargetTexture2D) {
return 0;
}
GrGLuint texID;
GR_GL_CALL(this->gl(), GenTextures(1, &texID));
if (!texID) {
return 0;
}
GR_GL_CALL(this->gl(), BindTexture(GR_GL_TEXTURE_EXTERNAL, texID));
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
glEGLImageTargetTexture2D(GR_GL_TEXTURE_EXTERNAL, image);
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
return texID;
}
std::unique_ptr<sk_gpu_test::GLTestContext> ANGLEGLContext::makeNew() const {
std::unique_ptr<sk_gpu_test::GLTestContext> ctx =
sk_gpu_test::MakeANGLETestContext(fType, fVersion);
if (ctx) {
ctx->makeCurrent();
}
return ctx;
}
void ANGLEGLContext::destroyGLContext() {
if (fDisplay) {
eglMakeCurrent(fDisplay, 0, 0, 0);
if (fContext) {
eglDestroyContext(fDisplay, fContext);
fContext = EGL_NO_CONTEXT;
}
if (fSurface) {
eglDestroySurface(fDisplay, fSurface);
fSurface = EGL_NO_SURFACE;
}
//TODO should we close the display?
fDisplay = EGL_NO_DISPLAY;
}
}
void ANGLEGLContext::onPlatformMakeCurrent() const {
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("Could not set the context.\n");
}
}
void ANGLEGLContext::onPlatformSwapBuffers() const {
if (!eglSwapBuffers(fDisplay, fSurface)) {
SkDebugf("Could not complete eglSwapBuffers.\n");
}
}
GrGLFuncPtr ANGLEGLContext::onPlatformGetProcAddress(const char* name) const {
return eglGetProcAddress(name);
}
} // anonymous namespace
namespace sk_gpu_test {
const GrGLInterface* CreateANGLEGLInterface() {
static Libs gLibs = { nullptr, nullptr };
if (nullptr == gLibs.fGLLib) {
// We load the ANGLE library and never let it go
#if defined _WIN32
gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dll");
gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dll");
#elif defined SK_BUILD_FOR_MAC
gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dylib");
gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dylib");
#else
gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.so");
gLibs.fEGLLib = DynamicLoadLibrary("libEGL.so");
#endif
}
if (nullptr == gLibs.fGLLib || nullptr == gLibs.fEGLLib) {
// We can't setup the interface correctly w/o the so
return nullptr;
}
return GrGLAssembleGLESInterface(&gLibs, angle_get_gl_proc);
}
std::unique_ptr<GLTestContext> MakeANGLETestContext(ANGLEBackend type, ANGLEContextVersion version,
GLTestContext* shareContext){
ANGLEGLContext* angleShareContext = reinterpret_cast<ANGLEGLContext*>(shareContext);
std::unique_ptr<GLTestContext> ctx(new ANGLEGLContext(type, version, angleShareContext));
if (!ctx->isValid()) {
return nullptr;
}
return ctx;
}
} // namespace sk_gpu_test
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// System Includes
#include <algorithm>
#include <iostream>
// Local Includes
#include "libmesh_common.h"
#include "parallel.h"
#include "parallel_hilbert.h"
#include "parallel_sort.h"
#include "parallel_bin_sorter.h"
#ifdef LIBMESH_HAVE_LIBHILBERT
# include "hilbert.h"
#endif
namespace libMesh
{
namespace Parallel {
// The Constructor sorts the local data using
// std::sort(). Therefore, the construction of
// a Parallel::Sort object takes O(nlogn) time,
// where n is the length of _data.
template <typename KeyType>
Sort<KeyType>::Sort(std::vector<KeyType>& d,
const unsigned int n_procs,
const unsigned int proc_id) :
_n_procs(n_procs),
_proc_id(proc_id),
_bin_is_sorted(false),
_data(d)
{
std::sort(_data.begin(), _data.end());
// Allocate storage
_local_bin_sizes.resize(_n_procs);
}
template <typename KeyType>
void Sort<KeyType>::sort()
{
// Find the global data size. The sorting
// algorithms assume they have a range to
// work with, so catch the degenerate cases here
unsigned int global_data_size = _data.size();
Parallel::sum (global_data_size);
if (global_data_size < 2)
{
// the entire global range is either empty
// or contains only one element
_my_bin = _data;
Parallel::allgather (static_cast<unsigned int>(_my_bin.size()),
_local_bin_sizes);
}
else
{
this->binsort();
this->communicate_bins();
this->sort_local_bin();
}
// Set sorted flag to true
_bin_is_sorted = true;
}
template <typename KeyType>
void Sort<KeyType>::binsort()
{
// Find the global min and max from all the
// processors.
std::vector<KeyType> global_min_max(2);
// Insert the local min and max for this processor
global_min_max[0] = -_data.front();
global_min_max[1] = _data.back();
// Communicate to determine the global
// min and max for all processors.
Parallel::max(global_min_max);
// Multiply the min by -1 to obtain the true min
global_min_max[0] *= -1;
// Bin-Sort based on the global min and max
Parallel::BinSorter<KeyType> bs(_data);
bs.binsort(_n_procs, global_min_max[1], global_min_max[0]);
// Now save the local bin sizes in a vector so
// we don't have to keep around the BinSorter.
for (unsigned int i=0; i<_n_procs; ++i)
_local_bin_sizes[i] = bs.sizeof_bin(i);
}
#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
// Full specialization for HilbertIndices, there is a fair amount of
// code duplication here that could potentially be consolidated with the
// above method
template <>
void Sort<Hilbert::HilbertIndices>::binsort()
{
// Find the global min and max from all the
// processors. Do this using MPI_Allreduce.
Hilbert::HilbertIndices
local_min, local_max,
global_min, global_max;
if (_data.empty())
{
local_min.rack0 = local_min.rack1 = local_min.rack2 = static_cast<Hilbert::inttype>(-1);
local_max.rack0 = local_max.rack1 = local_max.rack2 = 0;
}
else
{
local_min = _data.front();
local_max = _data.back();
}
MPI_Op hilbert_max, hilbert_min;
MPI_Op_create ((MPI_User_function*)__hilbert_max_op, true, &hilbert_max);
MPI_Op_create ((MPI_User_function*)__hilbert_min_op, true, &hilbert_min);
// Communicate to determine the global
// min and max for all processors.
MPI_Allreduce(&local_min,
&global_min,
1,
Parallel::StandardType<Hilbert::HilbertIndices>(),
hilbert_min,
libMesh::COMM_WORLD);
MPI_Allreduce(&local_max,
&global_max,
1,
Parallel::StandardType<Hilbert::HilbertIndices>(),
hilbert_max,
libMesh::COMM_WORLD);
MPI_Op_free (&hilbert_max);
MPI_Op_free (&hilbert_min);
// Bin-Sort based on the global min and max
Parallel::BinSorter<Hilbert::HilbertIndices> bs(_data);
bs.binsort(_n_procs, global_max, global_min);
// Now save the local bin sizes in a vector so
// we don't have to keep around the BinSorter.
for (unsigned int i=0; i<_n_procs; ++i)
_local_bin_sizes[i] = bs.sizeof_bin(i);
}
#endif // #ifdef LIBMESH_HAVE_LIBHILBERT
template <typename KeyType>
void Sort<KeyType>::communicate_bins()
{
#ifdef LIBMESH_HAVE_MPI
// Create storage for the global bin sizes. This
// is the number of keys which will be held in
// each bin over all processors.
std::vector<unsigned int> global_bin_sizes = _local_bin_sizes;
// Sum to find the total number of entries in each bin.
Parallel::sum(global_bin_sizes);
// Create a vector to temporarily hold the results of MPI_Gatherv
// calls. The vector dest may be saved away to _my_bin depending on which
// processor is being MPI_Gatherv'd.
std::vector<KeyType> dest;
unsigned int local_offset = 0;
for (unsigned int i=0; i<_n_procs; ++i)
{
// Vector to receive the total bin size for each
// processor. Processor i's bin size will be
// held in proc_bin_size[i]
std::vector<unsigned int> proc_bin_size;
// Find the number of contributions coming from each
// processor for this bin. Note: allgather combines
// the MPI_Gather and MPI_Bcast operations into one.
Parallel::allgather(_local_bin_sizes[i], proc_bin_size);
// Compute the offsets into my_bin for each processor's
// portion of the bin. These are basically partial sums
// of the proc_bin_size vector.
std::vector<unsigned int> displacements(_n_procs);
for (unsigned int j=1; j<_n_procs; ++j)
displacements[j] = proc_bin_size[j-1] + displacements[j-1];
// Resize the destination buffer
dest.resize (global_bin_sizes[i]);
MPI_Gatherv((_data.size() > local_offset) ?
&_data[local_offset] :
NULL, // Points to the beginning of the bin to be sent
_local_bin_sizes[i], // How much data is in the bin being sent.
Parallel::StandardType<KeyType>(), // The data type we are sorting
(dest.empty()) ?
NULL :
&dest[0], // Enough storage to hold all bin contributions
(int*) &proc_bin_size[0], // How much is to be received from each processor
(int*) &displacements[0], // Offsets into the receive buffer
Parallel::StandardType<KeyType>(), // The data type we are sorting
i, // The root process (we do this once for each proc)
libMesh::COMM_WORLD);
// Copy the destination buffer if it
// corresponds to the bin for this processor
if (i == _proc_id)
_my_bin = dest;
// Increment the local offset counter
local_offset += _local_bin_sizes[i];
}
#endif // LIBMESH_HAVE_MPI
}
#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
// Full specialization for HilbertIndices, there is a fair amount of
// code duplication here that could potentially be consolidated with the
// above method
template <>
void Sort<Hilbert::HilbertIndices>::communicate_bins()
{
// Create storage for the global bin sizes. This
// is the number of keys which will be held in
// each bin over all processors.
std::vector<unsigned int> global_bin_sizes(_n_procs);
libmesh_assert (_local_bin_sizes.size() == global_bin_sizes.size());
// Sum to find the total number of entries in each bin.
// This is stored in global_bin_sizes. Note, we
// explicitly know that we are communicating MPI_UNSIGNED's here.
MPI_Allreduce(&_local_bin_sizes[0],
&global_bin_sizes[0],
_n_procs,
MPI_UNSIGNED,
MPI_SUM,
libMesh::COMM_WORLD);
// Create a vector to temporarily hold the results of MPI_Gatherv
// calls. The vector dest may be saved away to _my_bin depending on which
// processor is being MPI_Gatherv'd.
std::vector<Hilbert::HilbertIndices> sendbuf, dest;
unsigned int local_offset = 0;
for (unsigned int i=0; i<_n_procs; ++i)
{
// Vector to receive the total bin size for each
// processor. Processor i's bin size will be
// held in proc_bin_size[i]
std::vector<unsigned int> proc_bin_size(_n_procs);
// Find the number of contributions coming from each
// processor for this bin. Note: Allgather combines
// the MPI_Gather and MPI_Bcast operations into one.
// Note: Here again we know that we are communicating
// MPI_UNSIGNED's so there is no need to check the MPI_traits.
MPI_Allgather(&_local_bin_sizes[i], // Source: # of entries on this proc in bin i
1, // Number of items to gather
MPI_UNSIGNED,
&proc_bin_size[0], // Destination: Total # of entries in bin i
1,
MPI_UNSIGNED,
libMesh::COMM_WORLD);
// Compute the offsets into my_bin for each processor's
// portion of the bin. These are basically partial sums
// of the proc_bin_size vector.
std::vector<unsigned int> displacements(_n_procs);
for (unsigned int j=1; j<_n_procs; ++j)
displacements[j] = proc_bin_size[j-1] + displacements[j-1];
// Resize the destination buffer
dest.resize (global_bin_sizes[i]);
MPI_Gatherv((_data.size() > local_offset) ?
&_data[local_offset] :
NULL, // Points to the beginning of the bin to be sent
_local_bin_sizes[i], // How much data is in the bin being sent.
Parallel::StandardType<Hilbert::HilbertIndices>(), // The data type we are sorting
(dest.empty()) ?
NULL :
&dest[0], // Enough storage to hold all bin contributions
(int*) &proc_bin_size[0], // How much is to be received from each processor
(int*) &displacements[0], // Offsets into the receive buffer
Parallel::StandardType<Hilbert::HilbertIndices>(), // The data type we are sorting
i, // The root process (we do this once for each proc)
libMesh::COMM_WORLD);
// Copy the destination buffer if it
// corresponds to the bin for this processor
if (i == _proc_id)
_my_bin = dest;
// Increment the local offset counter
local_offset += _local_bin_sizes[i];
}
}
#endif // #if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
template <typename KeyType>
void Sort<KeyType>::sort_local_bin()
{
std::sort(_my_bin.begin(), _my_bin.end());
}
template <typename KeyType>
const std::vector<KeyType>& Sort<KeyType>::bin()
{
if (!_bin_is_sorted)
{
libMesh::out << "Warning! Bin is not yet sorted!" << std::endl;
}
return _my_bin;
}
}
// Explicitly instantiate for int, double
template class Parallel::Sort<int>;
template class Parallel::Sort<double>;
#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
template class Parallel::Sort<Hilbert::HilbertIndices>;
#endif
} // namespace libMesh
<commit_msg>Optimized parallel sort in n_processors() == 1 case<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// System Includes
#include <algorithm>
#include <iostream>
// Local Includes
#include "libmesh_common.h"
#include "parallel.h"
#include "parallel_hilbert.h"
#include "parallel_sort.h"
#include "parallel_bin_sorter.h"
#ifdef LIBMESH_HAVE_LIBHILBERT
# include "hilbert.h"
#endif
namespace libMesh
{
namespace Parallel {
// The Constructor sorts the local data using
// std::sort(). Therefore, the construction of
// a Parallel::Sort object takes O(nlogn) time,
// where n is the length of _data.
template <typename KeyType>
Sort<KeyType>::Sort(std::vector<KeyType>& d,
const unsigned int n_procs,
const unsigned int proc_id) :
_n_procs(n_procs),
_proc_id(proc_id),
_bin_is_sorted(false),
_data(d)
{
std::sort(_data.begin(), _data.end());
// Allocate storage
_local_bin_sizes.resize(_n_procs);
}
template <typename KeyType>
void Sort<KeyType>::sort()
{
// Find the global data size. The sorting
// algorithms assume they have a range to
// work with, so catch the degenerate cases here
unsigned int global_data_size = _data.size();
Parallel::sum (global_data_size);
if (global_data_size < 2)
{
// the entire global range is either empty
// or contains only one element
_my_bin = _data;
Parallel::allgather (static_cast<unsigned int>(_my_bin.size()),
_local_bin_sizes);
}
else
{
if (libMesh::n_processors() > 1)
{
this->binsort();
this->communicate_bins();
}
else
_my_bin = _data;
this->sort_local_bin();
}
// Set sorted flag to true
_bin_is_sorted = true;
}
template <typename KeyType>
void Sort<KeyType>::binsort()
{
// Find the global min and max from all the
// processors.
std::vector<KeyType> global_min_max(2);
// Insert the local min and max for this processor
global_min_max[0] = -_data.front();
global_min_max[1] = _data.back();
// Communicate to determine the global
// min and max for all processors.
Parallel::max(global_min_max);
// Multiply the min by -1 to obtain the true min
global_min_max[0] *= -1;
// Bin-Sort based on the global min and max
Parallel::BinSorter<KeyType> bs(_data);
bs.binsort(_n_procs, global_min_max[1], global_min_max[0]);
// Now save the local bin sizes in a vector so
// we don't have to keep around the BinSorter.
for (unsigned int i=0; i<_n_procs; ++i)
_local_bin_sizes[i] = bs.sizeof_bin(i);
}
#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
// Full specialization for HilbertIndices, there is a fair amount of
// code duplication here that could potentially be consolidated with the
// above method
template <>
void Sort<Hilbert::HilbertIndices>::binsort()
{
// Find the global min and max from all the
// processors. Do this using MPI_Allreduce.
Hilbert::HilbertIndices
local_min, local_max,
global_min, global_max;
if (_data.empty())
{
local_min.rack0 = local_min.rack1 = local_min.rack2 = static_cast<Hilbert::inttype>(-1);
local_max.rack0 = local_max.rack1 = local_max.rack2 = 0;
}
else
{
local_min = _data.front();
local_max = _data.back();
}
MPI_Op hilbert_max, hilbert_min;
MPI_Op_create ((MPI_User_function*)__hilbert_max_op, true, &hilbert_max);
MPI_Op_create ((MPI_User_function*)__hilbert_min_op, true, &hilbert_min);
// Communicate to determine the global
// min and max for all processors.
MPI_Allreduce(&local_min,
&global_min,
1,
Parallel::StandardType<Hilbert::HilbertIndices>(),
hilbert_min,
libMesh::COMM_WORLD);
MPI_Allreduce(&local_max,
&global_max,
1,
Parallel::StandardType<Hilbert::HilbertIndices>(),
hilbert_max,
libMesh::COMM_WORLD);
MPI_Op_free (&hilbert_max);
MPI_Op_free (&hilbert_min);
// Bin-Sort based on the global min and max
Parallel::BinSorter<Hilbert::HilbertIndices> bs(_data);
bs.binsort(_n_procs, global_max, global_min);
// Now save the local bin sizes in a vector so
// we don't have to keep around the BinSorter.
for (unsigned int i=0; i<_n_procs; ++i)
_local_bin_sizes[i] = bs.sizeof_bin(i);
}
#endif // #ifdef LIBMESH_HAVE_LIBHILBERT
template <typename KeyType>
void Sort<KeyType>::communicate_bins()
{
#ifdef LIBMESH_HAVE_MPI
// Create storage for the global bin sizes. This
// is the number of keys which will be held in
// each bin over all processors.
std::vector<unsigned int> global_bin_sizes = _local_bin_sizes;
// Sum to find the total number of entries in each bin.
Parallel::sum(global_bin_sizes);
// Create a vector to temporarily hold the results of MPI_Gatherv
// calls. The vector dest may be saved away to _my_bin depending on which
// processor is being MPI_Gatherv'd.
std::vector<KeyType> dest;
unsigned int local_offset = 0;
for (unsigned int i=0; i<_n_procs; ++i)
{
// Vector to receive the total bin size for each
// processor. Processor i's bin size will be
// held in proc_bin_size[i]
std::vector<unsigned int> proc_bin_size;
// Find the number of contributions coming from each
// processor for this bin. Note: allgather combines
// the MPI_Gather and MPI_Bcast operations into one.
Parallel::allgather(_local_bin_sizes[i], proc_bin_size);
// Compute the offsets into my_bin for each processor's
// portion of the bin. These are basically partial sums
// of the proc_bin_size vector.
std::vector<unsigned int> displacements(_n_procs);
for (unsigned int j=1; j<_n_procs; ++j)
displacements[j] = proc_bin_size[j-1] + displacements[j-1];
// Resize the destination buffer
dest.resize (global_bin_sizes[i]);
MPI_Gatherv((_data.size() > local_offset) ?
&_data[local_offset] :
NULL, // Points to the beginning of the bin to be sent
_local_bin_sizes[i], // How much data is in the bin being sent.
Parallel::StandardType<KeyType>(), // The data type we are sorting
(dest.empty()) ?
NULL :
&dest[0], // Enough storage to hold all bin contributions
(int*) &proc_bin_size[0], // How much is to be received from each processor
(int*) &displacements[0], // Offsets into the receive buffer
Parallel::StandardType<KeyType>(), // The data type we are sorting
i, // The root process (we do this once for each proc)
libMesh::COMM_WORLD);
// Copy the destination buffer if it
// corresponds to the bin for this processor
if (i == _proc_id)
_my_bin = dest;
// Increment the local offset counter
local_offset += _local_bin_sizes[i];
}
#endif // LIBMESH_HAVE_MPI
}
#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
// Full specialization for HilbertIndices, there is a fair amount of
// code duplication here that could potentially be consolidated with the
// above method
template <>
void Sort<Hilbert::HilbertIndices>::communicate_bins()
{
// Create storage for the global bin sizes. This
// is the number of keys which will be held in
// each bin over all processors.
std::vector<unsigned int> global_bin_sizes(_n_procs);
libmesh_assert (_local_bin_sizes.size() == global_bin_sizes.size());
// Sum to find the total number of entries in each bin.
// This is stored in global_bin_sizes. Note, we
// explicitly know that we are communicating MPI_UNSIGNED's here.
MPI_Allreduce(&_local_bin_sizes[0],
&global_bin_sizes[0],
_n_procs,
MPI_UNSIGNED,
MPI_SUM,
libMesh::COMM_WORLD);
// Create a vector to temporarily hold the results of MPI_Gatherv
// calls. The vector dest may be saved away to _my_bin depending on which
// processor is being MPI_Gatherv'd.
std::vector<Hilbert::HilbertIndices> sendbuf, dest;
unsigned int local_offset = 0;
for (unsigned int i=0; i<_n_procs; ++i)
{
// Vector to receive the total bin size for each
// processor. Processor i's bin size will be
// held in proc_bin_size[i]
std::vector<unsigned int> proc_bin_size(_n_procs);
// Find the number of contributions coming from each
// processor for this bin. Note: Allgather combines
// the MPI_Gather and MPI_Bcast operations into one.
// Note: Here again we know that we are communicating
// MPI_UNSIGNED's so there is no need to check the MPI_traits.
MPI_Allgather(&_local_bin_sizes[i], // Source: # of entries on this proc in bin i
1, // Number of items to gather
MPI_UNSIGNED,
&proc_bin_size[0], // Destination: Total # of entries in bin i
1,
MPI_UNSIGNED,
libMesh::COMM_WORLD);
// Compute the offsets into my_bin for each processor's
// portion of the bin. These are basically partial sums
// of the proc_bin_size vector.
std::vector<unsigned int> displacements(_n_procs);
for (unsigned int j=1; j<_n_procs; ++j)
displacements[j] = proc_bin_size[j-1] + displacements[j-1];
// Resize the destination buffer
dest.resize (global_bin_sizes[i]);
MPI_Gatherv((_data.size() > local_offset) ?
&_data[local_offset] :
NULL, // Points to the beginning of the bin to be sent
_local_bin_sizes[i], // How much data is in the bin being sent.
Parallel::StandardType<Hilbert::HilbertIndices>(), // The data type we are sorting
(dest.empty()) ?
NULL :
&dest[0], // Enough storage to hold all bin contributions
(int*) &proc_bin_size[0], // How much is to be received from each processor
(int*) &displacements[0], // Offsets into the receive buffer
Parallel::StandardType<Hilbert::HilbertIndices>(), // The data type we are sorting
i, // The root process (we do this once for each proc)
libMesh::COMM_WORLD);
// Copy the destination buffer if it
// corresponds to the bin for this processor
if (i == _proc_id)
_my_bin = dest;
// Increment the local offset counter
local_offset += _local_bin_sizes[i];
}
}
#endif // #if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
template <typename KeyType>
void Sort<KeyType>::sort_local_bin()
{
std::sort(_my_bin.begin(), _my_bin.end());
}
template <typename KeyType>
const std::vector<KeyType>& Sort<KeyType>::bin()
{
if (!_bin_is_sorted)
{
libMesh::out << "Warning! Bin is not yet sorted!" << std::endl;
}
return _my_bin;
}
}
// Explicitly instantiate for int, double
template class Parallel::Sort<int>;
template class Parallel::Sort<double>;
#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)
template class Parallel::Sort<Hilbert::HilbertIndices>;
#endif
} // namespace libMesh
<|endoftext|> |
<commit_before>/// \file http_parser.cpp
/// Holds all code for the HTTP namespace.
#include "http_parser.h"
/// This constructor creates an empty HTTP::Parser, ready for use for either reading or writing.
/// All this constructor does is call HTTP::Parser::Clean().
HTTP::Parser::Parser(){Clean();}
/// Completely re-initializes the HTTP::Parser, leaving it ready for either reading or writing usage.
void HTTP::Parser::Clean(){
seenHeaders = false;
seenReq = false;
method = "GET";
url = "/";
protocol = "HTTP/1.1";
body.clear();
length = 0;
headers.clear();
vars.clear();
}
/// Re-initializes the HTTP::Parser, leaving the internal data buffer alone, then tries to parse a new request or response.
/// Does the same as HTTP::Parser::Clean(), then returns HTTP::Parser::parse().
bool HTTP::Parser::CleanForNext(){
Clean();
return parse();
}
/// Returns a string containing a valid HTTP 1.0 or 1.1 request, ready for sending.
/// The request is build from internal variables set before this call is made.
/// To be precise, method, url, protocol, headers and body are used.
/// \return A string containing a valid HTTP 1.0 or 1.1 request, ready for sending.
std::string HTTP::Parser::BuildRequest(){
/// \todo Include GET/POST variable parsing?
std::map<std::string, std::string>::iterator it;
std::string tmp = method+" "+url+" "+protocol+"\n";
for (it=headers.begin(); it != headers.end(); it++){
tmp += (*it).first + ": " + (*it).second + "\n";
}
tmp += "\n";
tmp += body;
return tmp;
}
/// Returns a string containing a valid HTTP 1.0 or 1.1 response, ready for sending.
/// The response is partly build from internal variables set before this call is made.
/// To be precise, protocol, headers and body are used.
/// \param code The HTTP response code. Usually you want 200.
/// \param message The HTTP response message. Usually you want "OK".
/// \return A string containing a valid HTTP 1.0 or 1.1 response, ready for sending.
std::string HTTP::Parser::BuildResponse(std::string code, std::string message){
/// \todo Include GET/POST variable parsing?
std::map<std::string, std::string>::iterator it;
std::string tmp = protocol+" "+code+" "+message+"\n";
for (it=headers.begin(); it != headers.end(); it++){
tmp += (*it).first + ": " + (*it).second + "\n";
}
tmp += "\n";
tmp += body;
return tmp;
}
/// Trims any whitespace at the front or back of the string.
/// Used when getting/setting headers.
/// \param s The string to trim. The string itself will be changed, not returned.
void HTTP::Parser::Trim(std::string & s){
size_t startpos = s.find_first_not_of(" \t");
size_t endpos = s.find_last_not_of(" \t");
if ((std::string::npos == startpos) || (std::string::npos == endpos)){s = "";}else{s = s.substr(startpos, endpos-startpos+1);}
}
/// Function that sets the body of a response or request, along with the correct Content-Length header.
/// \param s The string to set the body to.
void HTTP::Parser::SetBody(std::string s){
body = s;
SetHeader("Content-Length", s.length());
}
/// Function that sets the body of a response or request, along with the correct Content-Length header.
/// \param buffer The buffer data to set the body to.
/// \param len Length of the buffer data.
void HTTP::Parser::SetBody(char * buffer, int len){
body = "";
body.append(buffer, len);
SetHeader("Content-Length", len);
}
/// Returns header i, if set.
std::string HTTP::Parser::GetHeader(std::string i){return headers[i];}
/// Returns POST variable i, if set.
std::string HTTP::Parser::GetVar(std::string i){return vars[i];}
/// Sets header i to string value v.
void HTTP::Parser::SetHeader(std::string i, std::string v){
Trim(i);
Trim(v);
headers[i] = v;
}
/// Sets header i to integer value v.
void HTTP::Parser::SetHeader(std::string i, int v){
Trim(i);
char val[128];
sprintf(val, "%i", v);
headers[i] = val;
}
/// Sets POST variable i to string value v.
void HTTP::Parser::SetVar(std::string i, std::string v){
Trim(i);
Trim(v);
vars[i] = v;
}
/// Attempt to read a whole HTTP request or response from Socket::Connection.
/// \param sock The socket to use.
/// \param nonblock When true, will not block even if the socket is blocking.
/// \return True of a whole request or response was read, false otherwise.
bool HTTP::Parser::Read(Socket::Connection & sock, bool nonblock){
if (nonblock && (sock.ready() < 1)){return parse();}
sock.read(HTTPbuffer);
return parse();
}//HTTPReader::ReadSocket
/// Reads a full set of HTTP responses/requests from file F.
/// \return Always false. Use HTTP::Parser::CleanForNext() to parse the contents of the file.
bool HTTP::Parser::Read(FILE * F){
//returned true als hele http packet gelezen is
int b = 1;
char buffer[500];
while (b > 0){
b = fread(buffer, 1, 500, F);
HTTPbuffer.append(buffer, b);
}
return false;
}//HTTPReader::ReadSocket
/// Attempt to read a whole HTTP response or request from the internal data buffer.
/// If succesful, fills its own fields with the proper data and removes the response/request
/// from the internal data buffer.
/// \return True on success, false otherwise.
bool HTTP::Parser::parse(){
size_t f;
std::string tmpA, tmpB, tmpC;
while (HTTPbuffer != ""){
if (!seenHeaders){
f = HTTPbuffer.find('\n');
if (f == std::string::npos) return false;
tmpA = HTTPbuffer.substr(0, f);
HTTPbuffer.erase(0, f+1);
while (tmpA.find('\r') != std::string::npos){tmpA.erase(tmpA.find('\r'));}
if (!seenReq){
seenReq = true;
f = tmpA.find(' ');
if (f != std::string::npos){method = tmpA.substr(0, f); tmpA.erase(0, f+1);}
f = tmpA.find(' ');
if (f != std::string::npos){url = tmpA.substr(0, f); tmpA.erase(0, f+1);}
f = tmpA.find(' ');
if (f != std::string::npos){protocol = tmpA.substr(0, f); tmpA.erase(0, f+1);}
if (url.find('?') != std::string::npos){
std::string queryvars = url.substr(url.find('?')+1);
parseVars(queryvars); //parse GET variables
}
}else{
if (tmpA.size() == 0){
seenHeaders = true;
if (GetHeader("Content-Length") != ""){length = atoi(GetHeader("Content-Length").c_str());}
}else{
f = tmpA.find(':');
if (f == std::string::npos) continue;
tmpB = tmpA.substr(0, f);
tmpC = tmpA.substr(f+1);
SetHeader(tmpB, tmpC);
}
}
}
if (seenHeaders){
if (length > 0){
if (HTTPbuffer.length() >= length){
if ((method != "HTTP/1.0") && (method != "HTTP/1.1")){
body = HTTPbuffer.substr(0, length);
parseVars(body); //parse POST variables
}
body = HTTPbuffer.substr(0, length);
HTTPbuffer.erase(0, length);
return true;
}else{
return false;
}
}else{
return true;
}
}
}
return false; //we should never get here...
}//HTTPReader::parse
/// Sends data as response to conn.
/// The response is automatically first build using HTTP::Parser::BuildResponse().
/// \param conn The Socket::Connection to send the response over.
/// \param code The HTTP response code. Usually you want 200.
/// \param message The HTTP response message. Usually you want "OK".
void HTTP::Parser::SendResponse(Socket::Connection & conn, std::string code, std::string message){
std::string tmp = BuildResponse(code, message);
conn.write(tmp);
}
/// Parses GET or POST-style variable data.
/// Saves to internal variable structure using HTTP::Parser::SetVar.
void HTTP::Parser::parseVars(std::string & data){
std::string varname;
std::string varval;
while (data.find('=') != std::string::npos){
size_t found = data.find('=');
varname = urlunescape(data.substr(0, found));
data.erase(0, found+1);
found = data.find('&');
varval = urlunescape(data.substr(0, found));
SetVar(varname, varval);
if (found == std::string::npos){
data.clear();
}else{
data.erase(0, found+1);
}
}
}
/// Sends data as HTTP/1.1 bodypart to conn.
/// HTTP/1.1 chunked encoding is automatically applied if needed.
/// \param conn The Socket::Connection to send the part over.
/// \param buffer The buffer to send.
/// \param len The length of the buffer.
void HTTP::Parser::SendBodyPart(Socket::Connection & conn, char * buffer, int len){
std::string tmp;
tmp.append(buffer, len);
SendBodyPart(conn, tmp);
}
/// Sends data as HTTP/1.1 bodypart to conn.
/// HTTP/1.1 chunked encoding is automatically applied if needed.
/// \param conn The Socket::Connection to send the part over.
/// \param bodypart The data to send.
void HTTP::Parser::SendBodyPart(Socket::Connection & conn, std::string bodypart){
if (protocol == "HTTP/1.1"){
static char len[10];
int sizelen;
sizelen = snprintf(len, 10, "%x\r\n", (unsigned int)bodypart.size());
conn.write(len, sizelen);
conn.write(bodypart);
conn.write(len+sizelen-2, 2);
}else{
conn.write(bodypart);
}
}
/// Unescapes URLencoded std::string data.
std::string HTTP::Parser::urlunescape(const std::string & in){
std::string out;
for (unsigned int i = 0; i < in.length(); ++i){
if (in[i] == '%'){
char tmp = 0;
++i;
if (i < in.length()){
tmp = unhex(in[i]) << 4;
}
++i;
if (i < in.length()){
tmp += unhex(in[i]);
}
out += tmp;
} else {
if (in[i] == '+'){out += ' ';}else{out += in[i];}
}
}
return out;
}
/// Helper function for urlunescape.
/// Takes a single char input and outputs its integer hex value.
int HTTP::Parser::unhex(char c){
return( c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c - 'a' + 10 );
}
/// URLencodes std::string data.
std::string HTTP::Parser::urlencode(const std::string &c){
std::string escaped="";
int max = c.length();
for(int i=0; i<max; i++){
if (('0'<=c[i] && c[i]<='9') || ('a'<=c[i] && c[i]<='z') || ('A'<=c[i] && c[i]<='Z') || (c[i]=='~' || c[i]=='!' || c[i]=='*' || c[i]=='(' || c[i]==')' || c[i]=='\'')){
escaped.append( &c[i], 1);
}else{
escaped.append("%");
escaped.append(hex(c[i]));
}
}
return escaped;
}
/// Helper function for urlescape.
/// Encodes a character as two hex digits.
std::string HTTP::Parser::hex(char dec){
char dig1 = (dec&0xF0)>>4;
char dig2 = (dec&0x0F);
if (dig1<= 9) dig1+=48;
if (10<= dig1 && dig1<=15) dig1+=97-10;
if (dig2<= 9) dig2+=48;
if (10<= dig2 && dig2<=15) dig2+=97-10;
std::string r;
r.append(&dig1, 1);
r.append(&dig2, 1);
return r;
}
<commit_msg>Fixed HTTP util parsing of variables.<commit_after>/// \file http_parser.cpp
/// Holds all code for the HTTP namespace.
#include "http_parser.h"
/// This constructor creates an empty HTTP::Parser, ready for use for either reading or writing.
/// All this constructor does is call HTTP::Parser::Clean().
HTTP::Parser::Parser(){Clean();}
/// Completely re-initializes the HTTP::Parser, leaving it ready for either reading or writing usage.
void HTTP::Parser::Clean(){
seenHeaders = false;
seenReq = false;
method = "GET";
url = "/";
protocol = "HTTP/1.1";
body.clear();
length = 0;
headers.clear();
vars.clear();
}
/// Re-initializes the HTTP::Parser, leaving the internal data buffer alone, then tries to parse a new request or response.
/// Does the same as HTTP::Parser::Clean(), then returns HTTP::Parser::parse().
bool HTTP::Parser::CleanForNext(){
Clean();
return parse();
}
/// Returns a string containing a valid HTTP 1.0 or 1.1 request, ready for sending.
/// The request is build from internal variables set before this call is made.
/// To be precise, method, url, protocol, headers and body are used.
/// \return A string containing a valid HTTP 1.0 or 1.1 request, ready for sending.
std::string HTTP::Parser::BuildRequest(){
/// \todo Include GET/POST variable parsing?
std::map<std::string, std::string>::iterator it;
std::string tmp = method+" "+url+" "+protocol+"\n";
for (it=headers.begin(); it != headers.end(); it++){
tmp += (*it).first + ": " + (*it).second + "\n";
}
tmp += "\n" + body + "\n";
return tmp;
}
/// Returns a string containing a valid HTTP 1.0 or 1.1 response, ready for sending.
/// The response is partly build from internal variables set before this call is made.
/// To be precise, protocol, headers and body are used.
/// \param code The HTTP response code. Usually you want 200.
/// \param message The HTTP response message. Usually you want "OK".
/// \return A string containing a valid HTTP 1.0 or 1.1 response, ready for sending.
std::string HTTP::Parser::BuildResponse(std::string code, std::string message){
/// \todo Include GET/POST variable parsing?
std::map<std::string, std::string>::iterator it;
std::string tmp = protocol+" "+code+" "+message+"\n";
for (it=headers.begin(); it != headers.end(); it++){
tmp += (*it).first + ": " + (*it).second + "\n";
}
tmp += "\n";
tmp += body;
return tmp;
}
/// Trims any whitespace at the front or back of the string.
/// Used when getting/setting headers.
/// \param s The string to trim. The string itself will be changed, not returned.
void HTTP::Parser::Trim(std::string & s){
size_t startpos = s.find_first_not_of(" \t");
size_t endpos = s.find_last_not_of(" \t");
if ((std::string::npos == startpos) || (std::string::npos == endpos)){s = "";}else{s = s.substr(startpos, endpos-startpos+1);}
}
/// Function that sets the body of a response or request, along with the correct Content-Length header.
/// \param s The string to set the body to.
void HTTP::Parser::SetBody(std::string s){
body = s;
SetHeader("Content-Length", s.length());
}
/// Function that sets the body of a response or request, along with the correct Content-Length header.
/// \param buffer The buffer data to set the body to.
/// \param len Length of the buffer data.
void HTTP::Parser::SetBody(char * buffer, int len){
body = "";
body.append(buffer, len);
SetHeader("Content-Length", len);
}
/// Returns header i, if set.
std::string HTTP::Parser::GetHeader(std::string i){return headers[i];}
/// Returns POST variable i, if set.
std::string HTTP::Parser::GetVar(std::string i){return vars[i];}
/// Sets header i to string value v.
void HTTP::Parser::SetHeader(std::string i, std::string v){
Trim(i);
Trim(v);
headers[i] = v;
}
/// Sets header i to integer value v.
void HTTP::Parser::SetHeader(std::string i, int v){
Trim(i);
char val[128];
sprintf(val, "%i", v);
headers[i] = val;
}
/// Sets POST variable i to string value v.
void HTTP::Parser::SetVar(std::string i, std::string v){
Trim(i);
Trim(v);
vars[i] = v;
}
/// Attempt to read a whole HTTP request or response from Socket::Connection.
/// \param sock The socket to use.
/// \param nonblock When true, will not block even if the socket is blocking.
/// \return True of a whole request or response was read, false otherwise.
bool HTTP::Parser::Read(Socket::Connection & sock, bool nonblock){
if (nonblock && (sock.ready() < 1)){return parse();}
sock.read(HTTPbuffer);
return parse();
}//HTTPReader::ReadSocket
/// Reads a full set of HTTP responses/requests from file F.
/// \return Always false. Use HTTP::Parser::CleanForNext() to parse the contents of the file.
bool HTTP::Parser::Read(FILE * F){
//returned true als hele http packet gelezen is
int b = 1;
char buffer[500];
while (b > 0){
b = fread(buffer, 1, 500, F);
HTTPbuffer.append(buffer, b);
}
return false;
}//HTTPReader::ReadSocket
/// Attempt to read a whole HTTP response or request from the internal data buffer.
/// If succesful, fills its own fields with the proper data and removes the response/request
/// from the internal data buffer.
/// \return True on success, false otherwise.
bool HTTP::Parser::parse(){
size_t f;
std::string tmpA, tmpB, tmpC;
while (HTTPbuffer != ""){
if (!seenHeaders){
f = HTTPbuffer.find('\n');
if (f == std::string::npos) return false;
tmpA = HTTPbuffer.substr(0, f);
HTTPbuffer.erase(0, f+1);
while (tmpA.find('\r') != std::string::npos){tmpA.erase(tmpA.find('\r'));}
if (!seenReq){
seenReq = true;
f = tmpA.find(' ');
if (f != std::string::npos){method = tmpA.substr(0, f); tmpA.erase(0, f+1);}
f = tmpA.find(' ');
if (f != std::string::npos){url = tmpA.substr(0, f); tmpA.erase(0, f+1);}
f = tmpA.find(' ');
if (f != std::string::npos){protocol = tmpA.substr(0, f); tmpA.erase(0, f+1);}
if (url.find('?') != std::string::npos){
std::string queryvars = url.substr(url.find('?')+1);
parseVars(queryvars); //parse GET variables
}
}else{
if (tmpA.size() == 0){
seenHeaders = true;
if (GetHeader("Content-Length") != ""){length = atoi(GetHeader("Content-Length").c_str());}
}else{
f = tmpA.find(':');
if (f == std::string::npos) continue;
tmpB = tmpA.substr(0, f);
tmpC = tmpA.substr(f+1);
SetHeader(tmpB, tmpC);
}
}
}
if (seenHeaders){
if (length > 0){
if (HTTPbuffer.length() >= length){
body = HTTPbuffer.substr(0, length);
parseVars(body); //parse POST variables
HTTPbuffer.erase(0, length);
return true;
}else{
return false;
}
}else{
return true;
}
}
}
return false; //we should never get here...
}//HTTPReader::parse
/// Sends data as response to conn.
/// The response is automatically first build using HTTP::Parser::BuildResponse().
/// \param conn The Socket::Connection to send the response over.
/// \param code The HTTP response code. Usually you want 200.
/// \param message The HTTP response message. Usually you want "OK".
void HTTP::Parser::SendResponse(Socket::Connection & conn, std::string code, std::string message){
std::string tmp = BuildResponse(code, message);
conn.write(tmp);
}
/// Parses GET or POST-style variable data.
/// Saves to internal variable structure using HTTP::Parser::SetVar.
void HTTP::Parser::parseVars(std::string & data){
std::string varname;
std::string varval;
while (data.find('=') != std::string::npos){
size_t found = data.find('=');
varname = urlunescape(data.substr(0, found));
data.erase(0, found+1);
found = data.find('&');
varval = urlunescape(data.substr(0, found));
SetVar(varname, varval);
if (found == std::string::npos){
data.clear();
}else{
data.erase(0, found+1);
}
}
}
/// Sends data as HTTP/1.1 bodypart to conn.
/// HTTP/1.1 chunked encoding is automatically applied if needed.
/// \param conn The Socket::Connection to send the part over.
/// \param buffer The buffer to send.
/// \param len The length of the buffer.
void HTTP::Parser::SendBodyPart(Socket::Connection & conn, char * buffer, int len){
std::string tmp;
tmp.append(buffer, len);
SendBodyPart(conn, tmp);
}
/// Sends data as HTTP/1.1 bodypart to conn.
/// HTTP/1.1 chunked encoding is automatically applied if needed.
/// \param conn The Socket::Connection to send the part over.
/// \param bodypart The data to send.
void HTTP::Parser::SendBodyPart(Socket::Connection & conn, std::string bodypart){
if (protocol == "HTTP/1.1"){
static char len[10];
int sizelen;
sizelen = snprintf(len, 10, "%x\r\n", (unsigned int)bodypart.size());
conn.write(len, sizelen);
conn.write(bodypart);
conn.write(len+sizelen-2, 2);
}else{
conn.write(bodypart);
}
}
/// Unescapes URLencoded std::string data.
std::string HTTP::Parser::urlunescape(const std::string & in){
std::string out;
for (unsigned int i = 0; i < in.length(); ++i){
if (in[i] == '%'){
char tmp = 0;
++i;
if (i < in.length()){
tmp = unhex(in[i]) << 4;
}
++i;
if (i < in.length()){
tmp += unhex(in[i]);
}
out += tmp;
} else {
if (in[i] == '+'){out += ' ';}else{out += in[i];}
}
}
return out;
}
/// Helper function for urlunescape.
/// Takes a single char input and outputs its integer hex value.
int HTTP::Parser::unhex(char c){
return( c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c - 'a' + 10 );
}
/// URLencodes std::string data.
std::string HTTP::Parser::urlencode(const std::string &c){
std::string escaped="";
int max = c.length();
for(int i=0; i<max; i++){
if (('0'<=c[i] && c[i]<='9') || ('a'<=c[i] && c[i]<='z') || ('A'<=c[i] && c[i]<='Z') || (c[i]=='~' || c[i]=='!' || c[i]=='*' || c[i]=='(' || c[i]==')' || c[i]=='\'')){
escaped.append( &c[i], 1);
}else{
escaped.append("%");
escaped.append(hex(c[i]));
}
}
return escaped;
}
/// Helper function for urlescape.
/// Encodes a character as two hex digits.
std::string HTTP::Parser::hex(char dec){
char dig1 = (dec&0xF0)>>4;
char dig2 = (dec&0x0F);
if (dig1<= 9) dig1+=48;
if (10<= dig1 && dig1<=15) dig1+=97-10;
if (dig2<= 9) dig2+=48;
if (10<= dig2 && dig2<=15) dig2+=97-10;
std::string r;
r.append(&dig1, 1);
r.append(&dig2, 1);
return r;
}
<|endoftext|> |
<commit_before>#include <chord_types.h>
#include <location.h>
#include <id_utils.h>
#include <configurator.h>
#include "block_status.h"
#include "misc_utils.h"
#include "dhash.h"
u_long
num_efrags ()
{
static bool initialized = false;
static int v = 0;
if (!initialized) {
initialized = Configurator::only ().get_int ("dhash.efrags", v);
assert (initialized);
}
return v;
}
void
block_status::missing_on (ptr<location> l)
{
for (size_t i = 0; i < missing.size (); i++)
if (missing[i]->id () == l->id ()) {
assert (missing[i] == l);
return;
}
missing.push_back (l);
}
void
block_status::found_on (ptr<location> l)
{
size_t last = missing.size () - 1;
for (size_t i = 0; i < missing.size (); i++) {
assert (missing[i]);
if (missing[i]->id () == l->id ()) {
missing[i] = missing[last];
missing.pop_back ();
return;
}
}
}
bool
block_status::is_missing_on (chordID n)
{
for (size_t i = 0; i < missing.size (); i++)
if (missing[i]->id () == n)
return true;
return false;
}
void
block_status::print ()
{
warn << "status of " << id << ": missing on ";
for (u_int i = 0; i < missing.size (); i++)
{
warn << missing[i]->id() << " ";
}
warn << "\n";
}
block_status_manager::block_status_manager (chordID me) : my_id (me)
{
}
void
block_status_manager::add_block (const chordID &b)
{
if (blocks[b] != NULL)
return;
block_status *bs = New block_status (b);
blocks.insert (bs);
sblocks.insert (bs);
}
void
block_status_manager::del_block (const chordID &b)
{
block_status *bs = blocks[b];
if (bs == NULL)
return;
blocks.remove (bs);
sblocks.remove (bs->id);
delete bs;
}
void
block_status_manager::missing (ptr<location> remote, const chordID &b)
{
if (blocks[b] == NULL) {
add_block (b);
}
blocks[b]->missing_on (remote);
}
void
block_status_manager::unmissing (ptr<location> remote, const chordID &b)
{
if (blocks[b] == NULL)
return;
blocks[b]->found_on (remote);
}
chordID
block_status_manager::first_block ()
{
if (sblocks.size () == 0)
return chordID (0);
block_status *bs = sblocks.closestsucc (my_id);
return bs->id;
}
chordID
block_status_manager::next_block (const chordID &b)
{
if (sblocks.size () == 0)
return chordID (0);
block_status *bs = sblocks.closestsucc (incID(b));
if (!bs)
bs = sblocks.first ();
return bs->id;
}
const vec<ptr<location> >
block_status_manager::where_missing (const chordID &b)
{
block_status *bs = blocks[b];
if (bs == NULL) {
vec<ptr<location> > nothing;
return nothing; /* silently fail... */
}
return bs->missing;
}
bool
block_status_manager::missing_on (const chordID &b, chordID &n)
{
block_status *bs = blocks[b];
if (bs == NULL) return false;
vec<ptr<location> > m = bs->missing;
for (u_int i = 0; i < m.size (); i++)
if (m[i]->id () == n) return true;
return false;
}
const vec<chordID>
block_status_manager::missing_what (const chordID &n)
{
vec<chordID > ret;
block_status *bs = blocks.first ();
while (bs) {
if (bs->is_missing_on (n)) {
ret.push_back (bs->id);
}
bs = blocks.next(bs);
}
return ret;
}
const ptr<location>
block_status_manager::best_missing (const chordID &b, vec<ptr<location> > succs)
{
vec<ptr<location> > m = where_missing (b);
assert (m.size () > 0);
chordID best = m[0]->id ();
ptr<location> l = m[0];
for (u_int i = 0; i < m.size (); i++)
if (betweenbothincl (my_id, best, m[i]->id ())
&& in_vector (succs, b)) {
best = m[i]->id ();
l = m[i];
}
return l;
}
u_int
block_status_manager::pcount (const chordID &b, vec<ptr<location> > succs)
{
int present = 0;
//for every successor, assume present if not in missing list
// and if succ # < dhash::efrags
block_status *bs = blocks[b];
if (!bs) return num_efrags ();
vec<ptr<location> > missing = bs->missing;
char is_missing;
// FED: removed below from for termination clause; allow holes by
// testing all successors
// && s < num_efrags ()
for (u_int s = 0;
s < succs.size ();
s++)
{
is_missing = 0;
for (u_int m=0; m < missing.size (); m++)
{
if (missing[m]->id () == succs[s]->id ()) is_missing = 1;
}
if (!is_missing) present++;
}
return present;
}
u_int
block_status_manager::mcount (const chordID &b)
{
block_status *bs = blocks[b];
if (bs == NULL)
return 0;
else
return bs->missing.size ();
}
void
block_status_manager::print ()
{
block_status *bs = blocks.first ();
while (bs)
{
bs->print ();
bs = blocks.next (bs);
}
}
<commit_msg>Don't need to include dhash.h<commit_after>#include <chord_types.h>
#include <location.h>
#include <id_utils.h>
#include <configurator.h>
#include "block_status.h"
#include "misc_utils.h"
u_long
num_efrags ()
{
static bool initialized = false;
static int v = 0;
if (!initialized) {
initialized = Configurator::only ().get_int ("dhash.efrags", v);
assert (initialized);
}
return v;
}
void
block_status::missing_on (ptr<location> l)
{
for (size_t i = 0; i < missing.size (); i++)
if (missing[i]->id () == l->id ()) {
assert (missing[i] == l);
return;
}
missing.push_back (l);
}
void
block_status::found_on (ptr<location> l)
{
size_t last = missing.size () - 1;
for (size_t i = 0; i < missing.size (); i++) {
assert (missing[i]);
if (missing[i]->id () == l->id ()) {
missing[i] = missing[last];
missing.pop_back ();
return;
}
}
}
bool
block_status::is_missing_on (chordID n)
{
for (size_t i = 0; i < missing.size (); i++)
if (missing[i]->id () == n)
return true;
return false;
}
void
block_status::print ()
{
warn << "status of " << id << ": missing on ";
for (u_int i = 0; i < missing.size (); i++)
{
warn << missing[i]->id() << " ";
}
warn << "\n";
}
block_status_manager::block_status_manager (chordID me) : my_id (me)
{
}
void
block_status_manager::add_block (const chordID &b)
{
if (blocks[b] != NULL)
return;
block_status *bs = New block_status (b);
blocks.insert (bs);
sblocks.insert (bs);
}
void
block_status_manager::del_block (const chordID &b)
{
block_status *bs = blocks[b];
if (bs == NULL)
return;
blocks.remove (bs);
sblocks.remove (bs->id);
delete bs;
}
void
block_status_manager::missing (ptr<location> remote, const chordID &b)
{
if (blocks[b] == NULL) {
add_block (b);
}
blocks[b]->missing_on (remote);
}
void
block_status_manager::unmissing (ptr<location> remote, const chordID &b)
{
if (blocks[b] == NULL)
return;
blocks[b]->found_on (remote);
}
chordID
block_status_manager::first_block ()
{
if (sblocks.size () == 0)
return chordID (0);
block_status *bs = sblocks.closestsucc (my_id);
return bs->id;
}
chordID
block_status_manager::next_block (const chordID &b)
{
if (sblocks.size () == 0)
return chordID (0);
block_status *bs = sblocks.closestsucc (incID(b));
if (!bs)
bs = sblocks.first ();
return bs->id;
}
const vec<ptr<location> >
block_status_manager::where_missing (const chordID &b)
{
block_status *bs = blocks[b];
if (bs == NULL) {
vec<ptr<location> > nothing;
return nothing; /* silently fail... */
}
return bs->missing;
}
bool
block_status_manager::missing_on (const chordID &b, chordID &n)
{
block_status *bs = blocks[b];
if (bs == NULL) return false;
vec<ptr<location> > m = bs->missing;
for (u_int i = 0; i < m.size (); i++)
if (m[i]->id () == n) return true;
return false;
}
const vec<chordID>
block_status_manager::missing_what (const chordID &n)
{
vec<chordID > ret;
block_status *bs = blocks.first ();
while (bs) {
if (bs->is_missing_on (n)) {
ret.push_back (bs->id);
}
bs = blocks.next(bs);
}
return ret;
}
const ptr<location>
block_status_manager::best_missing (const chordID &b, vec<ptr<location> > succs)
{
vec<ptr<location> > m = where_missing (b);
assert (m.size () > 0);
chordID best = m[0]->id ();
ptr<location> l = m[0];
for (u_int i = 0; i < m.size (); i++)
if (betweenbothincl (my_id, best, m[i]->id ())
&& in_vector (succs, b)) {
best = m[i]->id ();
l = m[i];
}
return l;
}
u_int
block_status_manager::pcount (const chordID &b, vec<ptr<location> > succs)
{
int present = 0;
//for every successor, assume present if not in missing list
// and if succ # < dhash::efrags
block_status *bs = blocks[b];
if (!bs) return num_efrags ();
vec<ptr<location> > missing = bs->missing;
char is_missing;
// FED: removed below from for termination clause; allow holes by
// testing all successors
// && s < num_efrags ()
for (u_int s = 0;
s < succs.size ();
s++)
{
is_missing = 0;
for (u_int m=0; m < missing.size (); m++)
{
if (missing[m]->id () == succs[s]->id ()) is_missing = 1;
}
if (!is_missing) present++;
}
return present;
}
u_int
block_status_manager::mcount (const chordID &b)
{
block_status *bs = blocks[b];
if (bs == NULL)
return 0;
else
return bs->missing.size ();
}
void
block_status_manager::print ()
{
block_status *bs = blocks.first ();
while (bs)
{
bs->print ();
bs = blocks.next (bs);
}
}
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "MaskedExponential.h"
registerMooseObject("MarmotApp", MaskedExponential);
InputParameters
MaskedExponential::validParams()
{
InputParameters params = Kernel::validParams();
params.addRequiredCoupledVar("w", "Chemical potential for the defect species");
params.addRequiredCoupledVar("T", "Temperature");
params.addClassDescription(
"Kernel to add dilute solution term to Poisson's equation for electrochemical sintering");
params.addParam<MaterialPropertyName>(
"mask", "hm", "Mask function that specifies where this kernel is active");
params.addRequiredParam<MaterialPropertyName>("n_eq", "Equilibrium defect concentration");
params.addRequiredParam<int>("species_charge", "Charge of species this kernel is being used for");
params.addCoupledVar("args", "Vector of nonlinear variable arguments this object depends on");
return params;
}
MaskedExponential::MaskedExponential(const InputParameters & parameters)
: DerivativeMaterialInterface<JvarMapKernelInterface<Kernel>>(parameters),
_w_var(coupled("w")),
_w(coupledValue("w")),
_temp_name(getVar("T", 0)->name()),
_temp_var(coupled("T")),
_temp(coupledValue("T")),
_mask(getMaterialProperty<Real>("mask")),
_prop_dmaskdarg(_n_args),
_n_eq(getMaterialProperty<Real>("n_eq")),
_prop_dn_eqdT(getMaterialPropertyDerivative<Real>("n_eq", _temp_name)),
_prop_dn_eqdarg(_n_args),
_z(getParam<int>("species_charge")),
_kB(8.617343e-5), // eV/K
_e(1.0) // To put energy units in eV
{
// Get derivatives of mask and equilibrium defect concentration
for (unsigned int i = 0; i < _n_args; ++i)
{
_prop_dmaskdarg[i] = &getMaterialPropertyDerivative<Real>("mask", i);
_prop_dn_eqdarg[i] = &getMaterialPropertyDerivative<Real>("n_eq", i);
}
}
void
MaskedExponential::initialSetup()
{
validateNonlinearCoupling<Real>("mask");
validateNonlinearCoupling<Real>("n_eq");
}
Real
MaskedExponential::computeQpResidual()
{
return _mask[_qp] * _z * _e * _n_eq[_qp] * _test[_i][_qp] *
exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]);
}
Real
MaskedExponential::computeQpJacobian()
{
return -_mask[_qp] * _z * _z * _e * _e / _kB / _temp[_qp] * _n_eq[_qp] * _test[_i][_qp] *
_phi[_j][_qp] * exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]);
}
Real
MaskedExponential::computeQpOffDiagJacobian(unsigned int jvar)
{
// Handle chemical potential explicitly since it appears in the residual
if (jvar == _w_var)
return _mask[_qp] * _z * _e * _n_eq[_qp] / _kB / _temp[_qp] *
exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]) * _phi[_j][_qp] * _test[_i][_qp];
// Handle temperature explicitly since it appears in the residual
if (jvar == _temp_var)
return _mask[_qp] * _z * _e * exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]) *
(_prop_dn_eqdT[_qp] -
_n_eq[_qp] * (_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp] / _temp[_qp]) *
_phi[_j][_qp] * _test[_i][_qp];
// General expression for remaining variable dependencies that don't appear in the residual
// for all other vars get the coupled variable jvar is referring to
const unsigned int cvar = mapJvarToCvar(jvar);
return _z * _e * exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]) *
((*_prop_dmaskdarg[cvar])[_qp] + (*_prop_dn_eqdarg[cvar])[_qp]) * _test[_i][_qp] *
_phi[_j][_qp];
}
<commit_msg>Update registration for move of MaskedExponential to MOOSE for electrochemical phase-field model #19339<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "MaskedExponential.h"
registerMooseObject("PhaseFieldApp", MaskedExponential);
InputParameters
MaskedExponential::validParams()
{
InputParameters params = Kernel::validParams();
params.addRequiredCoupledVar("w", "Chemical potential for the defect species");
params.addRequiredCoupledVar("T", "Temperature");
params.addClassDescription(
"Kernel to add dilute solution term to Poisson's equation for electrochemical sintering");
params.addParam<MaterialPropertyName>(
"mask", "hm", "Mask function that specifies where this kernel is active");
params.addRequiredParam<MaterialPropertyName>("n_eq", "Equilibrium defect concentration");
params.addRequiredParam<int>("species_charge", "Charge of species this kernel is being used for");
params.addCoupledVar("args", "Vector of nonlinear variable arguments this object depends on");
return params;
}
MaskedExponential::MaskedExponential(const InputParameters & parameters)
: DerivativeMaterialInterface<JvarMapKernelInterface<Kernel>>(parameters),
_w_var(coupled("w")),
_w(coupledValue("w")),
_temp_name(getVar("T", 0)->name()),
_temp_var(coupled("T")),
_temp(coupledValue("T")),
_mask(getMaterialProperty<Real>("mask")),
_prop_dmaskdarg(_n_args),
_n_eq(getMaterialProperty<Real>("n_eq")),
_prop_dn_eqdT(getMaterialPropertyDerivative<Real>("n_eq", _temp_name)),
_prop_dn_eqdarg(_n_args),
_z(getParam<int>("species_charge")),
_kB(8.617343e-5), // eV/K
_e(1.0) // To put energy units in eV
{
// Get derivatives of mask and equilibrium defect concentration
for (unsigned int i = 0; i < _n_args; ++i)
{
_prop_dmaskdarg[i] = &getMaterialPropertyDerivative<Real>("mask", i);
_prop_dn_eqdarg[i] = &getMaterialPropertyDerivative<Real>("n_eq", i);
}
}
void
MaskedExponential::initialSetup()
{
validateNonlinearCoupling<Real>("mask");
validateNonlinearCoupling<Real>("n_eq");
}
Real
MaskedExponential::computeQpResidual()
{
return _mask[_qp] * _z * _e * _n_eq[_qp] * _test[_i][_qp] *
exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]);
}
Real
MaskedExponential::computeQpJacobian()
{
return -_mask[_qp] * _z * _z * _e * _e / _kB / _temp[_qp] * _n_eq[_qp] * _test[_i][_qp] *
_phi[_j][_qp] * exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]);
}
Real
MaskedExponential::computeQpOffDiagJacobian(unsigned int jvar)
{
// Handle chemical potential explicitly since it appears in the residual
if (jvar == _w_var)
return _mask[_qp] * _z * _e * _n_eq[_qp] / _kB / _temp[_qp] *
exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]) * _phi[_j][_qp] * _test[_i][_qp];
// Handle temperature explicitly since it appears in the residual
if (jvar == _temp_var)
return _mask[_qp] * _z * _e * exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]) *
(_prop_dn_eqdT[_qp] -
_n_eq[_qp] * (_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp] / _temp[_qp]) *
_phi[_j][_qp] * _test[_i][_qp];
// General expression for remaining variable dependencies that don't appear in the residual
// for all other vars get the coupled variable jvar is referring to
const unsigned int cvar = mapJvarToCvar(jvar);
return _z * _e * exp((_w[_qp] - _z * _e * _u[_qp]) / _kB / _temp[_qp]) *
((*_prop_dmaskdarg[cvar])[_qp] + (*_prop_dn_eqdarg[cvar])[_qp]) * _test[_i][_qp] *
_phi[_j][_qp];
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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/plugin/plugin_channel_base.h"
#include "base/hash_tables.h"
#include "chrome/common/child_process.h"
#include "ipc/ipc_sync_message.h"
#if defined(OS_POSIX)
#include "ipc/ipc_channel_posix.h"
#endif
typedef base::hash_map<std::string, scoped_refptr<PluginChannelBase> >
PluginChannelMap;
static PluginChannelMap g_plugin_channels_;
PluginChannelBase* PluginChannelBase::GetChannel(
const std::string& channel_name, IPC::Channel::Mode mode,
PluginChannelFactory factory, MessageLoop* ipc_message_loop,
bool create_pipe_now) {
scoped_refptr<PluginChannelBase> channel;
PluginChannelMap::const_iterator iter = g_plugin_channels_.find(channel_name);
if (iter == g_plugin_channels_.end()) {
channel = factory();
} else {
channel = iter->second;
}
DCHECK(channel != NULL);
if (!channel->channel_valid()) {
channel->channel_name_ = channel_name;
channel->mode_ = mode;
if (channel->Init(ipc_message_loop, create_pipe_now)) {
g_plugin_channels_[channel_name] = channel;
} else {
channel = NULL;
}
}
return channel;
}
void PluginChannelBase::Broadcast(IPC::Message* message) {
for (PluginChannelMap::iterator iter = g_plugin_channels_.begin();
iter != g_plugin_channels_.end();
++iter) {
iter->second->Send(new IPC::Message(*message));
}
delete message;
}
PluginChannelBase::PluginChannelBase()
: plugin_count_(0),
peer_pid_(0),
in_remove_route_(false),
channel_valid_(false),
in_dispatch_(0),
send_unblocking_only_during_dispatch_(false) {
}
PluginChannelBase::~PluginChannelBase() {
}
void PluginChannelBase::CleanupChannels() {
// Make a copy of the references as we can't iterate the map since items will
// be removed from it as we clean them up.
std::vector<scoped_refptr<PluginChannelBase> > channels;
for (PluginChannelMap::const_iterator iter = g_plugin_channels_.begin();
iter != g_plugin_channels_.end();
++iter) {
channels.push_back(iter->second);
}
for (size_t i = 0; i < channels.size(); ++i)
channels[i]->CleanUp();
// This will clean up channels added to the map for which subsequent
// AddRoute wasn't called
g_plugin_channels_.clear();
}
bool PluginChannelBase::Init(MessageLoop* ipc_message_loop,
bool create_pipe_now) {
channel_.reset(new IPC::SyncChannel(
channel_name_, mode_, this, NULL, ipc_message_loop, create_pipe_now,
ChildProcess::current()->GetShutDownEvent()));
channel_valid_ = true;
return true;
}
bool PluginChannelBase::Send(IPC::Message* message) {
if (!channel_.get()) {
delete message;
return false;
}
if (send_unblocking_only_during_dispatch_ && in_dispatch_ == 0 &&
message->is_sync()) {
message->set_unblock(false);
}
return channel_->Send(message);
}
int PluginChannelBase::Count() {
return static_cast<int>(g_plugin_channels_.size());
}
void PluginChannelBase::OnMessageReceived(const IPC::Message& message) {
// This call might cause us to be deleted, so keep an extra reference to
// ourself so that we can send the reply and decrement back in_dispatch_.
scoped_refptr<PluginChannelBase> me(this);
in_dispatch_++;
if (message.routing_id() == MSG_ROUTING_CONTROL) {
OnControlMessageReceived(message);
} else {
bool routed = router_.RouteMessage(message);
if (!routed && message.is_sync()) {
// The listener has gone away, so we must respond or else the caller will
// hang waiting for a reply.
IPC::Message* reply = IPC::SyncMessage::GenerateReply(&message);
reply->set_reply_error();
Send(reply);
}
}
in_dispatch_--;
}
void PluginChannelBase::OnChannelConnected(int32 peer_pid) {
peer_pid_ = peer_pid;
}
void PluginChannelBase::AddRoute(int route_id,
IPC::Channel::Listener* listener,
bool npobject) {
if (npobject) {
npobject_listeners_[route_id] = listener;
} else {
plugin_count_++;
}
router_.AddRoute(route_id, listener);
}
void PluginChannelBase::RemoveRoute(int route_id) {
router_.RemoveRoute(route_id);
ListenerMap::iterator iter = npobject_listeners_.find(route_id);
if (iter != npobject_listeners_.end()) {
// This was an NPObject proxy or stub, it's not involved in the refcounting.
// If this RemoveRoute call from the NPObject is a result of us calling
// OnChannelError below, don't call erase() here because that'll corrupt
// the iterator below.
if (!in_remove_route_)
npobject_listeners_.erase(iter);
return;
}
plugin_count_--;
DCHECK(plugin_count_ >= 0);
if (!plugin_count_) {
ListenerMap::iterator npobj_iter = npobject_listeners_.begin();
in_remove_route_ = true;
while (npobj_iter != npobject_listeners_.end()) {
npobj_iter->second->OnChannelError();
npobj_iter++;
}
in_remove_route_ = false;
PluginChannelMap::iterator iter = g_plugin_channels_.begin();
while (iter != g_plugin_channels_.end()) {
if (iter->second == this) {
#if defined(OS_POSIX)
if (channel_valid()) {
IPC::RemoveAndCloseChannelSocket(channel_name());
}
#endif
g_plugin_channels_.erase(iter);
return;
}
iter++;
}
NOTREACHED();
}
}
void PluginChannelBase::OnControlMessageReceived(const IPC::Message& msg) {
NOTREACHED() <<
"should override in subclass if you care about control messages";
}
void PluginChannelBase::OnChannelError() {
#if defined(OS_POSIX)
if (channel_valid()) {
IPC::RemoveAndCloseChannelSocket(channel_name());
}
#endif
channel_valid_ = false;
}
void PluginChannelBase::SendUnblockingOnlyDuringDispatch() {
send_unblocking_only_during_dispatch_ = true;
}
<commit_msg>Potential fix for the PluginChannel::CleanUp crash. This will go out on tomorrow's dev channel build and we can see if the crashes go away while I try to write a repro.<commit_after>// Copyright (c) 2006-2008 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/plugin/plugin_channel_base.h"
#include "base/hash_tables.h"
#include "chrome/common/child_process.h"
#include "ipc/ipc_sync_message.h"
#if defined(OS_POSIX)
#include "ipc/ipc_channel_posix.h"
#endif
typedef base::hash_map<std::string, scoped_refptr<PluginChannelBase> >
PluginChannelMap;
static PluginChannelMap g_plugin_channels_;
PluginChannelBase* PluginChannelBase::GetChannel(
const std::string& channel_name, IPC::Channel::Mode mode,
PluginChannelFactory factory, MessageLoop* ipc_message_loop,
bool create_pipe_now) {
scoped_refptr<PluginChannelBase> channel;
PluginChannelMap::const_iterator iter = g_plugin_channels_.find(channel_name);
if (iter == g_plugin_channels_.end()) {
channel = factory();
} else {
channel = iter->second;
}
DCHECK(channel != NULL);
if (!channel->channel_valid()) {
channel->channel_name_ = channel_name;
channel->mode_ = mode;
if (channel->Init(ipc_message_loop, create_pipe_now)) {
g_plugin_channels_[channel_name] = channel;
} else {
channel = NULL;
}
}
return channel;
}
void PluginChannelBase::Broadcast(IPC::Message* message) {
for (PluginChannelMap::iterator iter = g_plugin_channels_.begin();
iter != g_plugin_channels_.end();
++iter) {
iter->second->Send(new IPC::Message(*message));
}
delete message;
}
PluginChannelBase::PluginChannelBase()
: plugin_count_(0),
peer_pid_(0),
in_remove_route_(false),
channel_valid_(false),
in_dispatch_(0),
send_unblocking_only_during_dispatch_(false) {
}
PluginChannelBase::~PluginChannelBase() {
}
void PluginChannelBase::CleanupChannels() {
// Make a copy of the references as we can't iterate the map since items will
// be removed from it as we clean them up.
std::vector<scoped_refptr<PluginChannelBase> > channels;
for (PluginChannelMap::const_iterator iter = g_plugin_channels_.begin();
iter != g_plugin_channels_.end();
++iter) {
channels.push_back(iter->second);
}
for (size_t i = 0; i < channels.size(); ++i)
channels[i]->CleanUp();
// This will clean up channels added to the map for which subsequent
// AddRoute wasn't called
g_plugin_channels_.clear();
}
bool PluginChannelBase::Init(MessageLoop* ipc_message_loop,
bool create_pipe_now) {
channel_.reset(new IPC::SyncChannel(
channel_name_, mode_, this, NULL, ipc_message_loop, create_pipe_now,
ChildProcess::current()->GetShutDownEvent()));
channel_valid_ = true;
return true;
}
bool PluginChannelBase::Send(IPC::Message* message) {
if (!channel_.get()) {
delete message;
return false;
}
if (send_unblocking_only_during_dispatch_ && in_dispatch_ == 0 &&
message->is_sync()) {
message->set_unblock(false);
}
return channel_->Send(message);
}
int PluginChannelBase::Count() {
return static_cast<int>(g_plugin_channels_.size());
}
void PluginChannelBase::OnMessageReceived(const IPC::Message& message) {
// This call might cause us to be deleted, so keep an extra reference to
// ourself so that we can send the reply and decrement back in_dispatch_.
scoped_refptr<PluginChannelBase> me(this);
in_dispatch_++;
if (message.routing_id() == MSG_ROUTING_CONTROL) {
OnControlMessageReceived(message);
} else {
bool routed = router_.RouteMessage(message);
if (!routed && message.is_sync()) {
// The listener has gone away, so we must respond or else the caller will
// hang waiting for a reply.
IPC::Message* reply = IPC::SyncMessage::GenerateReply(&message);
reply->set_reply_error();
Send(reply);
}
}
in_dispatch_--;
}
void PluginChannelBase::OnChannelConnected(int32 peer_pid) {
peer_pid_ = peer_pid;
}
void PluginChannelBase::AddRoute(int route_id,
IPC::Channel::Listener* listener,
bool npobject) {
if (npobject) {
npobject_listeners_[route_id] = listener;
} else {
plugin_count_++;
}
router_.AddRoute(route_id, listener);
}
void PluginChannelBase::RemoveRoute(int route_id) {
router_.RemoveRoute(route_id);
ListenerMap::iterator iter = npobject_listeners_.find(route_id);
if (iter != npobject_listeners_.end()) {
// This was an NPObject proxy or stub, it's not involved in the refcounting.
// If this RemoveRoute call from the NPObject is a result of us calling
// OnChannelError below, don't call erase() here because that'll corrupt
// the iterator below.
if (in_remove_route_) {
iter->second = NULL;
} else {
npobject_listeners_.erase(iter);
}
return;
}
plugin_count_--;
DCHECK(plugin_count_ >= 0);
if (!plugin_count_) {
ListenerMap::iterator npobj_iter = npobject_listeners_.begin();
in_remove_route_ = true;
while (npobj_iter != npobject_listeners_.end()) {
if (npobj_iter->second)
npobj_iter->second->OnChannelError();
npobj_iter++;
}
in_remove_route_ = false;
PluginChannelMap::iterator iter = g_plugin_channels_.begin();
while (iter != g_plugin_channels_.end()) {
if (iter->second == this) {
#if defined(OS_POSIX)
if (channel_valid()) {
IPC::RemoveAndCloseChannelSocket(channel_name());
}
#endif
g_plugin_channels_.erase(iter);
return;
}
iter++;
}
NOTREACHED();
}
}
void PluginChannelBase::OnControlMessageReceived(const IPC::Message& msg) {
NOTREACHED() <<
"should override in subclass if you care about control messages";
}
void PluginChannelBase::OnChannelError() {
#if defined(OS_POSIX)
if (channel_valid()) {
IPC::RemoveAndCloseChannelSocket(channel_name());
}
#endif
channel_valid_ = false;
}
void PluginChannelBase::SendUnblockingOnlyDuringDispatch() {
send_unblocking_only_during_dispatch_ = true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/user_script_slave.h"
#include "app/resource_bundle.h"
#include "base/histogram.h"
#include "base/logging.h"
#include "base/perftimer.h"
#include "base/pickle.h"
#include "base/shared_memory.h"
#include "base/string_util.h"
#include "chrome/renderer/extension_groups.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "grit/renderer_resources.h"
using WebKit::WebFrame;
using WebKit::WebString;
// These two strings are injected before and after the Greasemonkey API and
// user script to wrap it in an anonymous scope.
static const char kUserScriptHead[] = "(function (unsafeWindow) {\n";
static const char kUserScriptTail[] = "\n})(window);";
// Sets up the chrome.extension module. This may be run multiple times per
// context, but the init method deletes itself after the first time.
static const char kInitExtension[] =
"if (chrome.initExtension) chrome.initExtension('%s', true);";
int UserScriptSlave::GetIsolatedWorldId(const std::string& extension_id) {
typedef std::map<std::string, int> IsolatedWorldMap;
static IsolatedWorldMap g_isolated_world_ids;
static int g_next_isolated_world_id = 1;
IsolatedWorldMap::iterator iter = g_isolated_world_ids.find(extension_id);
if (iter != g_isolated_world_ids.end())
return iter->second;
int new_id = g_next_isolated_world_id;
++g_next_isolated_world_id;
// This map will tend to pile up over time, but realistically, you're never
// going to have enough extensions for it to matter.
g_isolated_world_ids[extension_id] = new_id;
return new_id;
}
UserScriptSlave::UserScriptSlave()
: shared_memory_(NULL),
script_deleter_(&scripts_) {
api_js_ = ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_GREASEMONKEY_API_JS);
}
bool UserScriptSlave::UpdateScripts(base::SharedMemoryHandle shared_memory) {
scripts_.clear();
// Create the shared memory object (read only).
shared_memory_.reset(new base::SharedMemory(shared_memory, true));
if (!shared_memory_.get())
return false;
// First get the size of the memory block.
if (!shared_memory_->Map(sizeof(Pickle::Header)))
return false;
Pickle::Header* pickle_header =
reinterpret_cast<Pickle::Header*>(shared_memory_->memory());
// Now map in the rest of the block.
int pickle_size = sizeof(Pickle::Header) + pickle_header->payload_size;
shared_memory_->Unmap();
if (!shared_memory_->Map(pickle_size))
return false;
// Unpickle scripts.
void* iter = NULL;
size_t num_scripts = 0;
Pickle pickle(reinterpret_cast<char*>(shared_memory_->memory()),
pickle_size);
pickle.ReadSize(&iter, &num_scripts);
scripts_.reserve(num_scripts);
for (size_t i = 0; i < num_scripts; ++i) {
scripts_.push_back(new UserScript());
UserScript* script = scripts_.back();
script->Unpickle(pickle, &iter);
// Note that this is a pointer into shared memory. We don't own it. It gets
// cleared up when the last renderer or browser process drops their
// reference to the shared memory.
for (size_t j = 0; j < script->js_scripts().size(); ++j) {
const char* body = NULL;
int body_length = 0;
CHECK(pickle.ReadData(&iter, &body, &body_length));
script->js_scripts()[j].set_external_content(
base::StringPiece(body, body_length));
}
for (size_t j = 0; j < script->css_scripts().size(); ++j) {
const char* body = NULL;
int body_length = 0;
CHECK(pickle.ReadData(&iter, &body, &body_length));
script->css_scripts()[j].set_external_content(
base::StringPiece(body, body_length));
}
}
return true;
}
// static
void UserScriptSlave::InsertInitExtensionCode(
std::vector<WebScriptSource>* sources, const std::string& extension_id) {
DCHECK(sources);
sources->insert(sources->begin(),
WebScriptSource(WebString::fromUTF8(
StringPrintf(kInitExtension, extension_id.c_str()))));
}
bool UserScriptSlave::InjectScripts(WebFrame* frame,
UserScript::RunLocation location) {
// Don't bother if this is not a URL we inject script into.
if (!URLPattern::IsValidScheme(GURL(frame->url()).scheme()))
return true;
PerfTimer timer;
int num_css = 0;
int num_scripts = 0;
for (size_t i = 0; i < scripts_.size(); ++i) {
std::vector<WebScriptSource> sources;
UserScript* script = scripts_[i];
if (!script->MatchesUrl(frame->url()))
continue; // This frame doesn't match the script url pattern, skip it.
// CSS files are always injected on document start before js scripts.
if (location == UserScript::DOCUMENT_START) {
num_css += script->css_scripts().size();
for (size_t j = 0; j < script->css_scripts().size(); ++j) {
PerfTimer insert_timer;
UserScript::File& file = script->css_scripts()[j];
frame->insertStyleText(
WebString::fromUTF8(file.GetContent().as_string()), WebString());
UMA_HISTOGRAM_TIMES("Extensions.InjectCssTime", insert_timer.Elapsed());
}
}
if (script->run_location() == location) {
num_scripts += script->js_scripts().size();
for (size_t j = 0; j < script->js_scripts().size(); ++j) {
UserScript::File &file = script->js_scripts()[j];
std::string content = file.GetContent().as_string();
// We add this dumb function wrapper for standalone user script to
// emulate what Greasemonkey does.
if (script->is_standalone()) {
content.insert(0, kUserScriptHead);
content += kUserScriptTail;
}
sources.push_back(
WebScriptSource(WebString::fromUTF8(content), file.url()));
}
}
if (!sources.empty()) {
int isolated_world_id = 0;
// Emulate Greasemonkey API for scripts that were converted to extensions
// and "standalone" user scripts.
if (script->is_standalone() || script->emulate_greasemonkey()) {
sources.insert(sources.begin(),
WebScriptSource(WebString::fromUTF8(api_js_.as_string())));
}
// Setup chrome.self to contain an Extension object with the correct
// ID.
if (!script->extension_id().empty()) {
InsertInitExtensionCode(&sources, script->extension_id());
isolated_world_id = GetIsolatedWorldId(script->extension_id());
}
PerfTimer exec_timer;
frame->executeScriptInIsolatedWorld(
isolated_world_id, &sources.front(), sources.size(),
EXTENSION_GROUP_CONTENT_SCRIPTS);
UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed());
}
}
// Log debug info.
if (location == UserScript::DOCUMENT_START) {
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectStart_CssCount", num_css);
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectStart_ScriptCount", num_scripts);
if (num_css || num_scripts)
UMA_HISTOGRAM_TIMES("Extensions.InjectStart_Time", timer.Elapsed());
} else if (location == UserScript::DOCUMENT_END) {
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectEnd_ScriptCount", num_scripts);
if (num_scripts)
UMA_HISTOGRAM_TIMES("Extensions.InjectEnd_Time", timer.Elapsed());
} else if (location == UserScript::DOCUMENT_IDLE) {
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectIdle_ScriptCount", num_scripts);
if (num_scripts)
UMA_HISTOGRAM_TIMES("Extensions.InjectIdle_Time", timer.Elapsed());
} else {
NOTREACHED();
}
LOG(INFO) << "Injected " << num_scripts << " scripts and " << num_css <<
"css files into " << frame->url().spec().data();
return true;
}
<commit_msg>Do not run user scripts on chrome.google.com<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/user_script_slave.h"
#include "app/resource_bundle.h"
#include "base/histogram.h"
#include "base/logging.h"
#include "base/perftimer.h"
#include "base/pickle.h"
#include "base/shared_memory.h"
#include "base/string_util.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/renderer/extension_groups.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "grit/renderer_resources.h"
using WebKit::WebFrame;
using WebKit::WebString;
// These two strings are injected before and after the Greasemonkey API and
// user script to wrap it in an anonymous scope.
static const char kUserScriptHead[] = "(function (unsafeWindow) {\n";
static const char kUserScriptTail[] = "\n})(window);";
// Sets up the chrome.extension module. This may be run multiple times per
// context, but the init method deletes itself after the first time.
static const char kInitExtension[] =
"if (chrome.initExtension) chrome.initExtension('%s', true);";
int UserScriptSlave::GetIsolatedWorldId(const std::string& extension_id) {
typedef std::map<std::string, int> IsolatedWorldMap;
static IsolatedWorldMap g_isolated_world_ids;
static int g_next_isolated_world_id = 1;
IsolatedWorldMap::iterator iter = g_isolated_world_ids.find(extension_id);
if (iter != g_isolated_world_ids.end())
return iter->second;
int new_id = g_next_isolated_world_id;
++g_next_isolated_world_id;
// This map will tend to pile up over time, but realistically, you're never
// going to have enough extensions for it to matter.
g_isolated_world_ids[extension_id] = new_id;
return new_id;
}
UserScriptSlave::UserScriptSlave()
: shared_memory_(NULL),
script_deleter_(&scripts_) {
api_js_ = ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_GREASEMONKEY_API_JS);
}
bool UserScriptSlave::UpdateScripts(base::SharedMemoryHandle shared_memory) {
scripts_.clear();
// Create the shared memory object (read only).
shared_memory_.reset(new base::SharedMemory(shared_memory, true));
if (!shared_memory_.get())
return false;
// First get the size of the memory block.
if (!shared_memory_->Map(sizeof(Pickle::Header)))
return false;
Pickle::Header* pickle_header =
reinterpret_cast<Pickle::Header*>(shared_memory_->memory());
// Now map in the rest of the block.
int pickle_size = sizeof(Pickle::Header) + pickle_header->payload_size;
shared_memory_->Unmap();
if (!shared_memory_->Map(pickle_size))
return false;
// Unpickle scripts.
void* iter = NULL;
size_t num_scripts = 0;
Pickle pickle(reinterpret_cast<char*>(shared_memory_->memory()),
pickle_size);
pickle.ReadSize(&iter, &num_scripts);
scripts_.reserve(num_scripts);
for (size_t i = 0; i < num_scripts; ++i) {
scripts_.push_back(new UserScript());
UserScript* script = scripts_.back();
script->Unpickle(pickle, &iter);
// Note that this is a pointer into shared memory. We don't own it. It gets
// cleared up when the last renderer or browser process drops their
// reference to the shared memory.
for (size_t j = 0; j < script->js_scripts().size(); ++j) {
const char* body = NULL;
int body_length = 0;
CHECK(pickle.ReadData(&iter, &body, &body_length));
script->js_scripts()[j].set_external_content(
base::StringPiece(body, body_length));
}
for (size_t j = 0; j < script->css_scripts().size(); ++j) {
const char* body = NULL;
int body_length = 0;
CHECK(pickle.ReadData(&iter, &body, &body_length));
script->css_scripts()[j].set_external_content(
base::StringPiece(body, body_length));
}
}
return true;
}
// static
void UserScriptSlave::InsertInitExtensionCode(
std::vector<WebScriptSource>* sources, const std::string& extension_id) {
DCHECK(sources);
sources->insert(sources->begin(),
WebScriptSource(WebString::fromUTF8(
StringPrintf(kInitExtension, extension_id.c_str()))));
}
bool UserScriptSlave::InjectScripts(WebFrame* frame,
UserScript::RunLocation location) {
GURL frame_url = GURL(frame->url());
// Don't bother if this is not a URL we inject script into.
if (!URLPattern::IsValidScheme(frame_url.scheme()))
return true;
// Don't inject user scripts into the gallery itself. This prevents
// a user script from removing the "report abuse" link, for example.
if (frame_url.host() == GURL(Extension::kGalleryBrowseUrl).host())
return true;
PerfTimer timer;
int num_css = 0;
int num_scripts = 0;
for (size_t i = 0; i < scripts_.size(); ++i) {
std::vector<WebScriptSource> sources;
UserScript* script = scripts_[i];
if (!script->MatchesUrl(frame->url()))
continue; // This frame doesn't match the script url pattern, skip it.
// CSS files are always injected on document start before js scripts.
if (location == UserScript::DOCUMENT_START) {
num_css += script->css_scripts().size();
for (size_t j = 0; j < script->css_scripts().size(); ++j) {
PerfTimer insert_timer;
UserScript::File& file = script->css_scripts()[j];
frame->insertStyleText(
WebString::fromUTF8(file.GetContent().as_string()), WebString());
UMA_HISTOGRAM_TIMES("Extensions.InjectCssTime", insert_timer.Elapsed());
}
}
if (script->run_location() == location) {
num_scripts += script->js_scripts().size();
for (size_t j = 0; j < script->js_scripts().size(); ++j) {
UserScript::File &file = script->js_scripts()[j];
std::string content = file.GetContent().as_string();
// We add this dumb function wrapper for standalone user script to
// emulate what Greasemonkey does.
if (script->is_standalone()) {
content.insert(0, kUserScriptHead);
content += kUserScriptTail;
}
sources.push_back(
WebScriptSource(WebString::fromUTF8(content), file.url()));
}
}
if (!sources.empty()) {
int isolated_world_id = 0;
// Emulate Greasemonkey API for scripts that were converted to extensions
// and "standalone" user scripts.
if (script->is_standalone() || script->emulate_greasemonkey()) {
sources.insert(sources.begin(),
WebScriptSource(WebString::fromUTF8(api_js_.as_string())));
}
// Setup chrome.self to contain an Extension object with the correct
// ID.
if (!script->extension_id().empty()) {
InsertInitExtensionCode(&sources, script->extension_id());
isolated_world_id = GetIsolatedWorldId(script->extension_id());
}
PerfTimer exec_timer;
frame->executeScriptInIsolatedWorld(
isolated_world_id, &sources.front(), sources.size(),
EXTENSION_GROUP_CONTENT_SCRIPTS);
UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed());
}
}
// Log debug info.
if (location == UserScript::DOCUMENT_START) {
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectStart_CssCount", num_css);
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectStart_ScriptCount", num_scripts);
if (num_css || num_scripts)
UMA_HISTOGRAM_TIMES("Extensions.InjectStart_Time", timer.Elapsed());
} else if (location == UserScript::DOCUMENT_END) {
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectEnd_ScriptCount", num_scripts);
if (num_scripts)
UMA_HISTOGRAM_TIMES("Extensions.InjectEnd_Time", timer.Elapsed());
} else if (location == UserScript::DOCUMENT_IDLE) {
UMA_HISTOGRAM_COUNTS_100("Extensions.InjectIdle_ScriptCount", num_scripts);
if (num_scripts)
UMA_HISTOGRAM_TIMES("Extensions.InjectIdle_Time", timer.Elapsed());
} else {
NOTREACHED();
}
LOG(INFO) << "Injected " << num_scripts << " scripts and " << num_css <<
"css files into " << frame->url().spec().data();
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
static const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:8000/");
static const FilePath::CharType kStartFile[] =
FILE_PATH_LITERAL("dom_checker.html");
const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test";
class DomCheckerTest : public UITest {
public:
DomCheckerTest() {
dom_automation_enabled_ = true;
enable_file_cookies_ = false;
show_window_ = true;
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
typedef std::list<std::string> ResultsList;
typedef std::set<std::string> ResultsSet;
void RunTest(bool use_http, ResultsList* new_passes,
ResultsList* new_failures) {
int test_count = 0;
ResultsSet expected_failures, current_failures;
std::string failures_file = use_http ?
"expected_failures-http.txt" : "expected_failures-file.txt";
GetExpectedFailures(failures_file, &expected_failures);
RunDomChecker(use_http, &test_count, ¤t_failures);
printf("\nTests run: %d\n", test_count);
// Compute the list of new passes and failures.
CompareSets(current_failures, expected_failures, new_passes);
CompareSets(expected_failures, current_failures, new_failures);
}
void PrintResults(const ResultsList& new_passes,
const ResultsList& new_failures) {
PrintResults(new_failures, "new tests failing", true);
PrintResults(new_passes, "new tests passing", false);
}
private:
void PrintResults(const ResultsList& results, const char* message,
bool add_failure) {
if (!results.empty()) {
if (add_failure)
ADD_FAILURE();
printf("%s:\n", message);
ResultsList::const_iterator it = results.begin();
for (; it != results.end(); ++it)
printf(" %s\n", it->c_str());
printf("\n");
}
}
// Find the elements of "b" that are not in "a".
void CompareSets(const ResultsSet& a, const ResultsSet& b,
ResultsList* only_in_b) {
ResultsSet::const_iterator it = b.begin();
for (; it != b.end(); ++it) {
if (a.find(*it) == a.end())
only_in_b->push_back(*it);
}
}
// Return the path to the DOM checker directory on the local filesystem.
FilePath GetDomCheckerDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dom_checker");
}
bool ReadExpectedResults(const std::string& failures_file,
std::string* results) {
FilePath results_path = GetDomCheckerDir();
results_path = results_path.AppendASCII(failures_file);
return file_util::ReadFileToString(results_path, results);
}
void ParseExpectedFailures(const std::string& input, ResultsSet* output) {
if (input.empty())
return;
std::vector<std::string> tokens;
SplitString(input, '\n', &tokens);
std::vector<std::string>::const_iterator it = tokens.begin();
for (; it != tokens.end(); ++it) {
// Allow comments (lines that start with #).
if (it->length() > 0 && it->at(0) != '#')
output->insert(*it);
}
}
void GetExpectedFailures(const std::string& failures_file,
ResultsSet* expected_failures) {
std::string expected_failures_text;
bool have_expected_results = ReadExpectedResults(failures_file,
&expected_failures_text);
ASSERT_TRUE(have_expected_results);
ParseExpectedFailures(expected_failures_text, expected_failures);
}
bool WaitUntilTestCompletes(TabProxy* tab) {
return WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send(automation.IsDone());",
1000, UITest::test_timeout_ms());
}
bool GetTestCount(TabProxy* tab, int* test_count) {
return tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send(automation.GetTestCount());",
test_count);
}
bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetFailures()));",
&json_wide);
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
JSONStringValueSerializer deserializer(json);
scoped_ptr<Value> value(deserializer.Deserialize(NULL));
EXPECT_TRUE(value.get());
if (!value.get())
return false;
EXPECT_TRUE(value->IsType(Value::TYPE_LIST));
if (!value->IsType(Value::TYPE_LIST))
return false;
ListValue* list_value = static_cast<ListValue*>(value.get());
// The parsed JSON object will be an array of strings, each of which is a
// test failure. Add those strings to the results set.
ListValue::const_iterator it = list_value->begin();
for (; it != list_value->end(); ++it) {
EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING));
if ((*it)->IsType(Value::TYPE_STRING)) {
std::string test_name;
succeeded = (*it)->GetAsString(&test_name);
EXPECT_TRUE(succeeded);
if (succeeded)
tests_failed->insert(test_name);
}
}
return true;
}
void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) {
GURL test_url;
FilePath::StringType start_file(kStartFile);
if (use_http) {
FilePath::StringType url_string(kBaseUrl);
url_string.append(start_file);
test_url = GURL(url_string);
} else {
FilePath test_path = GetDomCheckerDir();
test_path = test_path.Append(start_file);
test_url = net::FilePathToFileURL(test_path);
}
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get()));
// Get the test results.
ASSERT_TRUE(GetTestCount(tab.get(), test_count));
ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed));
ASSERT_GT(*test_count, 0);
}
};
} // namespace
TEST_F(DomCheckerTest, File) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(false, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
TEST_F(DomCheckerTest, Http) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(true, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
<commit_msg>Style issues: - Fix indentation. - Reorder typedefs according to style guide. - Add DISALLOW_COPY_AND_ASSIGN. Review URL: http://codereview.chromium.org/42322<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
static const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:8000/");
static const FilePath::CharType kStartFile[] =
FILE_PATH_LITERAL("dom_checker.html");
const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test";
class DomCheckerTest : public UITest {
public:
typedef std::list<std::string> ResultsList;
typedef std::set<std::string> ResultsSet;
DomCheckerTest() {
dom_automation_enabled_ = true;
enable_file_cookies_ = false;
show_window_ = true;
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
void RunTest(bool use_http, ResultsList* new_passes,
ResultsList* new_failures) {
int test_count = 0;
ResultsSet expected_failures, current_failures;
std::string failures_file = use_http ?
"expected_failures-http.txt" : "expected_failures-file.txt";
GetExpectedFailures(failures_file, &expected_failures);
RunDomChecker(use_http, &test_count, ¤t_failures);
printf("\nTests run: %d\n", test_count);
// Compute the list of new passes and failures.
CompareSets(current_failures, expected_failures, new_passes);
CompareSets(expected_failures, current_failures, new_failures);
}
void PrintResults(const ResultsList& new_passes,
const ResultsList& new_failures) {
PrintResults(new_failures, "new tests failing", true);
PrintResults(new_passes, "new tests passing", false);
}
private:
void PrintResults(const ResultsList& results, const char* message,
bool add_failure) {
if (!results.empty()) {
if (add_failure)
ADD_FAILURE();
printf("%s:\n", message);
ResultsList::const_iterator it = results.begin();
for (; it != results.end(); ++it)
printf(" %s\n", it->c_str());
printf("\n");
}
}
// Find the elements of "b" that are not in "a".
void CompareSets(const ResultsSet& a, const ResultsSet& b,
ResultsList* only_in_b) {
ResultsSet::const_iterator it = b.begin();
for (; it != b.end(); ++it) {
if (a.find(*it) == a.end())
only_in_b->push_back(*it);
}
}
// Return the path to the DOM checker directory on the local filesystem.
FilePath GetDomCheckerDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dom_checker");
}
bool ReadExpectedResults(const std::string& failures_file,
std::string* results) {
FilePath results_path = GetDomCheckerDir();
results_path = results_path.AppendASCII(failures_file);
return file_util::ReadFileToString(results_path, results);
}
void ParseExpectedFailures(const std::string& input, ResultsSet* output) {
if (input.empty())
return;
std::vector<std::string> tokens;
SplitString(input, '\n', &tokens);
std::vector<std::string>::const_iterator it = tokens.begin();
for (; it != tokens.end(); ++it) {
// Allow comments (lines that start with #).
if (it->length() > 0 && it->at(0) != '#')
output->insert(*it);
}
}
void GetExpectedFailures(const std::string& failures_file,
ResultsSet* expected_failures) {
std::string expected_failures_text;
bool have_expected_results = ReadExpectedResults(failures_file,
&expected_failures_text);
ASSERT_TRUE(have_expected_results);
ParseExpectedFailures(expected_failures_text, expected_failures);
}
bool WaitUntilTestCompletes(TabProxy* tab) {
return WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send(automation.IsDone());",
1000, UITest::test_timeout_ms());
}
bool GetTestCount(TabProxy* tab, int* test_count) {
return tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send(automation.GetTestCount());",
test_count);
}
bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetFailures()));",
&json_wide);
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
JSONStringValueSerializer deserializer(json);
scoped_ptr<Value> value(deserializer.Deserialize(NULL));
EXPECT_TRUE(value.get());
if (!value.get())
return false;
EXPECT_TRUE(value->IsType(Value::TYPE_LIST));
if (!value->IsType(Value::TYPE_LIST))
return false;
ListValue* list_value = static_cast<ListValue*>(value.get());
// The parsed JSON object will be an array of strings, each of which is a
// test failure. Add those strings to the results set.
ListValue::const_iterator it = list_value->begin();
for (; it != list_value->end(); ++it) {
EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING));
if ((*it)->IsType(Value::TYPE_STRING)) {
std::string test_name;
succeeded = (*it)->GetAsString(&test_name);
EXPECT_TRUE(succeeded);
if (succeeded)
tests_failed->insert(test_name);
}
}
return true;
}
void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) {
GURL test_url;
FilePath::StringType start_file(kStartFile);
if (use_http) {
FilePath::StringType url_string(kBaseUrl);
url_string.append(start_file);
test_url = GURL(url_string);
} else {
FilePath test_path = GetDomCheckerDir();
test_path = test_path.Append(start_file);
test_url = net::FilePathToFileURL(test_path);
}
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get()));
// Get the test results.
ASSERT_TRUE(GetTestCount(tab.get(), test_count));
ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed));
ASSERT_GT(*test_count, 0);
}
DISALLOW_COPY_AND_ASSIGN(DomCheckerTest);
};
} // namespace
TEST_F(DomCheckerTest, File) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(false, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
TEST_F(DomCheckerTest, Http) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(true, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2004, 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
class RandomUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testSetGlobal();
void testGetData();
private:
QCA::Initializer* m_init;
};
void RandomUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
#include "../fixpaths.include"
}
void RandomUnitTest::cleanupTestCase()
{
delete m_init;
}
void RandomUnitTest::testSetGlobal()
{
QCA::Random rng = QCA::globalRNG( );
QCOMPARE( rng.provider()->name(), QString( "qca-botan" ) );
QCA::setGlobalRNG( "default" );
rng = QCA::globalRNG( );
QCOMPARE( rng.provider()->name(), QString( "default" ) );
QCA::setGlobalRNG( "qca-botan" );
QCA::Random rng1 = QCA::globalRNG();
QCOMPARE( rng1.provider()->name(), QString( "qca-botan" ) );
}
void RandomUnitTest::testGetData()
{
QStringList providersToTest;
providersToTest.append("default");
providersToTest.append("qca-botan");
foreach(QString provider, providersToTest) {
QCA::Random randObject (provider);
QCOMPARE( randObject.nextByte() == randObject.nextByte(), false );
QCOMPARE( QCA::Random().nextByte() == QCA::Random().nextByte(), false );
QCOMPARE( randObject.nextBytes(4) == randObject.nextBytes(4), false );
QCOMPARE( randObject.nextBytes(100) == randObject.nextBytes(100), false );
QCOMPARE( randObject.randomChar() == randObject.randomChar(), false );
QCOMPARE( QCA::Random().randomChar() == QCA::Random().randomChar(), false );
QCOMPARE( QCA::Random::randomChar() == QCA::Random::randomChar(), false );
QCOMPARE( QCA::Random().randomInt() == QCA::Random().randomInt(), false );
QCOMPARE( QCA::Random::randomInt() == QCA::Random::randomInt(), false );
QCOMPARE( QCA::Random().randomArray(3) == QCA::Random().randomArray(3), false );
QCOMPARE( QCA::Random::randomArray(3) == QCA::Random::randomArray(3), false );
QCOMPARE( randObject.nextByte(QCA::Random::Nonce) == randObject.nextByte(QCA::Random::SessionKey), false );
QCOMPARE( QCA::Random().nextByte(QCA::Random::PublicValue) == QCA::Random().nextByte(), false );
QCOMPARE( randObject.nextBytes(4) == randObject.nextBytes(4, QCA::Random::Nonce), false );
QCOMPARE( randObject.randomChar(QCA::Random::LongTermKey) == randObject.randomChar(), false );
QCOMPARE( QCA::Random().randomChar() == QCA::Random().randomChar(QCA::Random::PublicValue), false );
QCOMPARE( QCA::Random::randomChar(QCA::Random::PublicValue) == QCA::Random::randomChar(QCA::Random::Nonce), false );
QCOMPARE( QCA::Random().randomInt(QCA::Random::Nonce) == QCA::Random().randomInt(), false );
QCOMPARE( QCA::Random::randomInt(QCA::Random::Nonce) == QCA::Random::randomInt(QCA::Random::Nonce), false );
QCOMPARE( QCA::Random().randomArray(3, QCA::Random::Nonce) == QCA::Random().randomArray(3), false );
QCOMPARE( QCA::Random::randomArray(3, QCA::Random::SessionKey) == QCA::Random::randomArray(3, QCA::Random::PublicValue), false );
for (int len = 1; len <= 1024; len*=2 ) {
QCOMPARE( QCA::globalRNG().nextBytes(len, QCA::Random::SessionKey).size(), len );
}
}
}
QTEST_MAIN(RandomUnitTest)
#include "randomunittest.moc"
<commit_msg>Test the built in provider normally, and only test the botan RNG if available.<commit_after>/**
* Copyright (C) 2004, 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
class RandomUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testSetGlobal();
void testGetData();
private:
QCA::Initializer* m_init;
};
void RandomUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
#include "../fixpaths.include"
}
void RandomUnitTest::cleanupTestCase()
{
delete m_init;
}
void RandomUnitTest::testSetGlobal()
{
QCA::setGlobalRNG( "default" );
QCA::Random rng = QCA::globalRNG( );
QCOMPARE( rng.provider()->name(), QString( "default" ) );
// Only check this if we have the Botan provider
if ( QCA::findProvider( "qca-botan" ) ) {
QCA::setGlobalRNG( "qca-botan" );
QCA::Random rng1 = QCA::globalRNG();
QCOMPARE( rng1.provider()->name(), QString( "qca-botan" ) );
}
}
void RandomUnitTest::testGetData()
{
QStringList providersToTest;
providersToTest.append("default");
providersToTest.append("qca-botan");
foreach(QString provider, providersToTest) {
QCA::Random randObject (provider);
QCOMPARE( randObject.nextByte() == randObject.nextByte(), false );
QCOMPARE( QCA::Random().nextByte() == QCA::Random().nextByte(), false );
QCOMPARE( randObject.nextBytes(4) == randObject.nextBytes(4), false );
QCOMPARE( randObject.nextBytes(100) == randObject.nextBytes(100), false );
QCOMPARE( randObject.randomChar() == randObject.randomChar(), false );
QCOMPARE( QCA::Random().randomChar() == QCA::Random().randomChar(), false );
QCOMPARE( QCA::Random::randomChar() == QCA::Random::randomChar(), false );
QCOMPARE( QCA::Random().randomInt() == QCA::Random().randomInt(), false );
QCOMPARE( QCA::Random::randomInt() == QCA::Random::randomInt(), false );
QCOMPARE( QCA::Random().randomArray(3) == QCA::Random().randomArray(3), false );
QCOMPARE( QCA::Random::randomArray(3) == QCA::Random::randomArray(3), false );
QCOMPARE( randObject.nextByte(QCA::Random::Nonce) == randObject.nextByte(QCA::Random::SessionKey), false );
QCOMPARE( QCA::Random().nextByte(QCA::Random::PublicValue) == QCA::Random().nextByte(), false );
QCOMPARE( randObject.nextBytes(4) == randObject.nextBytes(4, QCA::Random::Nonce), false );
QCOMPARE( randObject.randomChar(QCA::Random::LongTermKey) == randObject.randomChar(), false );
QCOMPARE( QCA::Random().randomChar() == QCA::Random().randomChar(QCA::Random::PublicValue), false );
QCOMPARE( QCA::Random::randomChar(QCA::Random::PublicValue) == QCA::Random::randomChar(QCA::Random::Nonce), false );
QCOMPARE( QCA::Random().randomInt(QCA::Random::Nonce) == QCA::Random().randomInt(), false );
QCOMPARE( QCA::Random::randomInt(QCA::Random::Nonce) == QCA::Random::randomInt(QCA::Random::Nonce), false );
QCOMPARE( QCA::Random().randomArray(3, QCA::Random::Nonce) == QCA::Random().randomArray(3), false );
QCOMPARE( QCA::Random::randomArray(3, QCA::Random::SessionKey) == QCA::Random::randomArray(3, QCA::Random::PublicValue), false );
for (int len = 1; len <= 1024; len*=2 ) {
QCOMPARE( QCA::globalRNG().nextBytes(len, QCA::Random::SessionKey).size(), len );
}
}
}
QTEST_MAIN(RandomUnitTest)
#include "randomunittest.moc"
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "chrome_frame/chrome_launcher.h"
// We want to keep this EXE tiny, so we avoid all dependencies and link to no
// libraries, and we do not use the C runtime.
//
// To catch errors in debug builds, we define an extremely simple assert macro.
#ifndef NDEBUG
#define CLM_ASSERT(x) do { if (!(x)) { ::DebugBreak(); } } while (false)
#else
#define CLM_ASSERT(x)
#endif // NDEBUG
// In release builds, we skip the standard library completely to minimize
// size. This is more work in debug builds, and unnecessary, hence the
// different signatures.
#ifndef NDEBUG
int APIENTRY wWinMain(HINSTANCE, HINSTANCE, wchar_t*, int) {
#else
extern "C" void __cdecl WinMainCRTStartup() {
#endif // NDEBUG
// This relies on the chrome_launcher.exe residing in the same directory
// as our DLL. We build a full path to avoid loading it from any other
// directory in the DLL search path.
//
// The code is a bit verbose because we can't use the standard library.
const wchar_t kBaseName[] = L"npchrome_tab.dll";
wchar_t file_path[MAX_PATH + (sizeof(kBaseName) / sizeof(kBaseName[0])) + 1];
file_path[0] = L'\0';
::GetModuleFileName(::GetModuleHandle(NULL), file_path, MAX_PATH);
// Find index of last slash, and null-terminate the string after it.
//
// Proof for security purposes, since we can't use the safe string
// manipulation functions from the runtime:
// - File_path is always null-terminated, by us initially and by
// ::GetModuleFileName if it puts anything into the buffer.
// - If there is no slash in the path then it's a relative path, not an
// absolute one, and the code ends up creating a relative path to
// npchrome_tab.dll.
// - It's safe to use lstrcatW since we know the maximum length of both
// parts we are concatenating, and we know the buffer will fit them in
// the worst case.
int slash_index = lstrlenW(file_path);
// Invariant: 0 <= slash_index < MAX_PATH
CLM_ASSERT(slash_index > 0);
while (slash_index > 0 && file_path[slash_index] != L'\\')
--slash_index;
// Invariant: 0 <= slash_index < MAX_PATH and it is either the index of
// the last \ in the path, or 0.
if (slash_index != 0)
++slash_index; // don't remove the last '\'
file_path[slash_index] = L'\0';
lstrcatW(file_path, kBaseName);
UINT exit_code = ERROR_FILE_NOT_FOUND;
HMODULE chrome_tab = ::LoadLibrary(file_path);
CLM_ASSERT(chrome_tab);
if (chrome_tab) {
chrome_launcher::CfLaunchChromeProc proc =
reinterpret_cast<chrome_launcher::CfLaunchChromeProc>(
::GetProcAddress(chrome_tab, "CfLaunchChrome"));
CLM_ASSERT(proc);
if (proc) {
exit_code = proc();
} else {
exit_code = ERROR_INVALID_FUNCTION;
}
::FreeLibrary(chrome_tab);
}
::ExitProcess(exit_code);
}
<commit_msg>Setting the SVN eol style to LF on chrome frame sources<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "chrome_frame/chrome_launcher.h"
// We want to keep this EXE tiny, so we avoid all dependencies and link to no
// libraries, and we do not use the C runtime.
//
// To catch errors in debug builds, we define an extremely simple assert macro.
#ifndef NDEBUG
#define CLM_ASSERT(x) do { if (!(x)) { ::DebugBreak(); } } while (false)
#else
#define CLM_ASSERT(x)
#endif // NDEBUG
// In release builds, we skip the standard library completely to minimize
// size. This is more work in debug builds, and unnecessary, hence the
// different signatures.
#ifndef NDEBUG
int APIENTRY wWinMain(HINSTANCE, HINSTANCE, wchar_t*, int) {
#else
extern "C" void __cdecl WinMainCRTStartup() {
#endif // NDEBUG
// This relies on the chrome_launcher.exe residing in the same directory
// as our DLL. We build a full path to avoid loading it from any other
// directory in the DLL search path.
//
// The code is a bit verbose because we can't use the standard library.
const wchar_t kBaseName[] = L"npchrome_tab.dll";
wchar_t file_path[MAX_PATH + (sizeof(kBaseName) / sizeof(kBaseName[0])) + 1];
file_path[0] = L'\0';
::GetModuleFileName(::GetModuleHandle(NULL), file_path, MAX_PATH);
// Find index of last slash, and null-terminate the string after it.
//
// Proof for security purposes, since we can't use the safe string
// manipulation functions from the runtime:
// - File_path is always null-terminated, by us initially and by
// ::GetModuleFileName if it puts anything into the buffer.
// - If there is no slash in the path then it's a relative path, not an
// absolute one, and the code ends up creating a relative path to
// npchrome_tab.dll.
// - It's safe to use lstrcatW since we know the maximum length of both
// parts we are concatenating, and we know the buffer will fit them in
// the worst case.
int slash_index = lstrlenW(file_path);
// Invariant: 0 <= slash_index < MAX_PATH
CLM_ASSERT(slash_index > 0);
while (slash_index > 0 && file_path[slash_index] != L'\\')
--slash_index;
// Invariant: 0 <= slash_index < MAX_PATH and it is either the index of
// the last \ in the path, or 0.
if (slash_index != 0)
++slash_index; // don't remove the last '\'
file_path[slash_index] = L'\0';
lstrcatW(file_path, kBaseName);
UINT exit_code = ERROR_FILE_NOT_FOUND;
HMODULE chrome_tab = ::LoadLibrary(file_path);
CLM_ASSERT(chrome_tab);
if (chrome_tab) {
chrome_launcher::CfLaunchChromeProc proc =
reinterpret_cast<chrome_launcher::CfLaunchChromeProc>(
::GetProcAddress(chrome_tab, "CfLaunchChrome"));
CLM_ASSERT(proc);
if (proc) {
exit_code = proc();
} else {
exit_code = ERROR_INVALID_FUNCTION;
}
::FreeLibrary(chrome_tab);
}
::ExitProcess(exit_code);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MetaExportComponent.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2006-09-17 10:38:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_METAEXPORTCOMPONENT_HXX
#include "MetaExportComponent.hxx"
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP
#include <com/sun/star/uno/Exception.hpp>
#endif
// #110680#
//#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
//#include <comphelper/processfactory.hxx>
//#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmlmetae.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::xmloff::token;
// #110680#
XMLMetaExportComponent::XMLMetaExportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
sal_uInt16 nFlags )
: SvXMLExport( xServiceFactory, MAP_INCH, XML_META, nFlags )
{
}
XMLMetaExportComponent::~XMLMetaExportComponent()
{
}
sal_uInt32 XMLMetaExportComponent::exportDoc( enum XMLTokenEnum )
{
GetDocHandler()->startDocument();
{
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_DC ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_DC ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_META ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_META ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_OFFICE ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_OFFICE ) );
SvXMLElementExport aDocElem( *this, XML_NAMESPACE_OFFICE, XML_DOCUMENT_META,
sal_True, sal_True );
{
SvXMLElementExport aElem( *this, XML_NAMESPACE_OFFICE, XML_META,
sal_True, sal_True );
SfxXMLMetaExport aMeta( *this, GetModel() );
aMeta.Export();
}
}
GetDocHandler()->endDocument();
return 0;
}
// methods without content:
void XMLMetaExportComponent::_ExportAutoStyles() {}
void XMLMetaExportComponent::_ExportMasterStyles() {}
void XMLMetaExportComponent::_ExportContent() {}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportComponent_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLOasisMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportComponent_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportComponent" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportComponent_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_ALL|EXPORT_OASIS);
}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportOOO_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportOOO_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportOOo" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportOOO_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_ALL);
}
<commit_msg>INTEGRATION: CWS fwk53 (1.14.18); FILE MERGED 2006/10/16 10:44:11 mav 1.14.18.1: #i68682# fix meta.xml reader/writer<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MetaExportComponent.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: vg $ $Date: 2006-11-01 14:50:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_METAEXPORTCOMPONENT_HXX
#include "MetaExportComponent.hxx"
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
// #110680#
//#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
//#include <comphelper/processfactory.hxx>
//#endif
#ifndef _COMPHELPER_GENERICPROPERTYSET_HXX_
#include <comphelper/genericpropertyset.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmlmetae.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMERGER_HXX_
#include "PropertySetMerger.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::xmloff::token;
// #110680#
XMLMetaExportComponent::XMLMetaExportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
sal_uInt16 nFlags )
: SvXMLExport( xServiceFactory, MAP_INCH, XML_TEXT, nFlags )
{
}
XMLMetaExportComponent::~XMLMetaExportComponent()
{
}
void SAL_CALL XMLMetaExportComponent::setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
try
{
SvXMLExport::setSourceDocument( xDoc );
}
catch( lang::IllegalArgumentException& )
{
// allow to use document info service without model access
// this is required for standalone document info exporter
xDocInfo = uno::Reference< document::XDocumentInfo >::query( xDoc );
if( !xDocInfo.is() )
throw lang::IllegalArgumentException();
}
}
sal_uInt32 XMLMetaExportComponent::exportDoc( enum XMLTokenEnum )
{
uno::Reference< xml::sax::XDocumentHandler > xDocHandler = GetDocHandler();
if( (getExportFlags() & EXPORT_OASIS) == 0 )
{
uno::Reference< lang::XMultiServiceFactory > xFactory = getServiceFactory();
if( xFactory.is() )
{
try
{
::comphelper::PropertyMapEntry aInfoMap[] =
{
{ "Class", sizeof("Class")-1, 0,
&::getCppuType((::rtl::OUString*)0),
beans::PropertyAttribute::MAYBEVOID, 0},
{ NULL, 0, 0, NULL, 0, 0 }
};
uno::Reference< beans::XPropertySet > xConvPropSet(
::comphelper::GenericPropertySet_CreateInstance(
new ::comphelper::PropertySetInfo( aInfoMap ) ) );
uno::Any aAny;
aAny <<= GetXMLToken( XML_TEXT );
xConvPropSet->setPropertyValue(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Class")), aAny );
uno::Reference< beans::XPropertySet > xPropSet =
getExportInfo().is()
? PropertySetMerger_CreateInstance( getExportInfo(),
xConvPropSet )
: getExportInfo();
uno::Sequence< uno::Any > aArgs( 3 );
aArgs[0] <<= xDocHandler;
aArgs[1] <<= xPropSet;
aArgs[2] <<= GetModel();
// get filter component
xDocHandler = uno::Reference< xml::sax::XDocumentHandler >(
xFactory->createInstanceWithArguments(
::rtl::OUString::createFromAscii("com.sun.star.comp.Oasis2OOoTransformer"),
aArgs),
uno::UNO_QUERY_THROW );
SetDocHandler( xDocHandler );
}
catch( com::sun::star::uno::Exception& )
{
OSL_ENSURE( sal_False, "Can not intantiate com.sun.star.comp.Oasis2OOoTransformer!\n");
}
}
}
xDocHandler->startDocument();
{
#if 0
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_DC ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_DC ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_META ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_META ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_OFFICE ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_OFFICE ) );
#else
sal_uInt16 nPos = GetNamespaceMap().GetFirstKey();
while( USHRT_MAX != nPos )
{
GetAttrList().AddAttribute( GetNamespaceMap().GetAttrNameByKey( nPos ), GetNamespaceMap().GetNameByKey( nPos ) );
nPos = GetNamespaceMap().GetNextKey( nPos );
}
#endif
AddAttribute( XML_NAMESPACE_OFFICE, XML_VERSION, ::rtl::OUString::createFromAscii( "1.0" ) );
SvXMLElementExport aDocElem( *this, XML_NAMESPACE_OFFICE, XML_DOCUMENT_META,
sal_True, sal_True );
{
SvXMLElementExport aElem( *this, XML_NAMESPACE_OFFICE, XML_META,
sal_True, sal_True );
if ( xDocInfo.is() )
{
// standalone document exporter case
SfxXMLMetaExport aMeta( *this, xDocInfo );
aMeta.Export();
}
else
{
SfxXMLMetaExport aMeta( *this, GetModel() );
aMeta.Export();
}
}
}
xDocHandler->endDocument();
return 0;
}
// methods without content:
void XMLMetaExportComponent::_ExportAutoStyles() {}
void XMLMetaExportComponent::_ExportMasterStyles() {}
void XMLMetaExportComponent::_ExportContent() {}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportComponent_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLOasisMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportComponent_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportComponent" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportComponent_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_META|EXPORT_OASIS);
}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportOOO_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportOOO_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportOOo" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportOOO_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_META);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/ui/browser.h"
#include "content/public/browser/render_view_host.h"
#include "webkit/glue/webpreferences.h"
// Tests that GPU-related WebKit preferences are set for extension background
// pages. See http://crbug.com/64512.
// Disabled on Windows since it breaks Win7 build bots: http://crbug.com/164835.
#if defined(OS_WIN)
#define MAYBE_WebKitPrefsBackgroundPage DISABLED_WebKitPrefsBackgroundPage
#else
#define MAYBE_WebKitPrefsBackgroundPage WebKitPrefsBackgroundPage
#endif
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, WebKitPrefsBackgroundPage) {
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0")));
ExtensionProcessManager* manager =
extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
extensions::ExtensionHost* host =
FindHostWithPath(manager, "/backgroundpage.html", 1);
webkit_glue::WebPreferences prefs =
host->render_view_host()->GetWebkitPreferences();
ASSERT_TRUE(prefs.experimental_webgl_enabled);
ASSERT_TRUE(prefs.accelerated_compositing_enabled);
ASSERT_TRUE(prefs.accelerated_2d_canvas_enabled);
}
<commit_msg>Actually Disable ExtensionBrowserTest.WebKitPrefsBackgroundPage to get Win7 to buildbots to pass. (Was originally submitted with a stupid mistake in https://codereview.chromium.org/11471029/)<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/ui/browser.h"
#include "content/public/browser/render_view_host.h"
#include "webkit/glue/webpreferences.h"
// Tests that GPU-related WebKit preferences are set for extension background
// pages. See http://crbug.com/64512.
// Disabled on Windows since it breaks Win7 build bots: http://crbug.com/164835.
#if defined(OS_WIN)
#define MAYBE_WebKitPrefsBackgroundPage DISABLED_WebKitPrefsBackgroundPage
#else
#define MAYBE_WebKitPrefsBackgroundPage WebKitPrefsBackgroundPage
#endif
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, MAYBE_WebKitPrefsBackgroundPage) {
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0")));
ExtensionProcessManager* manager =
extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
extensions::ExtensionHost* host =
FindHostWithPath(manager, "/backgroundpage.html", 1);
webkit_glue::WebPreferences prefs =
host->render_view_host()->GetWebkitPreferences();
ASSERT_TRUE(prefs.experimental_webgl_enabled);
ASSERT_TRUE(prefs.accelerated_compositing_enabled);
ASSERT_TRUE(prefs.accelerated_2d_canvas_enabled);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/nss_decryptor_win.h"
#include "base/file_util.h"
#include "base/sys_string_conversions.h"
namespace {
typedef BOOL (WINAPI* SetDllDirectoryFunc)(LPCTSTR lpPathName);
// A helper class whose destructor calls SetDllDirectory(NULL) to undo the
// effects of a previous SetDllDirectory call.
class SetDllDirectoryCaller {
public:
explicit SetDllDirectoryCaller() : func_(NULL) { }
~SetDllDirectoryCaller() {
if (func_)
func_(NULL);
}
// Sets the SetDllDirectory function pointer to activates this object.
void set_func(SetDllDirectoryFunc func) { func_ = func; }
private:
SetDllDirectoryFunc func_;
};
} // namespace
// static
const wchar_t NSSDecryptor::kNSS3Library[] = L"nss3.dll";
const wchar_t NSSDecryptor::kSoftokn3Library[] = L"softokn3.dll";
const wchar_t NSSDecryptor::kPLDS4Library[] = L"plds4.dll";
const wchar_t NSSDecryptor::kNSPR4Library[] = L"nspr4.dll";
bool NSSDecryptor::Init(const std::wstring& dll_path,
const std::wstring& db_path) {
// We call SetDllDirectory to work around a Purify bug (GetModuleHandle
// fails inside Purify under certain conditions). SetDllDirectory only
// exists on Windows XP SP1 or later, so we look up its address at run time.
HMODULE kernel32_dll = GetModuleHandle(L"kernel32.dll");
if (kernel32_dll == NULL)
return false;
SetDllDirectoryFunc set_dll_directory =
(SetDllDirectoryFunc)GetProcAddress(kernel32_dll, "SetDllDirectoryW");
SetDllDirectoryCaller caller;
if (set_dll_directory != NULL) {
if (!set_dll_directory(dll_path.c_str()))
return false;
caller.set_func(set_dll_directory);
nss3_dll_ = LoadLibrary(kNSS3Library);
if (nss3_dll_ == NULL)
return false;
} else {
// Fall back on LoadLibraryEx if SetDllDirectory isn't available. We
// actually prefer this method because it doesn't change the DLL search
// path, which is a process-wide property.
std::wstring path = dll_path;
file_util::AppendToPath(&path, kNSS3Library);
nss3_dll_ = LoadLibraryEx(path.c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (nss3_dll_ == NULL)
return false;
// Firefox 2 uses NSS 3.11. Firefox 3 uses NSS 3.12. NSS 3.12 has two
// changes in its DLLs:
// 1. nss3.dll is not linked with softokn3.dll at build time, but rather
// loads softokn3.dll using LoadLibrary in NSS_Init.
// 2. softokn3.dll has a new dependency sqlite3.dll.
// NSS_Init's LoadLibrary call has trouble finding sqlite3.dll. To help
// it out, we preload softokn3.dll using LoadLibraryEx with the
// LOAD_WITH_ALTERED_SEARCH_PATH flag. This helps because LoadLibrary
// doesn't load a DLL again if it's already loaded. This workaround is
// harmless for NSS 3.11.
path = dll_path;
file_util::AppendToPath(&path, kSoftokn3Library);
softokn3_dll_ = LoadLibraryEx(path.c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (softokn3_dll_ == NULL) {
Free();
return false;
}
}
HMODULE plds4_dll = GetModuleHandle(kPLDS4Library);
HMODULE nspr4_dll = GetModuleHandle(kNSPR4Library);
return InitNSS(db_path, plds4_dll, nspr4_dll);
}
NSSDecryptor::NSSDecryptor()
: NSS_Init(NULL), NSS_Shutdown(NULL), PK11_GetInternalKeySlot(NULL),
PK11_CheckUserPassword(NULL), PK11_FreeSlot(NULL),
PK11_Authenticate(NULL), PK11SDR_Decrypt(NULL), SECITEM_FreeItem(NULL),
PL_ArenaFinish(NULL), PR_Cleanup(NULL),
nss3_dll_(NULL), softokn3_dll_(NULL),
is_nss_initialized_(false) {
}
NSSDecryptor::~NSSDecryptor() {
Free();
}
bool NSSDecryptor::InitNSS(const std::wstring& db_path,
base::NativeLibrary plds4_dll,
base::NativeLibrary nspr4_dll) {
// NSPR DLLs are already loaded now.
if (plds4_dll == NULL || nspr4_dll == NULL) {
Free();
return false;
}
// Gets the function address.
NSS_Init = (NSSInitFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "NSS_Init");
NSS_Shutdown = (NSSShutdownFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "NSS_Shutdown");
PK11_GetInternalKeySlot = (PK11GetInternalKeySlotFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_,
"PK11_GetInternalKeySlot");
PK11_FreeSlot = (PK11FreeSlotFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "PK11_FreeSlot");
PK11_Authenticate = (PK11AuthenticateFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "PK11_Authenticate");
PK11SDR_Decrypt = (PK11SDRDecryptFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "PK11SDR_Decrypt");
SECITEM_FreeItem = (SECITEMFreeItemFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "SECITEM_FreeItem");
PL_ArenaFinish = (PLArenaFinishFunc)
base::GetFunctionPointerFromNativeLibrary(plds4_dll, "PL_ArenaFinish");
PR_Cleanup = (PRCleanupFunc)
base::GetFunctionPointerFromNativeLibrary(nspr4_dll, "PR_Cleanup");
if (NSS_Init == NULL || NSS_Shutdown == NULL ||
PK11_GetInternalKeySlot == NULL || PK11_FreeSlot == NULL ||
PK11_Authenticate == NULL || PK11SDR_Decrypt == NULL ||
SECITEM_FreeItem == NULL || PL_ArenaFinish == NULL ||
PR_Cleanup == NULL) {
Free();
return false;
}
SECStatus result = NSS_Init(base::SysWideToNativeMB(db_path).c_str());
if (result != SECSuccess) {
Free();
return false;
}
is_nss_initialized_ = true;
return true;
}
void NSSDecryptor::Free() {
if (is_nss_initialized_) {
NSS_Shutdown();
PL_ArenaFinish();
PR_Cleanup();
is_nss_initialized_ = false;
}
if (softokn3_dll_ != NULL)
base::UnloadNativeLibrary(softokn3_dll_);
if (nss3_dll_ != NULL)
base::UnloadNativeLibrary(nss3_dll_);
NSS_Init = NULL;
NSS_Shutdown = NULL;
PK11_GetInternalKeySlot = NULL;
PK11_FreeSlot = NULL;
PK11_Authenticate = NULL;
PK11SDR_Decrypt = NULL;
SECITEM_FreeItem = NULL;
PL_ArenaFinish = NULL;
PR_Cleanup = NULL;
nss3_dll_ = NULL;
softokn3_dll_ = NULL;
}
<commit_msg>Remove the usage of the deprecated AppendToPath in nss_decryptor_win.cc<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/nss_decryptor_win.h"
#include "base/file_path.h"
#include "base/sys_string_conversions.h"
namespace {
typedef BOOL (WINAPI* SetDllDirectoryFunc)(LPCTSTR lpPathName);
// A helper class whose destructor calls SetDllDirectory(NULL) to undo the
// effects of a previous SetDllDirectory call.
class SetDllDirectoryCaller {
public:
explicit SetDllDirectoryCaller() : func_(NULL) { }
~SetDllDirectoryCaller() {
if (func_)
func_(NULL);
}
// Sets the SetDllDirectory function pointer to activates this object.
void set_func(SetDllDirectoryFunc func) { func_ = func; }
private:
SetDllDirectoryFunc func_;
};
} // namespace
// static
const wchar_t NSSDecryptor::kNSS3Library[] = L"nss3.dll";
const wchar_t NSSDecryptor::kSoftokn3Library[] = L"softokn3.dll";
const wchar_t NSSDecryptor::kPLDS4Library[] = L"plds4.dll";
const wchar_t NSSDecryptor::kNSPR4Library[] = L"nspr4.dll";
bool NSSDecryptor::Init(const std::wstring& dll_path,
const std::wstring& db_path) {
// We call SetDllDirectory to work around a Purify bug (GetModuleHandle
// fails inside Purify under certain conditions). SetDllDirectory only
// exists on Windows XP SP1 or later, so we look up its address at run time.
HMODULE kernel32_dll = GetModuleHandle(L"kernel32.dll");
if (kernel32_dll == NULL)
return false;
SetDllDirectoryFunc set_dll_directory =
(SetDllDirectoryFunc)GetProcAddress(kernel32_dll, "SetDllDirectoryW");
SetDllDirectoryCaller caller;
if (set_dll_directory != NULL) {
if (!set_dll_directory(dll_path.c_str()))
return false;
caller.set_func(set_dll_directory);
nss3_dll_ = LoadLibrary(kNSS3Library);
if (nss3_dll_ == NULL)
return false;
} else {
// Fall back on LoadLibraryEx if SetDllDirectory isn't available. We
// actually prefer this method because it doesn't change the DLL search
// path, which is a process-wide property.
FilePath path = FilePath(dll_path).Append(kNSS3Library);
nss3_dll_ = LoadLibraryEx(path.value().c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (nss3_dll_ == NULL)
return false;
// Firefox 2 uses NSS 3.11. Firefox 3 uses NSS 3.12. NSS 3.12 has two
// changes in its DLLs:
// 1. nss3.dll is not linked with softokn3.dll at build time, but rather
// loads softokn3.dll using LoadLibrary in NSS_Init.
// 2. softokn3.dll has a new dependency sqlite3.dll.
// NSS_Init's LoadLibrary call has trouble finding sqlite3.dll. To help
// it out, we preload softokn3.dll using LoadLibraryEx with the
// LOAD_WITH_ALTERED_SEARCH_PATH flag. This helps because LoadLibrary
// doesn't load a DLL again if it's already loaded. This workaround is
// harmless for NSS 3.11.
path = FilePath(dll_path).Append(kSoftokn3Library);
softokn3_dll_ = LoadLibraryEx(path.value().c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (softokn3_dll_ == NULL) {
Free();
return false;
}
}
HMODULE plds4_dll = GetModuleHandle(kPLDS4Library);
HMODULE nspr4_dll = GetModuleHandle(kNSPR4Library);
return InitNSS(db_path, plds4_dll, nspr4_dll);
}
NSSDecryptor::NSSDecryptor()
: NSS_Init(NULL), NSS_Shutdown(NULL), PK11_GetInternalKeySlot(NULL),
PK11_CheckUserPassword(NULL), PK11_FreeSlot(NULL),
PK11_Authenticate(NULL), PK11SDR_Decrypt(NULL), SECITEM_FreeItem(NULL),
PL_ArenaFinish(NULL), PR_Cleanup(NULL),
nss3_dll_(NULL), softokn3_dll_(NULL),
is_nss_initialized_(false) {
}
NSSDecryptor::~NSSDecryptor() {
Free();
}
bool NSSDecryptor::InitNSS(const std::wstring& db_path,
base::NativeLibrary plds4_dll,
base::NativeLibrary nspr4_dll) {
// NSPR DLLs are already loaded now.
if (plds4_dll == NULL || nspr4_dll == NULL) {
Free();
return false;
}
// Gets the function address.
NSS_Init = (NSSInitFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "NSS_Init");
NSS_Shutdown = (NSSShutdownFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "NSS_Shutdown");
PK11_GetInternalKeySlot = (PK11GetInternalKeySlotFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_,
"PK11_GetInternalKeySlot");
PK11_FreeSlot = (PK11FreeSlotFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "PK11_FreeSlot");
PK11_Authenticate = (PK11AuthenticateFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "PK11_Authenticate");
PK11SDR_Decrypt = (PK11SDRDecryptFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "PK11SDR_Decrypt");
SECITEM_FreeItem = (SECITEMFreeItemFunc)
base::GetFunctionPointerFromNativeLibrary(nss3_dll_, "SECITEM_FreeItem");
PL_ArenaFinish = (PLArenaFinishFunc)
base::GetFunctionPointerFromNativeLibrary(plds4_dll, "PL_ArenaFinish");
PR_Cleanup = (PRCleanupFunc)
base::GetFunctionPointerFromNativeLibrary(nspr4_dll, "PR_Cleanup");
if (NSS_Init == NULL || NSS_Shutdown == NULL ||
PK11_GetInternalKeySlot == NULL || PK11_FreeSlot == NULL ||
PK11_Authenticate == NULL || PK11SDR_Decrypt == NULL ||
SECITEM_FreeItem == NULL || PL_ArenaFinish == NULL ||
PR_Cleanup == NULL) {
Free();
return false;
}
SECStatus result = NSS_Init(base::SysWideToNativeMB(db_path).c_str());
if (result != SECSuccess) {
Free();
return false;
}
is_nss_initialized_ = true;
return true;
}
void NSSDecryptor::Free() {
if (is_nss_initialized_) {
NSS_Shutdown();
PL_ArenaFinish();
PR_Cleanup();
is_nss_initialized_ = false;
}
if (softokn3_dll_ != NULL)
base::UnloadNativeLibrary(softokn3_dll_);
if (nss3_dll_ != NULL)
base::UnloadNativeLibrary(nss3_dll_);
NSS_Init = NULL;
NSS_Shutdown = NULL;
PK11_GetInternalKeySlot = NULL;
PK11_FreeSlot = NULL;
PK11_Authenticate = NULL;
PK11SDR_Decrypt = NULL;
SECITEM_FreeItem = NULL;
PL_ArenaFinish = NULL;
PR_Cleanup = NULL;
nss3_dll_ = NULL;
softokn3_dll_ = NULL;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/options/cookies_view.h"
#include <algorithm>
#include "app/gfx/canvas.h"
#include "app/gfx/color_utils.h"
#include "app/l10n_util.h"
#include "base/i18n/time_formatting.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/views/appcache_info_view.h"
#include "chrome/browser/views/cookie_info_view.h"
#include "chrome/browser/views/database_info_view.h"
#include "chrome/browser/views/local_storage_info_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/cookie_monster.h"
#include "views/border.h"
#include "views/grid_layout.h"
#include "views/controls/label.h"
#include "views/controls/button/native_button.h"
#include "views/controls/tree/tree_view.h"
#include "views/controls/textfield/textfield.h"
#include "views/standard_layout.h"
// static
views::Window* CookiesView::instance_ = NULL;
static const int kSearchFilterDelayMs = 500;
///////////////////////////////////////////////////////////////////////////////
// CookiesTreeView
// Overridden to handle Delete key presses
class CookiesTreeView : public views::TreeView {
public:
explicit CookiesTreeView(CookiesTreeModel* cookies_model);
virtual ~CookiesTreeView() {}
// Removes the items associated with the selected node in the TreeView
void RemoveSelectedItems();
private:
DISALLOW_COPY_AND_ASSIGN(CookiesTreeView);
};
CookiesTreeView::CookiesTreeView(CookiesTreeModel* cookies_model) {
SetModel(cookies_model);
SetRootShown(false);
SetEditable(false);
}
void CookiesTreeView::RemoveSelectedItems() {
TreeModelNode* selected_node = GetSelectedNode();
if (selected_node) {
static_cast<CookiesTreeModel*>(model())->DeleteCookieNode(
static_cast<CookieTreeNode*>(GetSelectedNode()));
}
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView::InfoPanelView
// Overridden to handle layout of the various info views.
//
// This view is a child of the CookiesView and participates
// in its GridLayout. The various info views are all children
// of this view. Only one child is expected to be visible at a time.
class CookiesView::InfoPanelView : public views::View {
public:
virtual void Layout() {
int child_count = GetChildViewCount();
for (int i = 0; i < child_count; ++i)
GetChildViewAt(i)->SetBounds(0, 0, width(), height());
}
virtual gfx::Size GetPreferredSize() {
DCHECK(GetChildViewCount() > 0);
return GetChildViewAt(0)->GetPreferredSize();
}
};
///////////////////////////////////////////////////////////////////////////////
// CookiesView, public:
// static
void CookiesView::ShowCookiesWindow(Profile* profile) {
if (!instance_) {
CookiesView* cookies_view = new CookiesView(profile);
instance_ = views::Window::CreateChromeWindow(
NULL, gfx::Rect(), cookies_view);
}
if (!instance_->IsVisible()) {
instance_->Show();
} else {
instance_->Activate();
}
}
CookiesView::~CookiesView() {
cookies_tree_->SetModel(NULL);
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, TreeModelObserver overrides:
void CookiesView::TreeNodesAdded(TreeModel* model,
TreeModelNode* parent,
int start,
int count) {
UpdateRemoveButtonsState();
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::Buttonlistener implementation:
void CookiesView::ButtonPressed(
views::Button* sender, const views::Event& event) {
if (sender == remove_button_) {
cookies_tree_->RemoveSelectedItems();
if (cookies_tree_model_->GetRoot()->GetChildCount() == 0)
UpdateForEmptyState();
} else if (sender == remove_all_button_) {
cookies_tree_model_->DeleteAllStoredObjects();
UpdateForEmptyState();
} else if (sender == clear_search_button_) {
ResetSearchQuery();
}
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::Textfield::Controller implementation:
void CookiesView::ContentsChanged(views::Textfield* sender,
const std::wstring& new_contents) {
clear_search_button_->SetEnabled(!search_field_->text().empty());
search_update_factory_.RevokeAll();
MessageLoop::current()->PostDelayedTask(FROM_HERE,
search_update_factory_.NewRunnableMethod(
&CookiesView::UpdateSearchResults), kSearchFilterDelayMs);
}
bool CookiesView::HandleKeystroke(views::Textfield* sender,
const views::Textfield::Keystroke& key) {
if (key.GetKeyboardCode() == base::VKEY_ESCAPE) {
ResetSearchQuery();
} else if (key.GetKeyboardCode() == base::VKEY_RETURN) {
search_update_factory_.RevokeAll();
UpdateSearchResults();
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::DialogDelegate implementation:
std::wstring CookiesView::GetWindowTitle() const {
return l10n_util::GetString(IDS_COOKIES_WEBSITE_PERMISSIONS_WINDOW_TITLE);
}
void CookiesView::WindowClosing() {
instance_ = NULL;
}
views::View* CookiesView::GetContentsView() {
return this;
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::View overrides:
void CookiesView::Layout() {
// Lay out the Remove/Remove All buttons in the parent view.
gfx::Size ps = remove_button_->GetPreferredSize();
gfx::Rect parent_bounds = GetParent()->GetLocalBounds(false);
int y_buttons = parent_bounds.bottom() - ps.height() - kButtonVEdgeMargin;
remove_button_->SetBounds(kPanelHorizMargin, y_buttons, ps.width(),
ps.height());
ps = remove_all_button_->GetPreferredSize();
int remove_all_x = remove_button_->x() + remove_button_->width() +
kRelatedControlHorizontalSpacing;
remove_all_button_->SetBounds(remove_all_x, y_buttons, ps.width(),
ps.height());
// Lay out this View
View::Layout();
}
gfx::Size CookiesView::GetPreferredSize() {
return gfx::Size(views::Window::GetLocalizedContentsSize(
IDS_COOKIES_DIALOG_WIDTH_CHARS,
IDS_COOKIES_DIALOG_HEIGHT_LINES));
}
void CookiesView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && child == this)
Init();
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::TreeViewController overrides:
void CookiesView::OnTreeViewSelectionChanged(views::TreeView* tree_view) {
UpdateRemoveButtonsState();
CookieTreeNode::DetailedInfo detailed_info =
static_cast<CookieTreeNode*>(tree_view->GetSelectedNode())->
GetDetailedInfo();
if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_COOKIE) {
UpdateVisibleDetailedInfo(cookie_info_view_);
cookie_info_view_->SetCookie(detailed_info.cookie->first,
detailed_info.cookie->second);
} else if (detailed_info.node_type ==
CookieTreeNode::DetailedInfo::TYPE_DATABASE) {
UpdateVisibleDetailedInfo(database_info_view_);
database_info_view_->SetDatabaseInfo(*detailed_info.database_info);
} else if (detailed_info.node_type ==
CookieTreeNode::DetailedInfo::TYPE_LOCAL_STORAGE) {
UpdateVisibleDetailedInfo(local_storage_info_view_);
local_storage_info_view_->SetLocalStorageInfo(
*detailed_info.local_storage_info);
} else if (detailed_info.node_type ==
CookieTreeNode::DetailedInfo::TYPE_APPCACHE) {
UpdateVisibleDetailedInfo(appcache_info_view_);
appcache_info_view_->SetAppCacheInfo(detailed_info.appcache_info);
} else {
UpdateVisibleDetailedInfo(cookie_info_view_);
cookie_info_view_->ClearCookieDisplay();
}
}
void CookiesView::OnTreeViewKeyDown(base::KeyboardCode keycode) {
if (keycode == base::VKEY_DELETE)
cookies_tree_->RemoveSelectedItems();
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, public:
void CookiesView::UpdateSearchResults() {
cookies_tree_model_->UpdateSearchResults(search_field_->text());
remove_button_->SetEnabled(cookies_tree_model_->GetRoot()->
GetTotalNodeCount() > 1);
remove_all_button_->SetEnabled(cookies_tree_model_->GetRoot()->
GetTotalNodeCount() > 1);
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, private:
CookiesView::CookiesView(Profile* profile)
:
search_label_(NULL),
search_field_(NULL),
clear_search_button_(NULL),
description_label_(NULL),
cookies_tree_(NULL),
info_panel_(NULL),
cookie_info_view_(NULL),
database_info_view_(NULL),
local_storage_info_view_(NULL),
appcache_info_view_(NULL),
remove_button_(NULL),
remove_all_button_(NULL),
profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(search_update_factory_(this)) {
}
void CookiesView::Init() {
search_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_SEARCH_LABEL));
search_field_ = new views::Textfield;
search_field_->SetController(this);
clear_search_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_COOKIES_CLEAR_SEARCH_LABEL));
clear_search_button_->SetEnabled(false);
description_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_INFO_LABEL));
description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
cookies_tree_model_.reset(new CookiesTreeModel(profile_,
new BrowsingDataDatabaseHelper(profile_),
new BrowsingDataLocalStorageHelper(profile_),
new BrowsingDataAppCacheHelper(profile_)));
cookies_tree_model_->AddObserver(this);
info_panel_ = new InfoPanelView;
cookie_info_view_ = new CookieInfoView(false);
database_info_view_ = new DatabaseInfoView;
local_storage_info_view_ = new LocalStorageInfoView;
appcache_info_view_ = new AppCacheInfoView;
info_panel_->AddChildView(cookie_info_view_);
info_panel_->AddChildView(database_info_view_);
info_panel_->AddChildView(local_storage_info_view_);
info_panel_->AddChildView(appcache_info_view_);
cookies_tree_ = new CookiesTreeView(cookies_tree_model_.get());
remove_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_COOKIES_REMOVE_LABEL));
remove_all_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_COOKIES_REMOVE_ALL_LABEL));
using views::GridLayout;
using views::ColumnSet;
GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
const int five_column_layout_id = 0;
ColumnSet* column_set = layout->AddColumnSet(five_column_layout_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
GridLayout::USE_PREF, 0, 0);
const int single_column_layout_id = 1;
column_set = layout->AddColumnSet(single_column_layout_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, five_column_layout_id);
layout->AddView(search_label_);
layout->AddView(search_field_);
layout->AddView(clear_search_button_);
layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);
layout->StartRow(0, single_column_layout_id);
layout->AddView(description_label_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(1, single_column_layout_id);
cookies_tree_->set_lines_at_root(true);
cookies_tree_->set_auto_expand_children(true);
layout->AddView(cookies_tree_);
cookies_tree_->SetController(this);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, single_column_layout_id);
layout->AddView(info_panel_);
// Add the Remove/Remove All buttons to the ClientView
View* parent = GetParent();
parent->AddChildView(remove_button_);
parent->AddChildView(remove_all_button_);
if (!cookies_tree_model_.get()->GetRoot()->GetChildCount())
UpdateForEmptyState();
else
UpdateVisibleDetailedInfo(cookie_info_view_);
}
void CookiesView::ResetSearchQuery() {
search_field_->SetText(std::wstring());
clear_search_button_->SetEnabled(false);
UpdateSearchResults();
}
void CookiesView::UpdateForEmptyState() {
cookie_info_view_->ClearCookieDisplay();
remove_button_->SetEnabled(false);
remove_all_button_->SetEnabled(false);
UpdateVisibleDetailedInfo(cookie_info_view_);
}
void CookiesView::UpdateRemoveButtonsState() {
remove_button_->SetEnabled(cookies_tree_model_->GetRoot()->
GetTotalNodeCount() > 1 && cookies_tree_->GetSelectedNode());
remove_all_button_->SetEnabled(cookies_tree_model_->GetRoot()->
GetTotalNodeCount() > 1 && cookies_tree_->GetSelectedNode());
}
void CookiesView::UpdateVisibleDetailedInfo(views::View* view) {
cookie_info_view_->SetVisible(view == cookie_info_view_);
database_info_view_->SetVisible(view == database_info_view_);
local_storage_info_view_->SetVisible(view == local_storage_info_view_);
appcache_info_view_->SetVisible(view == appcache_info_view_);
}
<commit_msg>Enable "Remove All" button even if nothing is selected.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/options/cookies_view.h"
#include <algorithm>
#include "app/gfx/canvas.h"
#include "app/gfx/color_utils.h"
#include "app/l10n_util.h"
#include "base/i18n/time_formatting.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/views/appcache_info_view.h"
#include "chrome/browser/views/cookie_info_view.h"
#include "chrome/browser/views/database_info_view.h"
#include "chrome/browser/views/local_storage_info_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/cookie_monster.h"
#include "views/border.h"
#include "views/grid_layout.h"
#include "views/controls/label.h"
#include "views/controls/button/native_button.h"
#include "views/controls/tree/tree_view.h"
#include "views/controls/textfield/textfield.h"
#include "views/standard_layout.h"
// static
views::Window* CookiesView::instance_ = NULL;
static const int kSearchFilterDelayMs = 500;
///////////////////////////////////////////////////////////////////////////////
// CookiesTreeView
// Overridden to handle Delete key presses
class CookiesTreeView : public views::TreeView {
public:
explicit CookiesTreeView(CookiesTreeModel* cookies_model);
virtual ~CookiesTreeView() {}
// Removes the items associated with the selected node in the TreeView
void RemoveSelectedItems();
private:
DISALLOW_COPY_AND_ASSIGN(CookiesTreeView);
};
CookiesTreeView::CookiesTreeView(CookiesTreeModel* cookies_model) {
SetModel(cookies_model);
SetRootShown(false);
SetEditable(false);
}
void CookiesTreeView::RemoveSelectedItems() {
TreeModelNode* selected_node = GetSelectedNode();
if (selected_node) {
static_cast<CookiesTreeModel*>(model())->DeleteCookieNode(
static_cast<CookieTreeNode*>(GetSelectedNode()));
}
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView::InfoPanelView
// Overridden to handle layout of the various info views.
//
// This view is a child of the CookiesView and participates
// in its GridLayout. The various info views are all children
// of this view. Only one child is expected to be visible at a time.
class CookiesView::InfoPanelView : public views::View {
public:
virtual void Layout() {
int child_count = GetChildViewCount();
for (int i = 0; i < child_count; ++i)
GetChildViewAt(i)->SetBounds(0, 0, width(), height());
}
virtual gfx::Size GetPreferredSize() {
DCHECK(GetChildViewCount() > 0);
return GetChildViewAt(0)->GetPreferredSize();
}
};
///////////////////////////////////////////////////////////////////////////////
// CookiesView, public:
// static
void CookiesView::ShowCookiesWindow(Profile* profile) {
if (!instance_) {
CookiesView* cookies_view = new CookiesView(profile);
instance_ = views::Window::CreateChromeWindow(
NULL, gfx::Rect(), cookies_view);
}
if (!instance_->IsVisible()) {
instance_->Show();
} else {
instance_->Activate();
}
}
CookiesView::~CookiesView() {
cookies_tree_->SetModel(NULL);
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, TreeModelObserver overrides:
void CookiesView::TreeNodesAdded(TreeModel* model,
TreeModelNode* parent,
int start,
int count) {
UpdateRemoveButtonsState();
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::Buttonlistener implementation:
void CookiesView::ButtonPressed(
views::Button* sender, const views::Event& event) {
if (sender == remove_button_) {
cookies_tree_->RemoveSelectedItems();
if (cookies_tree_model_->GetRoot()->GetChildCount() == 0)
UpdateForEmptyState();
} else if (sender == remove_all_button_) {
cookies_tree_model_->DeleteAllStoredObjects();
UpdateForEmptyState();
} else if (sender == clear_search_button_) {
ResetSearchQuery();
}
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::Textfield::Controller implementation:
void CookiesView::ContentsChanged(views::Textfield* sender,
const std::wstring& new_contents) {
clear_search_button_->SetEnabled(!search_field_->text().empty());
search_update_factory_.RevokeAll();
MessageLoop::current()->PostDelayedTask(FROM_HERE,
search_update_factory_.NewRunnableMethod(
&CookiesView::UpdateSearchResults), kSearchFilterDelayMs);
}
bool CookiesView::HandleKeystroke(views::Textfield* sender,
const views::Textfield::Keystroke& key) {
if (key.GetKeyboardCode() == base::VKEY_ESCAPE) {
ResetSearchQuery();
} else if (key.GetKeyboardCode() == base::VKEY_RETURN) {
search_update_factory_.RevokeAll();
UpdateSearchResults();
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::DialogDelegate implementation:
std::wstring CookiesView::GetWindowTitle() const {
return l10n_util::GetString(IDS_COOKIES_WEBSITE_PERMISSIONS_WINDOW_TITLE);
}
void CookiesView::WindowClosing() {
instance_ = NULL;
}
views::View* CookiesView::GetContentsView() {
return this;
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::View overrides:
void CookiesView::Layout() {
// Lay out the Remove/Remove All buttons in the parent view.
gfx::Size ps = remove_button_->GetPreferredSize();
gfx::Rect parent_bounds = GetParent()->GetLocalBounds(false);
int y_buttons = parent_bounds.bottom() - ps.height() - kButtonVEdgeMargin;
remove_button_->SetBounds(kPanelHorizMargin, y_buttons, ps.width(),
ps.height());
ps = remove_all_button_->GetPreferredSize();
int remove_all_x = remove_button_->x() + remove_button_->width() +
kRelatedControlHorizontalSpacing;
remove_all_button_->SetBounds(remove_all_x, y_buttons, ps.width(),
ps.height());
// Lay out this View
View::Layout();
}
gfx::Size CookiesView::GetPreferredSize() {
return gfx::Size(views::Window::GetLocalizedContentsSize(
IDS_COOKIES_DIALOG_WIDTH_CHARS,
IDS_COOKIES_DIALOG_HEIGHT_LINES));
}
void CookiesView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && child == this)
Init();
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, views::TreeViewController overrides:
void CookiesView::OnTreeViewSelectionChanged(views::TreeView* tree_view) {
UpdateRemoveButtonsState();
CookieTreeNode::DetailedInfo detailed_info =
static_cast<CookieTreeNode*>(tree_view->GetSelectedNode())->
GetDetailedInfo();
if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_COOKIE) {
UpdateVisibleDetailedInfo(cookie_info_view_);
cookie_info_view_->SetCookie(detailed_info.cookie->first,
detailed_info.cookie->second);
} else if (detailed_info.node_type ==
CookieTreeNode::DetailedInfo::TYPE_DATABASE) {
UpdateVisibleDetailedInfo(database_info_view_);
database_info_view_->SetDatabaseInfo(*detailed_info.database_info);
} else if (detailed_info.node_type ==
CookieTreeNode::DetailedInfo::TYPE_LOCAL_STORAGE) {
UpdateVisibleDetailedInfo(local_storage_info_view_);
local_storage_info_view_->SetLocalStorageInfo(
*detailed_info.local_storage_info);
} else if (detailed_info.node_type ==
CookieTreeNode::DetailedInfo::TYPE_APPCACHE) {
UpdateVisibleDetailedInfo(appcache_info_view_);
appcache_info_view_->SetAppCacheInfo(detailed_info.appcache_info);
} else {
UpdateVisibleDetailedInfo(cookie_info_view_);
cookie_info_view_->ClearCookieDisplay();
}
}
void CookiesView::OnTreeViewKeyDown(base::KeyboardCode keycode) {
if (keycode == base::VKEY_DELETE)
cookies_tree_->RemoveSelectedItems();
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, public:
void CookiesView::UpdateSearchResults() {
cookies_tree_model_->UpdateSearchResults(search_field_->text());
UpdateRemoveButtonsState();
}
///////////////////////////////////////////////////////////////////////////////
// CookiesView, private:
CookiesView::CookiesView(Profile* profile)
:
search_label_(NULL),
search_field_(NULL),
clear_search_button_(NULL),
description_label_(NULL),
cookies_tree_(NULL),
info_panel_(NULL),
cookie_info_view_(NULL),
database_info_view_(NULL),
local_storage_info_view_(NULL),
appcache_info_view_(NULL),
remove_button_(NULL),
remove_all_button_(NULL),
profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(search_update_factory_(this)) {
}
void CookiesView::Init() {
search_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_SEARCH_LABEL));
search_field_ = new views::Textfield;
search_field_->SetController(this);
clear_search_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_COOKIES_CLEAR_SEARCH_LABEL));
clear_search_button_->SetEnabled(false);
description_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_INFO_LABEL));
description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
cookies_tree_model_.reset(new CookiesTreeModel(profile_,
new BrowsingDataDatabaseHelper(profile_),
new BrowsingDataLocalStorageHelper(profile_),
new BrowsingDataAppCacheHelper(profile_)));
cookies_tree_model_->AddObserver(this);
info_panel_ = new InfoPanelView;
cookie_info_view_ = new CookieInfoView(false);
database_info_view_ = new DatabaseInfoView;
local_storage_info_view_ = new LocalStorageInfoView;
appcache_info_view_ = new AppCacheInfoView;
info_panel_->AddChildView(cookie_info_view_);
info_panel_->AddChildView(database_info_view_);
info_panel_->AddChildView(local_storage_info_view_);
info_panel_->AddChildView(appcache_info_view_);
cookies_tree_ = new CookiesTreeView(cookies_tree_model_.get());
remove_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_COOKIES_REMOVE_LABEL));
remove_all_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_COOKIES_REMOVE_ALL_LABEL));
using views::GridLayout;
using views::ColumnSet;
GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
const int five_column_layout_id = 0;
ColumnSet* column_set = layout->AddColumnSet(five_column_layout_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
GridLayout::USE_PREF, 0, 0);
const int single_column_layout_id = 1;
column_set = layout->AddColumnSet(single_column_layout_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, five_column_layout_id);
layout->AddView(search_label_);
layout->AddView(search_field_);
layout->AddView(clear_search_button_);
layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);
layout->StartRow(0, single_column_layout_id);
layout->AddView(description_label_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(1, single_column_layout_id);
cookies_tree_->set_lines_at_root(true);
cookies_tree_->set_auto_expand_children(true);
layout->AddView(cookies_tree_);
cookies_tree_->SetController(this);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, single_column_layout_id);
layout->AddView(info_panel_);
// Add the Remove/Remove All buttons to the ClientView
View* parent = GetParent();
parent->AddChildView(remove_button_);
parent->AddChildView(remove_all_button_);
if (!cookies_tree_model_.get()->GetRoot()->GetChildCount())
UpdateForEmptyState();
else
UpdateVisibleDetailedInfo(cookie_info_view_);
}
void CookiesView::ResetSearchQuery() {
search_field_->SetText(std::wstring());
clear_search_button_->SetEnabled(false);
UpdateSearchResults();
}
void CookiesView::UpdateForEmptyState() {
cookie_info_view_->ClearCookieDisplay();
remove_button_->SetEnabled(false);
remove_all_button_->SetEnabled(false);
UpdateVisibleDetailedInfo(cookie_info_view_);
}
void CookiesView::UpdateRemoveButtonsState() {
remove_button_->SetEnabled(cookies_tree_model_->GetRoot()->
GetTotalNodeCount() > 1 && cookies_tree_->GetSelectedNode());
remove_all_button_->SetEnabled(cookies_tree_model_->GetRoot()->
GetTotalNodeCount() > 1);
}
void CookiesView::UpdateVisibleDetailedInfo(views::View* view) {
cookie_info_view_->SetVisible(view == cookie_info_view_);
database_info_view_->SetVisible(view == database_info_view_);
local_storage_info_view_->SetVisible(view == local_storage_info_view_);
appcache_info_view_->SetVisible(view == appcache_info_view_);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
#include "chrome/renderer/media/video_renderer_impl.h"
#include "media/base/yuv_convert.h"
VideoRendererImpl::VideoRendererImpl(WebMediaPlayerDelegateImpl* delegate)
: delegate_(delegate),
last_converted_frame_(NULL) {
}
bool VideoRendererImpl::OnInitialize(size_t width, size_t height) {
video_size_.SetSize(width, height);
bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height);
if (bitmap_.allocPixels(NULL, NULL)) {
bitmap_.eraseRGB(0x00, 0x00, 0x00);
return true;
}
NOTREACHED();
return false;
}
void VideoRendererImpl::OnPaintNeeded() {
delegate_->PostRepaintTask();
}
// This method is always called on the renderer's thread.
void VideoRendererImpl::Paint(skia::PlatformCanvas* canvas,
const gfx::Rect& dest_rect) {
scoped_refptr<media::VideoFrame> video_frame;
GetCurrentFrame(&video_frame);
if (video_frame.get()) {
CopyToCurrentFrame(video_frame);
video_frame = NULL;
}
SkMatrix matrix;
matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()),
static_cast<SkScalar>(dest_rect.y()));
if (dest_rect.width() != video_size_.width() ||
dest_rect.height() != video_size_.height()) {
matrix.preScale(
static_cast<SkScalar>(dest_rect.width() / video_size_.width()),
static_cast<SkScalar>(dest_rect.height() / video_size_.height()));
}
canvas->drawBitmapMatrix(bitmap_, matrix, NULL);
}
void VideoRendererImpl::CopyToCurrentFrame(media::VideoFrame* video_frame) {
base::TimeDelta timestamp = video_frame->GetTimestamp();
if (video_frame != last_converted_frame_ ||
timestamp != last_converted_timestamp_) {
last_converted_frame_ = video_frame;
last_converted_timestamp_ = timestamp;
media::VideoSurface frame_in;
if (video_frame->Lock(&frame_in)) {
// TODO(hclam): Support more video formats than just YV12.
DCHECK(frame_in.format == media::VideoSurface::YV12);
DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==
frame_in.strides[media::VideoSurface::kVPlane]);
DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);
bitmap_.lockPixels();
media::ConvertYV12ToRGB32(frame_in.data[media::VideoSurface::kYPlane],
frame_in.data[media::VideoSurface::kUPlane],
frame_in.data[media::VideoSurface::kVPlane],
static_cast<uint8*>(bitmap_.getPixels()),
frame_in.width,
frame_in.height,
frame_in.strides[media::VideoSurface::kYPlane],
frame_in.strides[media::VideoSurface::kUPlane],
bitmap_.rowBytes());
bitmap_.unlockPixels();
video_frame->Unlock();
} else {
NOTREACHED();
}
}
}
<commit_msg>TBR=ralphl<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
#include "chrome/renderer/media/video_renderer_impl.h"
#include "media/base/yuv_convert.h"
VideoRendererImpl::VideoRendererImpl(WebMediaPlayerDelegateImpl* delegate)
: delegate_(delegate),
last_converted_frame_(NULL) {
// TODO(hclam): decide whether to do the following line in this thread or
// in the render thread.
delegate_->SetVideoRenderer(this);
}
bool VideoRendererImpl::OnInitialize(size_t width, size_t height) {
video_size_.SetSize(width, height);
bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height);
if (bitmap_.allocPixels(NULL, NULL)) {
bitmap_.eraseRGB(0x00, 0x00, 0x00);
return true;
}
NOTREACHED();
return false;
}
void VideoRendererImpl::OnPaintNeeded() {
delegate_->PostRepaintTask();
}
// This method is always called on the renderer's thread.
void VideoRendererImpl::Paint(skia::PlatformCanvas* canvas,
const gfx::Rect& dest_rect) {
scoped_refptr<media::VideoFrame> video_frame;
GetCurrentFrame(&video_frame);
if (video_frame.get()) {
CopyToCurrentFrame(video_frame);
video_frame = NULL;
}
SkMatrix matrix;
matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()),
static_cast<SkScalar>(dest_rect.y()));
if (dest_rect.width() != video_size_.width() ||
dest_rect.height() != video_size_.height()) {
matrix.preScale(
static_cast<SkScalar>(dest_rect.width() / video_size_.width()),
static_cast<SkScalar>(dest_rect.height() / video_size_.height()));
}
canvas->drawBitmapMatrix(bitmap_, matrix, NULL);
}
void VideoRendererImpl::CopyToCurrentFrame(media::VideoFrame* video_frame) {
base::TimeDelta timestamp = video_frame->GetTimestamp();
if (video_frame != last_converted_frame_ ||
timestamp != last_converted_timestamp_) {
last_converted_frame_ = video_frame;
last_converted_timestamp_ = timestamp;
media::VideoSurface frame_in;
if (video_frame->Lock(&frame_in)) {
// TODO(hclam): Support more video formats than just YV12.
DCHECK(frame_in.format == media::VideoSurface::YV12);
DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==
frame_in.strides[media::VideoSurface::kVPlane]);
DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);
bitmap_.lockPixels();
media::ConvertYV12ToRGB32(frame_in.data[media::VideoSurface::kYPlane],
frame_in.data[media::VideoSurface::kUPlane],
frame_in.data[media::VideoSurface::kVPlane],
static_cast<uint8*>(bitmap_.getPixels()),
frame_in.width,
frame_in.height,
frame_in.strides[media::VideoSurface::kYPlane],
frame_in.strides[media::VideoSurface::kUPlane],
bitmap_.rowBytes());
bitmap_.unlockPixels();
video_frame->Unlock();
} else {
NOTREACHED();
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/api/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/api/infobars/infobar_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/page_transition_types.h"
#include "content/public/test/browser_test_utils.h"
#include "content/test/gpu/gpu_test_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gl/gl_implementation.h"
namespace {
void SimulateGPUCrash(Browser* browser) {
// None of the ui_test_utils entry points supports what we need to
// do here: navigate with the PAGE_TRANSITION_FROM_ADDRESS_BAR flag,
// without waiting for the navigation. It would be painful to change
// either of the NavigateToURL entry points to support these two
// constraints, so we use chrome::Navigate directly.
chrome::NavigateParams params(
browser,
GURL(chrome::kChromeUIGpuCrashURL),
static_cast<content::PageTransition>(
content::PAGE_TRANSITION_TYPED |
content::PAGE_TRANSITION_FROM_ADDRESS_BAR));
params.disposition = NEW_BACKGROUND_TAB;
chrome::Navigate(¶ms);
}
} // namespace
class WebGLInfobarTest : public InProcessBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
// GPU tests require gpu acceleration.
// We do not care which GL backend is used.
command_line->AppendSwitchASCII(switches::kUseGL, "any");
}
virtual void SetUpInProcessBrowserTestFixture() {
FilePath test_dir;
ASSERT_TRUE(PathService::Get(content::DIR_TEST_DATA, &test_dir));
gpu_test_dir_ = test_dir.AppendASCII("gpu");
}
FilePath gpu_test_dir_;
};
IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, ContextLossRaisesInfobar) {
// crbug.com/162982, flaky on Mac Retina Release, timeout on Debug.
if (GPUTestBotConfig::CurrentConfigMatches("MAC NVIDIA 0x0fd5"))
return;
// Load page and wait for it to load.
content::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURL(
browser(),
content::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"), "query=kill"));
observer.Wait();
content::WindowedNotificationObserver infobar_added(
chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
content::NotificationService::AllSources());
SimulateGPUCrash(browser());
infobar_added.Wait();
EXPECT_EQ(1u,
InfoBarService::FromWebContents(
chrome::GetActiveWebContents(browser()))->GetInfoBarCount());
}
IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, ContextLossInfobarReload) {
// crbug.com/162982, flaky on Mac Retina Release.
if (GPUTestBotConfig::CurrentConfigMatches("MAC NVIDIA 0x0fd5 RELEASE"))
return;
content::DOMMessageQueue message_queue;
// Load page and wait for it to load.
content::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURL(
browser(),
content::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"),
"query=kill_after_notification"));
observer.Wait();
std::string m;
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"LOADED\"", m);
message_queue.ClearQueue();
content::WindowedNotificationObserver infobar_added(
chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
content::NotificationService::AllSources());
SimulateGPUCrash(browser());
infobar_added.Wait();
ASSERT_EQ(1u,
InfoBarService::FromWebContents(
chrome::GetActiveWebContents(browser()))->GetInfoBarCount());
InfoBarDelegate* delegate =
InfoBarService::FromWebContents(
chrome::GetActiveWebContents(browser()))->GetInfoBarDelegateAt(0);
ASSERT_TRUE(delegate);
ASSERT_TRUE(delegate->AsThreeDAPIInfoBarDelegate());
delegate->AsConfirmInfoBarDelegate()->Cancel();
// The page should reload and another message sent to the
// DomAutomationController.
m = "";
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"LOADED\"", m);
}
// There isn't any point in adding a test which calls Accept() on the
// ThreeDAPIInfoBarDelegate; doing so doesn't remove the infobar, and
// there's no concrete event that could be observed in response.
<commit_msg>Disable ContextLossInfobarReloaded.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/api/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/api/infobars/infobar_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/page_transition_types.h"
#include "content/public/test/browser_test_utils.h"
#include "content/test/gpu/gpu_test_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gl/gl_implementation.h"
namespace {
void SimulateGPUCrash(Browser* browser) {
// None of the ui_test_utils entry points supports what we need to
// do here: navigate with the PAGE_TRANSITION_FROM_ADDRESS_BAR flag,
// without waiting for the navigation. It would be painful to change
// either of the NavigateToURL entry points to support these two
// constraints, so we use chrome::Navigate directly.
chrome::NavigateParams params(
browser,
GURL(chrome::kChromeUIGpuCrashURL),
static_cast<content::PageTransition>(
content::PAGE_TRANSITION_TYPED |
content::PAGE_TRANSITION_FROM_ADDRESS_BAR));
params.disposition = NEW_BACKGROUND_TAB;
chrome::Navigate(¶ms);
}
} // namespace
class WebGLInfobarTest : public InProcessBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
// GPU tests require gpu acceleration.
// We do not care which GL backend is used.
command_line->AppendSwitchASCII(switches::kUseGL, "any");
}
virtual void SetUpInProcessBrowserTestFixture() {
FilePath test_dir;
ASSERT_TRUE(PathService::Get(content::DIR_TEST_DATA, &test_dir));
gpu_test_dir_ = test_dir.AppendASCII("gpu");
}
FilePath gpu_test_dir_;
};
IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, ContextLossRaisesInfobar) {
// crbug.com/162982, flaky on Mac Retina Release.
if (GPUTestBotConfig::CurrentConfigMatches("MAC NVIDIA 0x0fd5 RELEASE"))
return;
// Load page and wait for it to load.
content::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURL(
browser(),
content::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"), "query=kill"));
observer.Wait();
content::WindowedNotificationObserver infobar_added(
chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
content::NotificationService::AllSources());
SimulateGPUCrash(browser());
infobar_added.Wait();
EXPECT_EQ(1u,
InfoBarService::FromWebContents(
chrome::GetActiveWebContents(browser()))->GetInfoBarCount());
}
IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, ContextLossInfobarReload) {
// crbug.com/162982, flaky on Mac Retina Release, timeout on Debug.
if (GPUTestBotConfig::CurrentConfigMatches("MAC NVIDIA 0x0fd5"))
return;
content::DOMMessageQueue message_queue;
// Load page and wait for it to load.
content::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURL(
browser(),
content::GetFileUrlWithQuery(
gpu_test_dir_.AppendASCII("webgl.html"),
"query=kill_after_notification"));
observer.Wait();
std::string m;
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"LOADED\"", m);
message_queue.ClearQueue();
content::WindowedNotificationObserver infobar_added(
chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
content::NotificationService::AllSources());
SimulateGPUCrash(browser());
infobar_added.Wait();
ASSERT_EQ(1u,
InfoBarService::FromWebContents(
chrome::GetActiveWebContents(browser()))->GetInfoBarCount());
InfoBarDelegate* delegate =
InfoBarService::FromWebContents(
chrome::GetActiveWebContents(browser()))->GetInfoBarDelegateAt(0);
ASSERT_TRUE(delegate);
ASSERT_TRUE(delegate->AsThreeDAPIInfoBarDelegate());
delegate->AsConfirmInfoBarDelegate()->Cancel();
// The page should reload and another message sent to the
// DomAutomationController.
m = "";
ASSERT_TRUE(message_queue.WaitForMessage(&m));
EXPECT_EQ("\"LOADED\"", m);
}
// There isn't any point in adding a test which calls Accept() on the
// ThreeDAPIInfoBarDelegate; doing so doesn't remove the infobar, and
// there's no concrete event that could be observed in response.
<|endoftext|> |
<commit_before>//
// (C) CharLS Team 2014, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "jpegmarkersegment.h"
#include "jpegmarkercode.h"
#include "util.h"
#include <vector>
#include <cstdint>
using namespace std;
using namespace charls;
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateStartOfFrameSegment(int width, int height, int bitsPerSample, int componentCount)
{
ASSERT(width >= 0 && width <= UINT16_MAX);
ASSERT(height >= 0 && height <= UINT16_MAX);
ASSERT(bitsPerSample > 0 && bitsPerSample <= UINT8_MAX);
ASSERT(componentCount > 0 && componentCount <= (UINT8_MAX - 1));
// Create a Frame Header as defined in T.87, C.2.2 and T.81, B.2.2
vector<uint8_t> content;
content.push_back(static_cast<uint8_t>(bitsPerSample)); // P = Sample precision
push_back(content, static_cast<uint16_t>(height)); // Y = Number of lines
push_back(content, static_cast<uint16_t>(width)); // X = Number of samples per line
// Components
content.push_back(static_cast<uint8_t>(componentCount)); // Nf = Number of image components in frame
for (auto component = 0; component < componentCount; ++component)
{
// Component Specification parameters
content.push_back(static_cast<uint8_t>(component + 1)); // Ci = Component identifier
content.push_back(0x11); // Hi + Vi = Horizontal sampling factor + Vertical sampling factor
content.push_back(0); // Tqi = Quantization table destination selector (reserved for JPEG-LS, should be set to 0)
}
return make_unique<JpegMarkerSegment>(JpegMarkerCode::StartOfFrameJpegLS, move(content));
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateJpegFileInterchangeFormatSegment(const JfifParameters& params)
{
ASSERT(params.units == 0 || params.units == 1 || params.units == 2);
ASSERT(params.Xdensity > 0);
ASSERT(params.Ydensity > 0);
ASSERT(params.Xthumbnail >= 0 && params.Xthumbnail < 256);
ASSERT(params.Ythumbnail >= 0 && params.Ythumbnail < 256);
// Create a JPEG APP0 segment in the JPEG File Interchange Format (JFIF), v1.02
vector<uint8_t> content;
for (auto c : { 'J', 'F', 'I', 'F', '\0' })
{
content.push_back(c);
}
push_back(content, static_cast<uint16_t>(params.version));
content.push_back(static_cast<uint8_t>(params.units));
push_back(content, static_cast<uint16_t>(params.Xdensity));
push_back(content, static_cast<uint16_t>(params.Ydensity));
// thumbnail
content.push_back(static_cast<uint8_t>(params.Xthumbnail));
content.push_back(static_cast<uint8_t>(params.Ythumbnail));
if (params.Xthumbnail > 0)
{
if (params.thumbnail)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "params.Xthumbnail is > 0 but params.thumbnail == null_ptr");
content.insert(content.end(), static_cast<uint8_t*>(params.thumbnail),
static_cast<uint8_t*>(params.thumbnail) + 3 * params.Xthumbnail * params.Ythumbnail);
}
return make_unique<JpegMarkerSegment>(JpegMarkerCode::ApplicationData0, move(content));
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateJpegLSExtendedParametersSegment(const JlsCustomParameters& params)
{
vector<uint8_t> content;
// Parameter ID. 0x01 = JPEG-LS preset coding parameters.
content.push_back(1);
push_back(content, static_cast<uint16_t>(params.MAXVAL));
push_back(content, static_cast<uint16_t>(params.T1));
push_back(content, static_cast<uint16_t>(params.T2));
push_back(content, static_cast<uint16_t>(params.T3));
push_back(content, static_cast<uint16_t>(params.RESET));
return make_unique<JpegMarkerSegment>(JpegMarkerCode::JpegLSExtendedParameters, move(content));
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateColorTransformSegment(ColorTransformation transformation)
{
vector<uint8_t> content;
content.push_back('m');
content.push_back('r');
content.push_back('f');
content.push_back('x');
content.push_back(static_cast<uint8_t>(transformation));
return make_unique<JpegMarkerSegment>(JpegMarkerCode::ApplicationData8, move(content));
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateStartOfScanSegment(int componentIndex, int componentCount, int allowedLossyError, InterleaveMode interleaveMode)
{
ASSERT(componentIndex >= 0);
ASSERT(componentCount > 0);
// Create a Scan Header as defined in T.87, C.2.3 and T.81, B.2.3
vector<uint8_t> content;
content.push_back(static_cast<uint8_t>(componentCount));
for (auto i = 0; i < componentCount; ++i)
{
content.push_back(static_cast<uint8_t>(componentIndex + i));
content.push_back(0); // Mapping table selector (0 = no table)
}
content.push_back(static_cast<uint8_t>(allowedLossyError)); // NEAR parameter
content.push_back(static_cast<uint8_t>(interleaveMode)); // ILV parameter
content.push_back(0); // transformation
return make_unique<JpegMarkerSegment>(JpegMarkerCode::StartOfScan, move(content));
}
<commit_msg>Updated code to leverage C++ 11 initializer lists<commit_after>//
// (C) CharLS Team 2014, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "jpegmarkersegment.h"
#include "jpegmarkercode.h"
#include "util.h"
#include <vector>
#include <cstdint>
using namespace std;
using namespace charls;
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateStartOfFrameSegment(int width, int height, int bitsPerSample, int componentCount)
{
ASSERT(width >= 0 && width <= UINT16_MAX);
ASSERT(height >= 0 && height <= UINT16_MAX);
ASSERT(bitsPerSample > 0 && bitsPerSample <= UINT8_MAX);
ASSERT(componentCount > 0 && componentCount <= (UINT8_MAX - 1));
// Create a Frame Header as defined in T.87, C.2.2 and T.81, B.2.2
vector<uint8_t> content;
content.push_back(static_cast<uint8_t>(bitsPerSample)); // P = Sample precision
push_back(content, static_cast<uint16_t>(height)); // Y = Number of lines
push_back(content, static_cast<uint16_t>(width)); // X = Number of samples per line
// Components
content.push_back(static_cast<uint8_t>(componentCount)); // Nf = Number of image components in frame
for (auto component = 0; component < componentCount; ++component)
{
// Component Specification parameters
content.push_back(static_cast<uint8_t>(component + 1)); // Ci = Component identifier
content.push_back(0x11); // Hi + Vi = Horizontal sampling factor + Vertical sampling factor
content.push_back(0); // Tqi = Quantization table destination selector (reserved for JPEG-LS, should be set to 0)
}
return make_unique<JpegMarkerSegment>(JpegMarkerCode::StartOfFrameJpegLS, move(content));
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateJpegFileInterchangeFormatSegment(const JfifParameters& params)
{
ASSERT(params.units == 0 || params.units == 1 || params.units == 2);
ASSERT(params.Xdensity > 0);
ASSERT(params.Ydensity > 0);
ASSERT(params.Xthumbnail >= 0 && params.Xthumbnail < 256);
ASSERT(params.Ythumbnail >= 0 && params.Ythumbnail < 256);
// Create a JPEG APP0 segment in the JPEG File Interchange Format (JFIF), v1.02
vector<uint8_t> content { 'J', 'F', 'I', 'F', '\0' };
push_back(content, static_cast<uint16_t>(params.version));
content.push_back(static_cast<uint8_t>(params.units));
push_back(content, static_cast<uint16_t>(params.Xdensity));
push_back(content, static_cast<uint16_t>(params.Ydensity));
// thumbnail
content.push_back(static_cast<uint8_t>(params.Xthumbnail));
content.push_back(static_cast<uint8_t>(params.Ythumbnail));
if (params.Xthumbnail > 0)
{
if (params.thumbnail)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "params.Xthumbnail is > 0 but params.thumbnail == null_ptr");
content.insert(content.end(), static_cast<uint8_t*>(params.thumbnail),
static_cast<uint8_t*>(params.thumbnail) + 3 * params.Xthumbnail * params.Ythumbnail);
}
return make_unique<JpegMarkerSegment>(JpegMarkerCode::ApplicationData0, move(content));
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateJpegLSExtendedParametersSegment(const JlsCustomParameters& params)
{
vector<uint8_t> content;
// Parameter ID. 0x01 = JPEG-LS preset coding parameters.
content.push_back(1);
push_back(content, static_cast<uint16_t>(params.MAXVAL));
push_back(content, static_cast<uint16_t>(params.T1));
push_back(content, static_cast<uint16_t>(params.T2));
push_back(content, static_cast<uint16_t>(params.T3));
push_back(content, static_cast<uint16_t>(params.RESET));
return make_unique<JpegMarkerSegment>(JpegMarkerCode::JpegLSExtendedParameters, move(content));
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateColorTransformSegment(ColorTransformation transformation)
{
return make_unique<JpegMarkerSegment>(
JpegMarkerCode::ApplicationData8,
vector<uint8_t> { 'm', 'r', 'f', 'x', static_cast<uint8_t>(transformation) });
}
unique_ptr<JpegMarkerSegment> JpegMarkerSegment::CreateStartOfScanSegment(int componentIndex, int componentCount, int allowedLossyError, InterleaveMode interleaveMode)
{
ASSERT(componentIndex >= 0);
ASSERT(componentCount > 0);
// Create a Scan Header as defined in T.87, C.2.3 and T.81, B.2.3
vector<uint8_t> content;
content.push_back(static_cast<uint8_t>(componentCount));
for (auto i = 0; i < componentCount; ++i)
{
content.push_back(static_cast<uint8_t>(componentIndex + i));
content.push_back(0); // Mapping table selector (0 = no table)
}
content.push_back(static_cast<uint8_t>(allowedLossyError)); // NEAR parameter
content.push_back(static_cast<uint8_t>(interleaveMode)); // ILV parameter
content.push_back(0); // transformation
return make_unique<JpegMarkerSegment>(JpegMarkerCode::StartOfScan, move(content));
}
<|endoftext|> |
<commit_before>// -*-Mode: C++;-*-
// $Id$
// * BeginRiceCopyright *****************************************************
//
// Copyright ((c)) 2002-2007, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $Source$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
//************************* System Include Files ****************************
#include <iostream>
using std::cerr;
using std::hex;
using std::dec;
#include <string>
using std::string;
//*************************** User Include Files ****************************
#include "Util.hpp"
#include <lib/banal/bloop-simple.hpp>
#include <lib/support/diagnostics.h>
#include <lib/support/pathfind.h>
#include <lib/support/realpath.h>
//*************************** Forward Declarations **************************
//***************************************************************************
//***************************************************************************
//
//***************************************************************************
Analysis::Util::ProfType_t
Analysis::Util::getProfileType(const std::string& filenm)
{
// FIXME: a better way of doing this would be to read the first 32
// bytes and test for the magic cookie.
// FIXME: not yet abstracted since csprof is still a mess
static const string CALLPATH_SFX = ".hpcrun";
if (filenm.length() > CALLPATH_SFX.length()) {
uint begpos = filenm.length() - CALLPATH_SFX.length();
if (filenm.find(CALLPATH_SFX, begpos) != string::npos) {
return ProfType_CALLPATH;
}
}
#if 0
// C++
std::ifstream in(fname);
in.read(char* buf, streamsize n);
// C:
char* buf = new char[32+1];
int bytesRead = ::fread(f, buf, sizeof(char), 32);
// Overloaded C++
std::ifstream in(fname);
std::istreambuf_iterator<char> i(in);
std::istreambuf_iterator<char> eos;
std::vector<char> v(i, eos);
// or: string str(i, i+32);
#endif
return ProfType_FLAT;
}
//***************************************************************************
//
//***************************************************************************
// Always consult the load module's structure information
// (Struct::LM) and perform a lookup by VMA first. If this fails:
//
// - If the structure was seeded by full structure by
// bloop::makeStructure (useStruct), then use the "unknown" file
// and procedures.
//
// - Otherwise, create structure using banal::bloop::makeStructureSimple
//
// This policy assumes that when full structure has been provided,
// banal::bloop::makeStructureSimple could have undesirable effects. One
// example of a problem is that for simple structure, a line ->
// Struct::Stmt map is consulted which is ambiguous in the presence of
// inlinine (Struct::Alien).
Prof::Struct::ACodeNode*
Analysis::Util::demandStructure(VMA vma, Prof::Struct::LM* lmStrct, binutils::LM* lm, bool useStruct)
{
Prof::Struct::ACodeNode* strct = lmStrct->findByVMA(vma);
if (!strct) {
if (useStruct) {
Prof::Struct::File* fileStrct =
Prof::Struct::File::demand(lmStrct,
Prof::Struct::Tree::UnknownFileNm);
strct = Prof::Struct::Proc::demand(fileStrct,
Prof::Struct::Tree::UnknownProcNm);
}
else {
strct = banal::bloop::makeStructureSimple(lmStrct, lm, vma);
}
}
return strct;
}
//***************************************************************************
//
//***************************************************************************
static string
copySourceFileMain(const string& fnm_orig,
std::map<string, string>& processedFiles,
const Analysis::PathTupleVec& pathVec,
const string& dstDir);
static bool
Flat_Filter(const Prof::Struct::ANode& x, long type)
{
return (x.type() == Prof::Struct::ANode::TyFILE
|| x.type() == Prof::Struct::ANode::TyALIEN);
}
// copySourceFiles: For every Prof::Struct::File and
// Prof::Struct::Alien x in 'structure' that can be reached with paths
// in 'pathVec', copy x to its appropriate viewname path and update
// x's path to be relative to this location.
void
Analysis::Util::copySourceFiles(Prof::Struct::Root* structure,
const Analysis::PathTupleVec& pathVec,
const string& dstDir)
{
// Prevent multiple copies of the same file (Alien scopes)
std::map<string, string> processedFiles;
Prof::Struct::ANodeFilter filter(Flat_Filter, "Flat_Filter", 0);
for (Prof::Struct::ANodeIterator it(structure, &filter); it.Current(); ++it) {
Prof::Struct::ANode* strct = it.CurNode();
// Note: 'fnm_orig' will be not be absolute if it is not possible
// to resolve it on the current filesystem. (cf. RealPathMgr)
// DIAG_Assert( , DIAG_UnexpectedInput);
const string& fnm_orig = (typeid(*strct) == typeid(Prof::Struct::Alien)) ?
dynamic_cast<Prof::Struct::Alien*>(strct)->fileName() : strct->name();
// ------------------------------------------------------
// Given fnm_orig, attempt to find and copy fnm_new
// ------------------------------------------------------
string fnm_new =
copySourceFileMain(fnm_orig, processedFiles, pathVec, dstDir);
// ------------------------------------------------------
// Update static structure
// ------------------------------------------------------
if (!fnm_new.empty()) {
if (typeid(*strct) == typeid(Prof::Struct::Alien)) {
dynamic_cast<Prof::Struct::Alien*>(strct)->fileName(fnm_new);
}
else {
dynamic_cast<Prof::Struct::File*>(strct)->name(fnm_new);
}
}
}
}
static std::pair<int, string>
matchFileWithPath(const string& filenm, const Analysis::PathTupleVec& pathVec);
static string
copySourceFile(const string& filenm, const string& dstDir,
const Analysis::PathTuple& pathTpl);
static string
copySourceFileMain(const string& fnm_orig,
std::map<string, string>& processedFiles,
const Analysis::PathTupleVec& pathVec,
const string& dstDir)
{
string fnm_new;
std::map<string, string>::iterator it = processedFiles.find(fnm_orig);
if (it != processedFiles.end()) {
fnm_new = it->second;
}
else {
std::pair<int, string> fnd = matchFileWithPath(fnm_orig, pathVec);
int idx = fnd.first;
if (idx >= 0) {
// fnm_orig explicitly matches a <search-path, path-view> tuple
fnm_new = copySourceFile(fnd.second, dstDir, pathVec[idx]);
}
else if (fnm_orig[0] == '/' && FileUtil::isReadable(fnm_orig.c_str())) {
// fnm_orig does not match a pathVec tuple; but if it is an
// absolute path that is readable, use the default <search-path,
// path-view> tuple.
static const Analysis::PathTuple
defaultTpl("/", Analysis::DefaultPathTupleTarget);
fnm_new = copySourceFile(fnm_orig, dstDir, defaultTpl);
}
if (fnm_new.empty()) {
DIAG_WMsg(2, "lost: " << fnm_orig);
}
else {
DIAG_Msg(2, " cp:" << fnm_orig << " -> " << fnm_new);
}
processedFiles.insert(make_pair(fnm_orig, fnm_new));
}
return fnm_new;
}
//***************************************************************************
// matchFileWithPath: Given a file name 'filenm' and a vector of paths
// 'pathVec', use 'pathfind_r' to determine which path in 'pathVec',
// if any, reaches 'filenm'. Returns an index and string pair. If a
// match is found, the index is an index in pathVec; otherwise it is
// negative. If a match is found, the string is the found file name.
static std::pair<int, string>
matchFileWithPath(const string& filenm, const Analysis::PathTupleVec& pathVec)
{
// Find the index to the path that reaches 'filenm'.
// It is possible that more than one path could reach the same
// file because of substrings.
// E.g.: p1: /p1/p2/p3/*, p2: /p1/p2/*, f: /p1/p2/p3/f.c
// Choose the path that is most qualified (We assume RealPath length
// is valid test.)
int foundIndex = -1; // index into 'pathVec'
int foundPathLn = 0; // length of the path represented by 'foundIndex'
string foundFnm;
for (uint i = 0; i < pathVec.size(); i++) {
// find the absolute form of 'curPath'
const string& curPath = pathVec[i].first;
string realPath(curPath);
if (is_recursive_path(curPath.c_str())) {
realPath[realPath.length()-RECURSIVE_PATH_SUFFIX_LN] = '\0';
}
realPath = RealPath(realPath.c_str());
int realPathLn = realPath.length();
// 'filenm' should be relative as input for pathfind_r. If 'filenm'
// is absolute and 'realPath' is a prefix, make it relative.
string tmpFile(filenm);
char* curFile = const_cast<char*>(tmpFile.c_str());
if (filenm[0] == '/') { // is 'filenm' absolute?
if (strncmp(curFile, realPath.c_str(), realPathLn) == 0) {
curFile = &curFile[realPathLn];
while (curFile[0] == '/') { ++curFile; } // should not start with '/'
}
else {
continue; // pathfind_r can't posibly find anything
}
}
const char* fnd_fnm = pathfind_r(curPath.c_str(), curFile, "r");
if (fnd_fnm) {
bool update = false;
if (foundIndex < 0) {
update = true;
}
else if ((foundIndex >= 0) && (realPathLn > foundPathLn)) {
update = true;
}
if (update) {
foundIndex = i;
foundPathLn = realPathLn;
foundFnm = RealPath(fnd_fnm);
}
}
}
return make_pair(foundIndex, foundFnm);
}
// Given a file 'filenm' a destination directory 'dstDir' and a
// PathTuple, form a database file name, copy 'filenm' into the
// database and return the database file name.
// NOTE: assume filenm is already a 'real path'
static string
copySourceFile(const string& filenm, const string& dstDir,
const Analysis::PathTuple& pathTpl)
{
const string& fnm_fnd = filenm;
const string& viewnm = pathTpl.second;
// Create new file name and copy commands
string fnm_new = "./" + viewnm + fnm_fnd;
string fnm_to;
if (dstDir[0] != '/') {
fnm_to = "./";
}
fnm_to = fnm_to + dstDir + "/" + viewnm + fnm_fnd;
string dir_to(fnm_to); // need to strip off ending filename to
uint end; // get full path for 'fnm_to'
for (end = dir_to.length() - 1; dir_to[end] != '/'; end--) { }
dir_to[end] = '\0'; // should not end with '/'
string cmdMkdir = "mkdir -p " + dir_to;
string cmdCp = "cp -f " + fnm_fnd + " " + fnm_to;
//cerr << cmdCp << std::endl;
// mkdir(x, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
// could use CopyFile; see StaticFiles::Copy
if (system(cmdMkdir.c_str()) == 0 && system(cmdCp.c_str()) == 0) {
DIAG_DevMsgIf(0, "cp " << fnm_to);
}
else {
DIAG_EMsg("copying: '" << fnm_to);
}
return fnm_new;
}
//****************************************************************************
<commit_msg>Analysis::Util::getProfileType: rewrite to test magic string instead of filename extension.<commit_after>// -*-Mode: C++;-*-
// $Id$
// * BeginRiceCopyright *****************************************************
//
// Copyright ((c)) 2002-2007, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $Source$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
//************************* System Include Files ****************************
#include <iostream>
using std::cerr;
using std::hex;
using std::dec;
#include <string>
using std::string;
#include <cstring>
//*************************** User Include Files ****************************
#include "Util.hpp"
#include <lib/banal/bloop-simple.hpp>
#include <lib/prof-lean/hpcfile_csprof.h>
#include <lib/prof-lean/hpcfile_hpcrun.h>
#include <lib/support/diagnostics.h>
#include <lib/support/pathfind.h>
#include <lib/support/realpath.h>
//*************************** Forward Declarations **************************
//***************************************************************************
//***************************************************************************
//
//***************************************************************************
Analysis::Util::ProfType_t
Analysis::Util::getProfileType(const std::string& filenm)
{
static const int bufSZ = 32;
char buf[bufSZ] = { '\0' };
std::istream* is = IOUtil::OpenIStream(filenm.c_str());
is->read(buf, bufSZ);
IOUtil::CloseStream(is);
ProfType_t ty = ProfType_NULL;
if (strncmp(buf, HPCFILE_CSPROF_MAGIC_STR,
HPCFILE_CSPROF_MAGIC_STR_LEN) == 0) {
ty = ProfType_CALLPATH;
}
else if (strncmp(buf, HPCRUNFILE_MAGIC_STR,
HPCRUNFILE_MAGIC_STR_LEN) == 0) {
ty = ProfType_FLAT;
}
return ty;
}
//***************************************************************************
//
//***************************************************************************
// Always consult the load module's structure information
// (Struct::LM) and perform a lookup by VMA first. If this fails:
//
// - If the structure was seeded by full structure by
// bloop::makeStructure (useStruct), then use the "unknown" file
// and procedures.
//
// - Otherwise, create structure using banal::bloop::makeStructureSimple
//
// This policy assumes that when full structure has been provided,
// banal::bloop::makeStructureSimple could have undesirable effects. One
// example of a problem is that for simple structure, a line ->
// Struct::Stmt map is consulted which is ambiguous in the presence of
// inlinine (Struct::Alien).
Prof::Struct::ACodeNode*
Analysis::Util::demandStructure(VMA vma, Prof::Struct::LM* lmStrct, binutils::LM* lm, bool useStruct)
{
Prof::Struct::ACodeNode* strct = lmStrct->findByVMA(vma);
if (!strct) {
if (useStruct) {
Prof::Struct::File* fileStrct =
Prof::Struct::File::demand(lmStrct,
Prof::Struct::Tree::UnknownFileNm);
strct = Prof::Struct::Proc::demand(fileStrct,
Prof::Struct::Tree::UnknownProcNm);
}
else {
strct = banal::bloop::makeStructureSimple(lmStrct, lm, vma);
}
}
return strct;
}
//***************************************************************************
//
//***************************************************************************
static string
copySourceFileMain(const string& fnm_orig,
std::map<string, string>& processedFiles,
const Analysis::PathTupleVec& pathVec,
const string& dstDir);
static bool
Flat_Filter(const Prof::Struct::ANode& x, long type)
{
return (x.type() == Prof::Struct::ANode::TyFILE
|| x.type() == Prof::Struct::ANode::TyALIEN);
}
// copySourceFiles: For every Prof::Struct::File and
// Prof::Struct::Alien x in 'structure' that can be reached with paths
// in 'pathVec', copy x to its appropriate viewname path and update
// x's path to be relative to this location.
void
Analysis::Util::copySourceFiles(Prof::Struct::Root* structure,
const Analysis::PathTupleVec& pathVec,
const string& dstDir)
{
// Prevent multiple copies of the same file (Alien scopes)
std::map<string, string> processedFiles;
Prof::Struct::ANodeFilter filter(Flat_Filter, "Flat_Filter", 0);
for (Prof::Struct::ANodeIterator it(structure, &filter); it.Current(); ++it) {
Prof::Struct::ANode* strct = it.CurNode();
// Note: 'fnm_orig' will be not be absolute if it is not possible
// to resolve it on the current filesystem. (cf. RealPathMgr)
// DIAG_Assert( , DIAG_UnexpectedInput);
const string& fnm_orig = (typeid(*strct) == typeid(Prof::Struct::Alien)) ?
dynamic_cast<Prof::Struct::Alien*>(strct)->fileName() : strct->name();
// ------------------------------------------------------
// Given fnm_orig, attempt to find and copy fnm_new
// ------------------------------------------------------
string fnm_new =
copySourceFileMain(fnm_orig, processedFiles, pathVec, dstDir);
// ------------------------------------------------------
// Update static structure
// ------------------------------------------------------
if (!fnm_new.empty()) {
if (typeid(*strct) == typeid(Prof::Struct::Alien)) {
dynamic_cast<Prof::Struct::Alien*>(strct)->fileName(fnm_new);
}
else {
dynamic_cast<Prof::Struct::File*>(strct)->name(fnm_new);
}
}
}
}
static std::pair<int, string>
matchFileWithPath(const string& filenm, const Analysis::PathTupleVec& pathVec);
static string
copySourceFile(const string& filenm, const string& dstDir,
const Analysis::PathTuple& pathTpl);
static string
copySourceFileMain(const string& fnm_orig,
std::map<string, string>& processedFiles,
const Analysis::PathTupleVec& pathVec,
const string& dstDir)
{
string fnm_new;
std::map<string, string>::iterator it = processedFiles.find(fnm_orig);
if (it != processedFiles.end()) {
fnm_new = it->second;
}
else {
std::pair<int, string> fnd = matchFileWithPath(fnm_orig, pathVec);
int idx = fnd.first;
if (idx >= 0) {
// fnm_orig explicitly matches a <search-path, path-view> tuple
fnm_new = copySourceFile(fnd.second, dstDir, pathVec[idx]);
}
else if (fnm_orig[0] == '/' && FileUtil::isReadable(fnm_orig.c_str())) {
// fnm_orig does not match a pathVec tuple; but if it is an
// absolute path that is readable, use the default <search-path,
// path-view> tuple.
static const Analysis::PathTuple
defaultTpl("/", Analysis::DefaultPathTupleTarget);
fnm_new = copySourceFile(fnm_orig, dstDir, defaultTpl);
}
if (fnm_new.empty()) {
DIAG_WMsg(2, "lost: " << fnm_orig);
}
else {
DIAG_Msg(2, " cp:" << fnm_orig << " -> " << fnm_new);
}
processedFiles.insert(make_pair(fnm_orig, fnm_new));
}
return fnm_new;
}
//***************************************************************************
// matchFileWithPath: Given a file name 'filenm' and a vector of paths
// 'pathVec', use 'pathfind_r' to determine which path in 'pathVec',
// if any, reaches 'filenm'. Returns an index and string pair. If a
// match is found, the index is an index in pathVec; otherwise it is
// negative. If a match is found, the string is the found file name.
static std::pair<int, string>
matchFileWithPath(const string& filenm, const Analysis::PathTupleVec& pathVec)
{
// Find the index to the path that reaches 'filenm'.
// It is possible that more than one path could reach the same
// file because of substrings.
// E.g.: p1: /p1/p2/p3/*, p2: /p1/p2/*, f: /p1/p2/p3/f.c
// Choose the path that is most qualified (We assume RealPath length
// is valid test.)
int foundIndex = -1; // index into 'pathVec'
int foundPathLn = 0; // length of the path represented by 'foundIndex'
string foundFnm;
for (uint i = 0; i < pathVec.size(); i++) {
// find the absolute form of 'curPath'
const string& curPath = pathVec[i].first;
string realPath(curPath);
if (is_recursive_path(curPath.c_str())) {
realPath[realPath.length()-RECURSIVE_PATH_SUFFIX_LN] = '\0';
}
realPath = RealPath(realPath.c_str());
int realPathLn = realPath.length();
// 'filenm' should be relative as input for pathfind_r. If 'filenm'
// is absolute and 'realPath' is a prefix, make it relative.
string tmpFile(filenm);
char* curFile = const_cast<char*>(tmpFile.c_str());
if (filenm[0] == '/') { // is 'filenm' absolute?
if (strncmp(curFile, realPath.c_str(), realPathLn) == 0) {
curFile = &curFile[realPathLn];
while (curFile[0] == '/') { ++curFile; } // should not start with '/'
}
else {
continue; // pathfind_r can't posibly find anything
}
}
const char* fnd_fnm = pathfind_r(curPath.c_str(), curFile, "r");
if (fnd_fnm) {
bool update = false;
if (foundIndex < 0) {
update = true;
}
else if ((foundIndex >= 0) && (realPathLn > foundPathLn)) {
update = true;
}
if (update) {
foundIndex = i;
foundPathLn = realPathLn;
foundFnm = RealPath(fnd_fnm);
}
}
}
return make_pair(foundIndex, foundFnm);
}
// Given a file 'filenm' a destination directory 'dstDir' and a
// PathTuple, form a database file name, copy 'filenm' into the
// database and return the database file name.
// NOTE: assume filenm is already a 'real path'
static string
copySourceFile(const string& filenm, const string& dstDir,
const Analysis::PathTuple& pathTpl)
{
const string& fnm_fnd = filenm;
const string& viewnm = pathTpl.second;
// Create new file name and copy commands
string fnm_new = "./" + viewnm + fnm_fnd;
string fnm_to;
if (dstDir[0] != '/') {
fnm_to = "./";
}
fnm_to = fnm_to + dstDir + "/" + viewnm + fnm_fnd;
string dir_to(fnm_to); // need to strip off ending filename to
uint end; // get full path for 'fnm_to'
for (end = dir_to.length() - 1; dir_to[end] != '/'; end--) { }
dir_to[end] = '\0'; // should not end with '/'
string cmdMkdir = "mkdir -p " + dir_to;
string cmdCp = "cp -f " + fnm_fnd + " " + fnm_to;
//cerr << cmdCp << std::endl;
// mkdir(x, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
// could use CopyFile; see StaticFiles::Copy
if (system(cmdMkdir.c_str()) == 0 && system(cmdCp.c_str()) == 0) {
DIAG_DevMsgIf(0, "cp " << fnm_to);
}
else {
DIAG_EMsg("copying: '" << fnm_to);
}
return fnm_new;
}
//****************************************************************************
<|endoftext|> |
<commit_before>#include <string>
#include <cctype>
#include <fstream>
#include <unistd.h>
#include <string.h>
#include "lib/driver/Driver.hpp"
CSSP::Driver::~Driver() {
for(const auto pair : this->fileToTreeMap) {
while(!pair.second->empty()) {
delete pair.second->front();
pair.second->pop_front();
}
delete pair.second;
}
this->fileToTreeMap.clear();
if (this->lexer) {
delete this->lexer;
}
if (this->parser) {
delete this->parser;
}
}
int CSSP::Driver::parse(const char *const filename) {
if (filename == nullptr) {
this->error
<< "Failed to read from file"
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
std::string path = this->getRealPath(filename);
std::string name = basename(path.c_str());
std::string dir = path.substr(0, path.length() - name.length());
if (chdir(dir.c_str())) {
this->error
<< "Failed to change directory relative to main file: "
<< dir
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
this->directory = dir;
this->mainFileName = path;
this->pushFileToQueue(path);
this->processQueue();
return 0;
}
int CSSP::Driver::parse(std::istream &stream) {
if (!stream.good() && stream.eof()) {
this->error
<< "Failed to read from stream"
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
char temp[256];
getcwd(temp, 256);
this->directory = std::string(temp);
this->mainFileName = "STDIN";
this->currentFileName = "STDIN";
this->parseHelper(stream);
this->processQueue();
return 0;
}
int CSSP::Driver::parsePartial(const std::string filename) {
std::ifstream file(filename);
if (!file.good()) {
this->error
<< "Failed to read from file: "
<< filename
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
return this->parseHelper(file);
}
int CSSP::Driver::parseHelper(std::istream &stream) {
if (this->lexer != nullptr) {
delete this->lexer;
}
try {
lexer = new CSSP::Lexer(&stream);
}
catch (std::bad_alloc &ba) {
this->error
<< "Failed to allocate lexer: ("
<< ba.what()
<< ")"
<< this->error.end()
<< std::endl;
exit(EXIT_FAILURE);
}
if (this->parser != nullptr) {
delete this->parser;
}
try {
parser = new CSSP::Parser((*lexer), (*this));
}
catch (std::bad_alloc &ba) {
this->error
<< "Failed to allocate parser: ("
<< ba.what()
<< ")"
<< this->error.end()
<< std::endl;
exit(EXIT_FAILURE);
}
if (parser->parse() != EXIT_SUCCESS) {
this->error
<< "Parser failed - parser end in non-acceptable state"
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool CSSP::Driver::isFileInTree(std::string filename) {
FileToTreeMapType::const_iterator position;
position = this->fileToTreeMap.find(filename);
return position != this->fileToTreeMap.end();
}
void CSSP::Driver::pushFileToQueue(std::string filename) {
if (access(filename.c_str(), F_OK) != 0) {
this->error << "Cannot open file " << filename << this->error.end() << std::endl;
return;
}
std::string path = this->getRealPath(filename);
this->log
<< "Add file "
<< path
<< " into queue"
<< this->log.end()
<< std::endl;
this->fileQueue.push(path);
}
int CSSP::Driver::processQueue() {
while (!this->fileQueue.empty()) {
std::string filename = this->fileQueue.front();
if (!this->isFileInTree(filename)) {
this->log
<< "Parse file: "
<< filename
<< this->log.end()
<< std::endl;
this->currentFileName = filename;
this->parsePartial(filename);
} else {
this->log
<< "File: "
<< filename
<< " already in tree"
<< this->log.end()
<< std::endl;
}
this->fileQueue.pop();
}
return 0;
}
void CSSP::Driver::setNodesAsCurrentTreeElement(NodeListType *nodes) {
this->fileToTreeMap.insert(FileToTreePairType(
this->currentFileName,
nodes
));
}
int CSSP::Driver::debugQueue() {
this->log
<< "Debug queue"
<< this->log.end()
<< std::endl;
for (FileToTreeMapType::const_iterator i = this->fileToTreeMap.begin(); i != fileToTreeMap.end(); i++) {
this->log
<< "File: "
<< i->first
<< this->log.end()
<< std::endl;
NodeListType nodes = *i->second;
for (auto const node : nodes) {
this->log
<< node->debugString()
<< this->log.end()
<< std::endl;
}
}
this->log
<< "End queue"
<< this->log.end()
<< std::endl;
return 0;
}
CSSP::Generator *CSSP::Driver::getGenerator(bool minify) {
return new CSSP::Generator(
&this->fileToTreeMap,
this->mainFileName,
minify
);
}
std::string CSSP::Driver::getRealPath(std::string path) {
if (access(path.c_str(), F_OK) != 0) {
this->error << "Cannot open file " << path << this->error.end() << std::endl;
return std::string();
}
char *buffer = realpath(path.c_str(), nullptr);
std::string realPath = std::string(buffer);
delete buffer;
return realPath;
}
const FileToTreeMapType *CSSP::Driver::getFileToTreeMap() const {
return &(this->fileToTreeMap);
}
<commit_msg>fixed realpath valgrind issue<commit_after>#include <string>
#include <cctype>
#include <fstream>
#include <unistd.h>
#include <string.h>
#include "lib/driver/Driver.hpp"
CSSP::Driver::~Driver() {
for(const auto pair : this->fileToTreeMap) {
while(!pair.second->empty()) {
delete pair.second->front();
pair.second->pop_front();
}
delete pair.second;
}
this->fileToTreeMap.clear();
if (this->lexer) {
delete this->lexer;
}
if (this->parser) {
delete this->parser;
}
}
int CSSP::Driver::parse(const char *const filename) {
if (filename == nullptr) {
this->error
<< "Failed to read from file"
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
std::string path = this->getRealPath(filename);
std::string name = basename(path.c_str());
std::string dir = path.substr(0, path.length() - name.length());
if (chdir(dir.c_str())) {
this->error
<< "Failed to change directory relative to main file: "
<< dir
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
this->directory = dir;
this->mainFileName = path;
this->pushFileToQueue(path);
this->processQueue();
return 0;
}
int CSSP::Driver::parse(std::istream &stream) {
if (!stream.good() && stream.eof()) {
this->error
<< "Failed to read from stream"
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
char temp[2048];
getcwd(temp, 2048);
this->directory = std::string(temp);
this->mainFileName = "STDIN";
this->currentFileName = "STDIN";
this->parseHelper(stream);
this->processQueue();
return 0;
}
int CSSP::Driver::parsePartial(const std::string filename) {
std::ifstream file(filename);
if (!file.good()) {
this->error
<< "Failed to read from file: "
<< filename
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
return this->parseHelper(file);
}
int CSSP::Driver::parseHelper(std::istream &stream) {
if (this->lexer != nullptr) {
delete this->lexer;
}
try {
lexer = new CSSP::Lexer(&stream);
}
catch (std::bad_alloc &ba) {
this->error
<< "Failed to allocate lexer: ("
<< ba.what()
<< ")"
<< this->error.end()
<< std::endl;
exit(EXIT_FAILURE);
}
if (this->parser != nullptr) {
delete this->parser;
}
try {
parser = new CSSP::Parser((*lexer), (*this));
}
catch (std::bad_alloc &ba) {
this->error
<< "Failed to allocate parser: ("
<< ba.what()
<< ")"
<< this->error.end()
<< std::endl;
exit(EXIT_FAILURE);
}
if (parser->parse() != EXIT_SUCCESS) {
this->error
<< "Parser failed - parser end in non-acceptable state"
<< this->error.end()
<< std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool CSSP::Driver::isFileInTree(std::string filename) {
FileToTreeMapType::const_iterator position;
position = this->fileToTreeMap.find(filename);
return position != this->fileToTreeMap.end();
}
void CSSP::Driver::pushFileToQueue(std::string filename) {
if (access(filename.c_str(), F_OK) != 0) {
this->error << "Cannot open file " << filename << this->error.end() << std::endl;
return;
}
std::string path = this->getRealPath(filename);
this->log
<< "Add file "
<< path
<< " into queue"
<< this->log.end()
<< std::endl;
this->fileQueue.push(path);
}
int CSSP::Driver::processQueue() {
while (!this->fileQueue.empty()) {
std::string filename = this->fileQueue.front();
if (!this->isFileInTree(filename)) {
this->log
<< "Parse file: "
<< filename
<< this->log.end()
<< std::endl;
this->currentFileName = filename;
this->parsePartial(filename);
} else {
this->log
<< "File: "
<< filename
<< " already in tree"
<< this->log.end()
<< std::endl;
}
this->fileQueue.pop();
}
return 0;
}
void CSSP::Driver::setNodesAsCurrentTreeElement(NodeListType *nodes) {
this->fileToTreeMap.insert(FileToTreePairType(
this->currentFileName,
nodes
));
}
int CSSP::Driver::debugQueue() {
this->log
<< "Debug queue"
<< this->log.end()
<< std::endl;
for (FileToTreeMapType::const_iterator i = this->fileToTreeMap.begin(); i != fileToTreeMap.end(); i++) {
this->log
<< "File: "
<< i->first
<< this->log.end()
<< std::endl;
NodeListType nodes = *i->second;
for (auto const node : nodes) {
this->log
<< node->debugString()
<< this->log.end()
<< std::endl;
}
}
this->log
<< "End queue"
<< this->log.end()
<< std::endl;
return 0;
}
CSSP::Generator *CSSP::Driver::getGenerator(bool minify) {
return new CSSP::Generator(
&this->fileToTreeMap,
this->mainFileName,
minify
);
}
std::string CSSP::Driver::getRealPath(std::string path) {
if (access(path.c_str(), F_OK) != 0) {
this->error << "Cannot open file " << path << this->error.end() << std::endl;
return std::string();
}
char buffer[2048];
realpath(path.c_str(), buffer);
return std::string(buffer);
}
const FileToTreeMapType *CSSP::Driver::getFileToTreeMap() const {
return &(this->fileToTreeMap);
}
<|endoftext|> |
<commit_before>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#include "heightmap_loader.hpp"
#include "code/ylikuutio/geometry/quad_triangulation.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iomanip> // std::setfill, std::setw
#include <iostream> // std::cout, std::cin, std::cerr
#include <sstream> // std::stringstream
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace ontology
{
bool load_BMP_world(
std::string image_path,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals,
GLuint &image_width,
GLuint &image_height,
std::string color_channel,
std::string triangulation_type)
{
std::cout << "Loading BMP file " << image_path << " ...\n";
// Data read from the header of the BMP file
unsigned char header[54];
uint32_t imageSize;
// Actual RGB image data.
uint8_t *image_data;
// Open the file
const char* char_image_path = image_path.c_str();
std::FILE* file = std::fopen(char_image_path, "rb");
if (!file)
{
std::cerr << image_path << " could not be opened.\n";
return false;
}
// Read the header, i.e. the 54 first bytes
// If less than 54 bytes are read, it's a problem.
if (std::fread(header, 1, 54, file) != 54)
{
std::cerr << "not a correct BMP file.\n";
return false;
}
// A BMP files always begins with "BM"
if ((header[0] != 'B') || (header[1] != 'M'))
{
std::cerr << "not a correct BMP file.\n";
return false;
}
// Make sure this is a 24bpp file
if (*(uint32_t*) & (header[0x1E]) != 0)
{
std::cerr << "not a correct BMP file.\n";
return false;
}
if (*(uint32_t*) & (header[0x1C]) != 24)
{
std::cerr << "not a correct BMP file.\n";
return false;
}
// Read the information about the image
imageSize = *(uint32_t*) & (header[0x22]);
image_width = *(uint32_t*) & (header[0x12]);
image_height = *(uint32_t*) & (header[0x16]);
// Define world size.
uint32_t world_size = image_width * image_height;
// Some BMP files are misformatted, guess missing information
if (imageSize == 0)
{
imageSize = image_width * image_height * 3; // 3 : one byte for each Red, Green and Blue component
}
// Create a buffer.
image_data = new uint8_t [imageSize];
// Read the actual image data from the file into the buffer.
std::fread(image_data, 1, imageSize, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
GLuint* vertex_data;
vertex_data = new GLuint [world_size];
uint8_t *image_pointer;
image_pointer = image_data;
GLuint* vertex_pointer;
vertex_pointer = vertex_data;
const char* char_color_channel = color_channel.c_str();
// start processing image_data.
for (GLuint z = 0; z < image_height; z++)
{
for (GLuint x = 0; x < image_width; x++)
{
GLuint y;
if (std::strcmp(char_color_channel, "blue") == 0)
{
y = (GLuint) *image_pointer; // y-coordinate is the blue (B) value.
}
else if (std::strcmp(char_color_channel, "green") == 0)
{
y = (GLuint) *(image_pointer + 1); // y-coordinate is the green (G) value.
}
else if (std::strcmp(char_color_channel, "red") == 0)
{
y = (GLuint) *(image_pointer + 2); // y-coordinate is the red (R) value.
}
// y-coordinate is the mean of R, G, & B.
else if ((std::strcmp(char_color_channel, "mean") == 0) || (std::strcmp(char_color_channel, "all") == 0))
{
y = (((GLuint) *image_pointer) + ((GLuint) *(image_pointer + 1)) + ((GLuint) *(image_pointer + 2))) / 3;
}
else
{
std::cerr << "invalid color channel!\n";
return false;
}
// std::cout << color_channel << " color channel value at (" << x << ", " << z << "): " << y << ".\n";
*vertex_pointer++ = y;
image_pointer += 3; // R, G, & B.
}
}
std::cout << "color channel in use: " << color_channel << "\n";
TriangulateQuadsStruct triangulate_quads_struct;
triangulate_quads_struct.image_width = image_width;
triangulate_quads_struct.image_height = image_height;
triangulate_quads_struct.triangulation_type = triangulation_type;
triangulate_quads_struct.sphere_radius = NAN;
triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.
return geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
}
bool load_SRTM_world(
std::string image_path,
double latitude,
double longitude,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals,
std::string triangulation_type)
{
// For SRTM worlds, the right heightmap filename must be resolved first.
// The SRTM filenames contain always the southwest coordinate of the block.
// Each single SRTM file contains 1 degree of latitude and 1 degree of longiture. File size is 1201x1201.
// Precision is 3 arc-seconds in both latitude and longitude.
// In coordinates (`latitude` and `longitude`) negative values mean south for latitude and west for longitude,
// and positive value mean north for latitude and east for longitude.
// Therefore the SRTM heightmap filename can be resolved by rounding both latitude and longitude down (towards negative infinity).
int32_t filename_latitude = floor(latitude);
int32_t filename_longitude = floor(longitude);
double southern_latitude = floor(latitude);
double western_longitude = floor(longitude);
double northern_latitude = southern_latitude + 1.0f;
double eastern_longitude = western_longitude + 1.0f;
std::string south_north_char;
std::string west_east_char;
if (filename_latitude < 0)
{
// negative latitudes mean southern hemisphere.
south_north_char = "S";
}
else
{
// positive latitudes mean northern hemisphere.
south_north_char = "N";
}
if (filename_longitude < 0)
{
// negative longitudes mean western hemisphere.
west_east_char = "W";
}
else
{
// positive longitudes mean eastern hemisphere.
west_east_char = "E";
}
std::stringstream latitude_stringstream;
std::stringstream longitude_stringstream;
uint32_t SRTM_filename_n_of_latitude_chars = 2;
uint32_t SRTM_filename_n_of_longitude_chars = 3;
latitude_stringstream << std::setw(SRTM_filename_n_of_latitude_chars) << std::setfill('0') << abs(filename_latitude);
longitude_stringstream << std::setw(SRTM_filename_n_of_longitude_chars) << std::setfill('0') << abs(filename_longitude);
std::string latitude_string = latitude_stringstream.str();
std::string longitude_string = longitude_stringstream.str();
std::string hgt_suffix = ".hgt";
std::string abs_image_path = image_path + south_north_char + latitude_string + west_east_char + longitude_string + hgt_suffix;
std::cout << "Loading SRTM file " << abs_image_path << " ...\n";
uint32_t imageSize;
uint32_t true_image_width, true_image_height, image_width_in_use, image_height_in_use;
// Actual 16-bit big-endian signed integer heightmap data.
uint8_t *image_data;
// Open the file
const char* char_image_path = abs_image_path.c_str();
std::FILE* file = std::fopen(char_image_path, "rb");
if (!file)
{
std::cerr << abs_image_path << " could not be opened.\n";
return false;
}
true_image_width = 1201;
true_image_height = 1201;
image_width_in_use = 1200;
image_height_in_use = 1200;
imageSize = sizeof(int16_t) * true_image_width * true_image_height;
// Create a buffer.
image_data = new uint8_t [imageSize];
// Read the actual image data from the file into the buffer.
std::fread(image_data, 1, imageSize, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
GLuint* vertex_data;
vertex_data = new GLuint [image_width_in_use * image_height_in_use];
uint8_t *image_pointer;
image_pointer = image_data + sizeof(int16_t) * (true_image_height - 1) * true_image_width; // start from southwestern corner.
GLuint* vertex_pointer;
vertex_pointer = vertex_data;
// start processing image_data.
// 90 meters is for equator.
// FIXME: this is a temporary testing code with a hardcoded start from the southwestern corner.
// TODO: write a proper code for loading the appropriate chunks (based on real spherical coordinates) into VBOs!
for (GLuint z = 0; z < image_height_in_use; z++)
{
for (GLuint x = 0; x < image_width_in_use; x++)
{
GLuint y;
y = ((((GLuint) *image_pointer) << 8) | ((GLuint) *(image_pointer + 1)));
image_pointer += sizeof(int16_t);
*vertex_pointer++ = y;
}
image_pointer -= sizeof(int16_t) * (image_width_in_use + true_image_width);
}
SphericalWorldStruct spherical_world_struct;
spherical_world_struct.southern_latitude = southern_latitude; // must be double, though SRTM data is split between full degrees.
spherical_world_struct.northern_latitude = northern_latitude; // must be double, though SRTM data is split between full degrees.
spherical_world_struct.western_longitude = western_longitude; // must be double, though SRTM data is split between full degrees.
spherical_world_struct.eastern_longitude = eastern_longitude; // must be double, though SRTM data is split between full degrees.
TriangulateQuadsStruct triangulate_quads_struct;
triangulate_quads_struct.image_width = image_width_in_use;
triangulate_quads_struct.image_height = image_height_in_use;
triangulate_quads_struct.triangulation_type = triangulation_type;
triangulate_quads_struct.sphere_radius = EARTH_RADIUS;
triangulate_quads_struct.spherical_world_struct = spherical_world_struct;
return geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
}
}
<commit_msg>`(GLuint)` -> `static_cast<GLuint>` x 2.<commit_after>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#include "heightmap_loader.hpp"
#include "code/ylikuutio/geometry/quad_triangulation.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iomanip> // std::setfill, std::setw
#include <iostream> // std::cout, std::cin, std::cerr
#include <sstream> // std::stringstream
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace ontology
{
bool load_BMP_world(
std::string image_path,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals,
GLuint &image_width,
GLuint &image_height,
std::string color_channel,
std::string triangulation_type)
{
std::cout << "Loading BMP file " << image_path << " ...\n";
// Data read from the header of the BMP file
unsigned char header[54];
uint32_t imageSize;
// Actual RGB image data.
uint8_t *image_data;
// Open the file
const char* char_image_path = image_path.c_str();
std::FILE* file = std::fopen(char_image_path, "rb");
if (!file)
{
std::cerr << image_path << " could not be opened.\n";
return false;
}
// Read the header, i.e. the 54 first bytes
// If less than 54 bytes are read, it's a problem.
if (std::fread(header, 1, 54, file) != 54)
{
std::cerr << "not a correct BMP file.\n";
return false;
}
// A BMP files always begins with "BM"
if ((header[0] != 'B') || (header[1] != 'M'))
{
std::cerr << "not a correct BMP file.\n";
return false;
}
// Make sure this is a 24bpp file
if (*(uint32_t*) & (header[0x1E]) != 0)
{
std::cerr << "not a correct BMP file.\n";
return false;
}
if (*(uint32_t*) & (header[0x1C]) != 24)
{
std::cerr << "not a correct BMP file.\n";
return false;
}
// Read the information about the image
imageSize = *(uint32_t*) & (header[0x22]);
image_width = *(uint32_t*) & (header[0x12]);
image_height = *(uint32_t*) & (header[0x16]);
// Define world size.
uint32_t world_size = image_width * image_height;
// Some BMP files are misformatted, guess missing information
if (imageSize == 0)
{
imageSize = image_width * image_height * 3; // 3 : one byte for each Red, Green and Blue component
}
// Create a buffer.
image_data = new uint8_t [imageSize];
// Read the actual image data from the file into the buffer.
std::fread(image_data, 1, imageSize, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
GLuint* vertex_data;
vertex_data = new GLuint [world_size];
uint8_t *image_pointer;
image_pointer = image_data;
GLuint* vertex_pointer;
vertex_pointer = vertex_data;
const char* char_color_channel = color_channel.c_str();
// start processing image_data.
for (GLuint z = 0; z < image_height; z++)
{
for (GLuint x = 0; x < image_width; x++)
{
GLuint y;
if (std::strcmp(char_color_channel, "blue") == 0)
{
y = (GLuint) *image_pointer; // y-coordinate is the blue (B) value.
}
else if (std::strcmp(char_color_channel, "green") == 0)
{
y = (GLuint) *(image_pointer + 1); // y-coordinate is the green (G) value.
}
else if (std::strcmp(char_color_channel, "red") == 0)
{
y = (GLuint) *(image_pointer + 2); // y-coordinate is the red (R) value.
}
// y-coordinate is the mean of R, G, & B.
else if ((std::strcmp(char_color_channel, "mean") == 0) || (std::strcmp(char_color_channel, "all") == 0))
{
y = (((GLuint) *image_pointer) + ((GLuint) *(image_pointer + 1)) + ((GLuint) *(image_pointer + 2))) / 3;
}
else
{
std::cerr << "invalid color channel!\n";
return false;
}
// std::cout << color_channel << " color channel value at (" << x << ", " << z << "): " << y << ".\n";
*vertex_pointer++ = y;
image_pointer += 3; // R, G, & B.
}
}
std::cout << "color channel in use: " << color_channel << "\n";
TriangulateQuadsStruct triangulate_quads_struct;
triangulate_quads_struct.image_width = image_width;
triangulate_quads_struct.image_height = image_height;
triangulate_quads_struct.triangulation_type = triangulation_type;
triangulate_quads_struct.sphere_radius = NAN;
triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.
return geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
}
bool load_SRTM_world(
std::string image_path,
double latitude,
double longitude,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals,
std::string triangulation_type)
{
// For SRTM worlds, the right heightmap filename must be resolved first.
// The SRTM filenames contain always the southwest coordinate of the block.
// Each single SRTM file contains 1 degree of latitude and 1 degree of longiture. File size is 1201x1201.
// Precision is 3 arc-seconds in both latitude and longitude.
// In coordinates (`latitude` and `longitude`) negative values mean south for latitude and west for longitude,
// and positive value mean north for latitude and east for longitude.
// Therefore the SRTM heightmap filename can be resolved by rounding both latitude and longitude down (towards negative infinity).
int32_t filename_latitude = floor(latitude);
int32_t filename_longitude = floor(longitude);
double southern_latitude = floor(latitude);
double western_longitude = floor(longitude);
double northern_latitude = southern_latitude + 1.0f;
double eastern_longitude = western_longitude + 1.0f;
std::string south_north_char;
std::string west_east_char;
if (filename_latitude < 0)
{
// negative latitudes mean southern hemisphere.
south_north_char = "S";
}
else
{
// positive latitudes mean northern hemisphere.
south_north_char = "N";
}
if (filename_longitude < 0)
{
// negative longitudes mean western hemisphere.
west_east_char = "W";
}
else
{
// positive longitudes mean eastern hemisphere.
west_east_char = "E";
}
std::stringstream latitude_stringstream;
std::stringstream longitude_stringstream;
uint32_t SRTM_filename_n_of_latitude_chars = 2;
uint32_t SRTM_filename_n_of_longitude_chars = 3;
latitude_stringstream << std::setw(SRTM_filename_n_of_latitude_chars) << std::setfill('0') << abs(filename_latitude);
longitude_stringstream << std::setw(SRTM_filename_n_of_longitude_chars) << std::setfill('0') << abs(filename_longitude);
std::string latitude_string = latitude_stringstream.str();
std::string longitude_string = longitude_stringstream.str();
std::string hgt_suffix = ".hgt";
std::string abs_image_path = image_path + south_north_char + latitude_string + west_east_char + longitude_string + hgt_suffix;
std::cout << "Loading SRTM file " << abs_image_path << " ...\n";
uint32_t imageSize;
uint32_t true_image_width, true_image_height, image_width_in_use, image_height_in_use;
// Actual 16-bit big-endian signed integer heightmap data.
uint8_t *image_data;
// Open the file
const char* char_image_path = abs_image_path.c_str();
std::FILE* file = std::fopen(char_image_path, "rb");
if (!file)
{
std::cerr << abs_image_path << " could not be opened.\n";
return false;
}
true_image_width = 1201;
true_image_height = 1201;
image_width_in_use = 1200;
image_height_in_use = 1200;
imageSize = sizeof(int16_t) * true_image_width * true_image_height;
// Create a buffer.
image_data = new uint8_t [imageSize];
// Read the actual image data from the file into the buffer.
std::fread(image_data, 1, imageSize, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
GLuint* vertex_data;
vertex_data = new GLuint [image_width_in_use * image_height_in_use];
uint8_t *image_pointer;
image_pointer = image_data + sizeof(int16_t) * (true_image_height - 1) * true_image_width; // start from southwestern corner.
GLuint* vertex_pointer;
vertex_pointer = vertex_data;
// start processing image_data.
// 90 meters is for equator.
// FIXME: this is a temporary testing code with a hardcoded start from the southwestern corner.
// TODO: write a proper code for loading the appropriate chunks (based on real spherical coordinates) into VBOs!
for (GLuint z = 0; z < image_height_in_use; z++)
{
for (GLuint x = 0; x < image_width_in_use; x++)
{
GLuint y;
y = static_cast<GLuint>(*image_pointer) << 8 | static_cast<GLuint>(*(image_pointer + 1));
image_pointer += sizeof(int16_t);
*vertex_pointer++ = y;
}
image_pointer -= sizeof(int16_t) * (image_width_in_use + true_image_width);
}
SphericalWorldStruct spherical_world_struct;
spherical_world_struct.southern_latitude = southern_latitude; // must be double, though SRTM data is split between full degrees.
spherical_world_struct.northern_latitude = northern_latitude; // must be double, though SRTM data is split between full degrees.
spherical_world_struct.western_longitude = western_longitude; // must be double, though SRTM data is split between full degrees.
spherical_world_struct.eastern_longitude = eastern_longitude; // must be double, though SRTM data is split between full degrees.
TriangulateQuadsStruct triangulate_quads_struct;
triangulate_quads_struct.image_width = image_width_in_use;
triangulate_quads_struct.image_height = image_height_in_use;
triangulate_quads_struct.triangulation_type = triangulation_type;
triangulate_quads_struct.sphere_radius = EARTH_RADIUS;
triangulate_quads_struct.spherical_world_struct = spherical_world_struct;
return geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: TypeGeneration.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2003-03-19 15:58:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COMPHELPER_TYPEGENERATION_HXX_
#define _COMPHELPER_TYPEGENERATION_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#define CPPU_E2T(type) ((com::sun::star::uno::Type*)type)
namespace com { namespace sun { namespace star { namespace uno {
class Type;
} } } }
namespace comphelper
{
enum CppuTypes
{
CPPUTYPE_UNKNOWN, // 0 == unknown == error!!!!
CPPUTYPE_BOOLEAN, //getBooleanCppuType()
CPPUTYPE_INT8, //getCppuType( (sal_Int8*)0 )
CPPUTYPE_INT16, //getCppuType( (sal_Int16*)0 )
CPPUTYPE_INT32, //getCppuType( (sal_Int32*)0 )
CPPUTYPE_DOUBLE, //getCppuType( (double*)0 )
CPPUTYPE_FLOAT, //getCppuType( (float*)0 )
CPPUTYPE_OUSTRING, //getCppuType( (OUString*)0 )
CPPUTYPE_FONTSLANT, //getCppuType( (FontSlant*)0 )
CPPUTYPE_LOCALE, //getCppuType( (Locale*)0 )
CPPUTYPE_PROPERTYVALUE, //getCppuType( (Sequence<PropertyValue>*)0 )
CPPUTYPE_PROPERTYVALUES, //getCppuType( (Sequence<PropertyValues>*)0 )
CPPUTYPE_BORDERLINE, //getCppuType( (table::BorderLine*)0 )
CPPUTYPE_BREAK, //getCppuType( (style::BreakType*)0 )
CPPUTYPE_GRAPHICLOC, //getCppuType( (style::GraphicLocation*)0 )
CPPUTYPE_DROPCAPFMT, //getCppuType( (style::DropCapFormat*)0 )
CPPUTYPE_LINESPACE, //getCppuType( (style::LineSpacing*)0 )
CPPUTYPE_AWTSIZE, //getCppuType( (awt::Size*)0 )
CPPUTYPE_SHADOWFMT, //getCppuType( (table::ShadowFormat*)0 )
CPPUTYPE_TBLCOLSEP, //getCppuType( (Sequence<text::TableColumnSeparator>*)0 )
CPPUTYPE_PNTSEQSEQ, //getCppuType( (PointSequenceSequence*)0 )
CPPUTYPE_DOCIDXMRK, //getCppuType( (Sequence< Reference< XDocumentIndexMark > >*)0 )
CPPUTYPE_SEQINT8, //getCppuType( (Sequence<sal_Int8>*)0 )
CPPUTYPE_SEQTABSTOP, //getCppuType( (Sequence<style::TabStop>*)0 )
CPPUTYPE_SEQANCHORTYPE, //getCppuType( (Sequence<text::TextContentAnchorType>*)0 )
CPPUTYPE_SEQDEPTXTFLD, //getCppuType( (Sequence<Reference<XDependentTextField> >*)0 )
CPPUTYPE_TXTCNTANCHOR, //getCppuType( (text::TextContentAnchorType*)0 )
CPPUTYPE_WRAPTXTMODE, //getCppuType( (text::WrapTextMode*)0 )
CPPUTYPE_COLORMODE, //getCppuType( (drawing::ColorMode*)0 )
CPPUTYPE_PAGESTYLELAY, //getCppuType( (style::PageStyleLayout*)0 )
CPPUTYPE_VERTALIGN, //getCppuType( (style::VerticalAlignment*)0 )
CPPUTYPE_TABLEBORDER, //getCppuType( (table::TableBorder*)0 )
CPPUTYPE_GRFCROP, //getCppuType( (text::GraphicCrop*)0 )
CPPUTYPE_SECTFILELNK, //getCppuType( (text::SectionFileLink*)0 )
CPPUTYPE_PAGENUMTYPE, //getCppuType( (const PageNumberType*)0 )
CPPUTYPE_DATETIME, //getCppuType( (util::DateTime*)0 )
CPPUTYPE_DATE, //getCppuType( (util::Date*)0 )
CPPUTYPE_REFINTERFACE, //getCppuType( (Reference<XInterface>*)0 )
CPPUTYPE_REFIDXREPL, //getCppuType( (Reference<container::XIndexReplace>*)0 )
CPPUTYPE_REFNAMECNT, //getCppuType( (Reference<container::XNameContainer>*)0 )
CPPUTYPE_REFTEXTFRAME, //getCppuType( (Reference<text::XTextFrame>*)0 )
CPPUTYPE_REFTEXTSECTION, //getCppuType( (Reference<text::XTextSection>*)0 )
CPPUTYPE_REFFOOTNOTE, //getCppuType( (Reference<text::XFootnote>*)0 )
CPPUTYPE_REFTEXT, //getCppuType( (Reference<text::XText>*)0 )
CPPUTYPE_REFTEXTCOL, //getCppuType( (Reference<text::XTextColumns>*)0 )
CPPUTYPE_REFFORBCHARS, //getCppuType( (Reference<XForbiddenCharacters>*)0)
CPPUTYPE_REFIDXCNTNR, //getCppuType( (Reference<XIndexContainer>*)0)
CPPUTYPE_REFTEXTCNTNT, //getCppuType( (Reference<XTextContent>*)0)
CPPUTYPE_REFBITMAP, //getCppuType( (Reference<awt::XBitmap>*)0)
CPPUTYPE_REFNMREPLACE, //getCppuType( (Reference<container::XNameReplace>*)0)
CPPUTYPE_REFCELL, //getCppuType( (Reference<table::XCell>*)0)
CPPUTYPE_REFDOCINDEX, //getCppuType( (Reference<text::XDocumentIndex>*)0)
CPPUTYPE_REFDOCIDXMRK, //getCppuType( (Reference<text::XDocumentIndexMark>*)0)
CPPUTYPE_REFTXTFIELD, //getCppuType( (Reference<text::XTextField>*)0)
CPPUTYPE_REFTXTRANGE, //getCppuType( (Reference<text::XTextRange>*)0)
CPPUTYPE_REFTXTTABLE, //getCppuType( (Reference<text::XTextTable>*)0)
CPPUTYPE_AWTPOINT, //getCppuType( (awt::Point*)0 )
CPPUTYPE_REFLIBCONTAINER, //getCppuType( (Reference< script::XLibraryContainer >*)0)
CPPUTYPE_SEQANY, //getCppuType( (Sequence< uno::Any >*)0)
CPPUTYPE_REFRESULTSET, //getCppuType( (Reference< sdbc::XResultSet >*)0)
CPPUTYPE_REFCONNECTION, //getCppuType( (Reference< sdbc::XConnection >*)0)
CPPUTYPE_REFMODEL, //getCppuType( (Reference< frame::XModel >*)0)
CPPUTYPE_OUSTRINGS, //getCppuType( (Sequence<OUString>*)0 )
CPPUTYPE_END
};
void GenerateCppuType ( sal_uInt16 eType, const com::sun::star::uno::Type*& pType );
}
#endif
<commit_msg>INTEGRATION: CWS os8 (1.6.4); FILE MERGED 2003/04/07 06:41:30 os 1.6.4.1: #108472# XComponent added<commit_after>/*************************************************************************
*
* $RCSfile: TypeGeneration.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2003-04-17 13:27:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COMPHELPER_TYPEGENERATION_HXX_
#define _COMPHELPER_TYPEGENERATION_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#define CPPU_E2T(type) ((com::sun::star::uno::Type*)type)
namespace com { namespace sun { namespace star { namespace uno {
class Type;
} } } }
namespace comphelper
{
enum CppuTypes
{
CPPUTYPE_UNKNOWN, // 0 == unknown == error!!!!
CPPUTYPE_BOOLEAN, //getBooleanCppuType()
CPPUTYPE_INT8, //getCppuType( (sal_Int8*)0 )
CPPUTYPE_INT16, //getCppuType( (sal_Int16*)0 )
CPPUTYPE_INT32, //getCppuType( (sal_Int32*)0 )
CPPUTYPE_DOUBLE, //getCppuType( (double*)0 )
CPPUTYPE_FLOAT, //getCppuType( (float*)0 )
CPPUTYPE_OUSTRING, //getCppuType( (OUString*)0 )
CPPUTYPE_FONTSLANT, //getCppuType( (FontSlant*)0 )
CPPUTYPE_LOCALE, //getCppuType( (Locale*)0 )
CPPUTYPE_PROPERTYVALUE, //getCppuType( (Sequence<PropertyValue>*)0 )
CPPUTYPE_PROPERTYVALUES, //getCppuType( (Sequence<PropertyValues>*)0 )
CPPUTYPE_BORDERLINE, //getCppuType( (table::BorderLine*)0 )
CPPUTYPE_BREAK, //getCppuType( (style::BreakType*)0 )
CPPUTYPE_GRAPHICLOC, //getCppuType( (style::GraphicLocation*)0 )
CPPUTYPE_DROPCAPFMT, //getCppuType( (style::DropCapFormat*)0 )
CPPUTYPE_LINESPACE, //getCppuType( (style::LineSpacing*)0 )
CPPUTYPE_AWTSIZE, //getCppuType( (awt::Size*)0 )
CPPUTYPE_SHADOWFMT, //getCppuType( (table::ShadowFormat*)0 )
CPPUTYPE_TBLCOLSEP, //getCppuType( (Sequence<text::TableColumnSeparator>*)0 )
CPPUTYPE_PNTSEQSEQ, //getCppuType( (PointSequenceSequence*)0 )
CPPUTYPE_DOCIDXMRK, //getCppuType( (Sequence< Reference< XDocumentIndexMark > >*)0 )
CPPUTYPE_SEQINT8, //getCppuType( (Sequence<sal_Int8>*)0 )
CPPUTYPE_SEQTABSTOP, //getCppuType( (Sequence<style::TabStop>*)0 )
CPPUTYPE_SEQANCHORTYPE, //getCppuType( (Sequence<text::TextContentAnchorType>*)0 )
CPPUTYPE_SEQDEPTXTFLD, //getCppuType( (Sequence<Reference<XDependentTextField> >*)0 )
CPPUTYPE_TXTCNTANCHOR, //getCppuType( (text::TextContentAnchorType*)0 )
CPPUTYPE_WRAPTXTMODE, //getCppuType( (text::WrapTextMode*)0 )
CPPUTYPE_COLORMODE, //getCppuType( (drawing::ColorMode*)0 )
CPPUTYPE_PAGESTYLELAY, //getCppuType( (style::PageStyleLayout*)0 )
CPPUTYPE_VERTALIGN, //getCppuType( (style::VerticalAlignment*)0 )
CPPUTYPE_TABLEBORDER, //getCppuType( (table::TableBorder*)0 )
CPPUTYPE_GRFCROP, //getCppuType( (text::GraphicCrop*)0 )
CPPUTYPE_SECTFILELNK, //getCppuType( (text::SectionFileLink*)0 )
CPPUTYPE_PAGENUMTYPE, //getCppuType( (const PageNumberType*)0 )
CPPUTYPE_DATETIME, //getCppuType( (util::DateTime*)0 )
CPPUTYPE_DATE, //getCppuType( (util::Date*)0 )
CPPUTYPE_REFINTERFACE, //getCppuType( (Reference<XInterface>*)0 )
CPPUTYPE_REFIDXREPL, //getCppuType( (Reference<container::XIndexReplace>*)0 )
CPPUTYPE_REFNAMECNT, //getCppuType( (Reference<container::XNameContainer>*)0 )
CPPUTYPE_REFTEXTFRAME, //getCppuType( (Reference<text::XTextFrame>*)0 )
CPPUTYPE_REFTEXTSECTION, //getCppuType( (Reference<text::XTextSection>*)0 )
CPPUTYPE_REFFOOTNOTE, //getCppuType( (Reference<text::XFootnote>*)0 )
CPPUTYPE_REFTEXT, //getCppuType( (Reference<text::XText>*)0 )
CPPUTYPE_REFTEXTCOL, //getCppuType( (Reference<text::XTextColumns>*)0 )
CPPUTYPE_REFFORBCHARS, //getCppuType( (Reference<XForbiddenCharacters>*)0)
CPPUTYPE_REFIDXCNTNR, //getCppuType( (Reference<XIndexContainer>*)0)
CPPUTYPE_REFTEXTCNTNT, //getCppuType( (Reference<XTextContent>*)0)
CPPUTYPE_REFBITMAP, //getCppuType( (Reference<awt::XBitmap>*)0)
CPPUTYPE_REFNMREPLACE, //getCppuType( (Reference<container::XNameReplace>*)0)
CPPUTYPE_REFCELL, //getCppuType( (Reference<table::XCell>*)0)
CPPUTYPE_REFDOCINDEX, //getCppuType( (Reference<text::XDocumentIndex>*)0)
CPPUTYPE_REFDOCIDXMRK, //getCppuType( (Reference<text::XDocumentIndexMark>*)0)
CPPUTYPE_REFTXTFIELD, //getCppuType( (Reference<text::XTextField>*)0)
CPPUTYPE_REFTXTRANGE, //getCppuType( (Reference<text::XTextRange>*)0)
CPPUTYPE_REFTXTTABLE, //getCppuType( (Reference<text::XTextTable>*)0)
CPPUTYPE_AWTPOINT, //getCppuType( (awt::Point*)0 )
CPPUTYPE_REFLIBCONTAINER, //getCppuType( (Reference< script::XLibraryContainer >*)0)
CPPUTYPE_SEQANY, //getCppuType( (Sequence< uno::Any >*)0)
CPPUTYPE_REFRESULTSET, //getCppuType( (Reference< sdbc::XResultSet >*)0)
CPPUTYPE_REFCONNECTION, //getCppuType( (Reference< sdbc::XConnection >*)0)
CPPUTYPE_REFMODEL, //getCppuType( (Reference< frame::XModel >*)0)
CPPUTYPE_OUSTRINGS, //getCppuType( (Sequence<OUString>*)0 )
CPPUTYPE_REFCOMPONENT, //getCppuType( (Reference< lang::XComponent >*)0 )
CPPUTYPE_END
};
void GenerateCppuType ( sal_uInt16 eType, const com::sun::star::uno::Type*& pType );
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AIndexes.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:29:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_ADO_INDEXES_HXX_
#include "ado/AIndexes.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#include "ado/AIndex.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_
#include <com/sun/star/sdbc/IndexType.hpp>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;
sdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)
{
return new OAdoIndex(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OIndexes::impl_refresh() throw(RuntimeException)
{
m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OIndexes::createEmptyObject()
{
return new OAdoIndex(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
void OIndexes::appendObject( const Reference< XPropertySet >& descriptor )
{
OAdoIndex* pIndex = NULL;
sal_Bool bError = sal_True;
if(getImplementation(pIndex,descriptor) && pIndex != NULL)
{
ADOIndexes* pIndexes = m_aCollection;
bError = FAILED(pIndexes->Append(OLEVariant(getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))),
OLEVariant(pIndex->getImpl())));
}
if(bError)
throw SQLException(::rtl::OUString::createFromAscii("Could not append index!"),static_cast<XTypeProvider*>(this),OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_HY0000),1000,Any());
}
// -------------------------------------------------------------------------
// XDrop
void OIndexes::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
m_aCollection.Delete(_sElementName);
}
// -------------------------------------------------------------------------
sdbcx::ObjectType OIndexes::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
OAdoIndex* pIndex = NULL;
if(getImplementation(pIndex,_xDescriptor) && pIndex != NULL)
return new OAdoIndex(isCaseSensitive(),m_pConnection,pIndex->getImpl());
return sdbcx::ObjectType();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS warnings01 (1.13.30); FILE MERGED 2005/12/22 11:44:35 fs 1.13.30.1: #i57457# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AIndexes.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:14:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_ADO_INDEXES_HXX_
#include "ado/AIndexes.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#include "ado/AIndex.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_
#include <com/sun/star/sdbc/IndexType.hpp>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;
sdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)
{
return new OAdoIndex(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OIndexes::impl_refresh() throw(RuntimeException)
{
m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OIndexes::createEmptyObject()
{
return new OAdoIndex(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
void OIndexes::appendObject( const Reference< XPropertySet >& descriptor )
{
OAdoIndex* pIndex = NULL;
sal_Bool bError = sal_True;
if(getImplementation(pIndex,descriptor) && pIndex != NULL)
{
ADOIndexes* pIndexes = m_aCollection;
bError = FAILED(pIndexes->Append(OLEVariant(getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))),
OLEVariant(pIndex->getImpl())));
}
if(bError)
throw SQLException(::rtl::OUString::createFromAscii("Could not append index!"),static_cast<XTypeProvider*>(this),OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_HY0000),1000,Any());
}
// -------------------------------------------------------------------------
// XDrop
void OIndexes::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
m_aCollection.Delete(_sElementName);
}
// -------------------------------------------------------------------------
sdbcx::ObjectType OIndexes::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
OAdoIndex* pIndex = NULL;
if(getImplementation(pIndex,_xDescriptor) && pIndex != NULL)
return new OAdoIndex(isCaseSensitive(),m_pConnection,pIndex->getImpl());
return sdbcx::ObjectType();
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ETables.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: oj $ $Date: 2002-10-08 08:25:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_FLAT_TABLES_HXX_
#include "flat/ETables.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_
#include "flat/ETable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity::flat;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
namespace starutil = ::com::sun::star::util;
Reference< XNamed > OFlatTables::createObject(const ::rtl::OUString& _rName)
{
OFlatTable* pRet = new OFlatTable(this,(OFlatConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
_rName,::rtl::OUString::createFromAscii("TABLE"));
Reference< XNamed > xRet = pRet;
pRet->construct();
return xRet;
}
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba24 (1.11.240); FILE MERGED 2005/02/09 08:07:46 oj 1.11.240.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
*
* $RCSfile: ETables.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2005-03-10 15:29:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_FLAT_TABLES_HXX_
#include "flat/ETables.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_
#include "flat/ETable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace connectivity;
using namespace ::comphelper;
using namespace connectivity::flat;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
namespace starutil = ::com::sun::star::util;
sdbcx::ObjectType OFlatTables::createObject(const ::rtl::OUString& _rName)
{
OFlatTable* pRet = new OFlatTable(this,(OFlatConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
_rName,::rtl::OUString::createFromAscii("TABLE"));
sdbcx::ObjectType xRet = pRet;
pRet->construct();
return xRet;
}
// -------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014-15, Richard Eakin - All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "mason/FileWatcher.h"
#include "mason/Profiling.h"
#include "cinder/app/App.h"
#include "cinder/Log.h"
//#define LOG_UPDATE( stream ) CI_LOG_I( stream )
#define LOG_UPDATE( stream ) ( (void)( 0 ) )
using namespace ci;
using namespace std;
namespace mason {
//! Base class for Watch types, which are returned from FileWatcher::load() and watch()
class Watch : public std::enable_shared_from_this<Watch>, private ci::Noncopyable {
public:
virtual ~Watch() = default;
//! Checks if the asset file is up-to-date. Also may discard the Watch if there are no more connected slots.
virtual void checkCurrent() = 0;
//! Remove any watches for \a filePath. If it is the last file associated with this Watch, discard
virtual void unwatch( const fs::path &filePath ) = 0;
//! Emit the signal callback.
virtual void emitCallback() = 0;
//! Marks the Watch as needing its callback to be emitted on the main thread.
void setNeedsCallback( bool b ) { mNeedsCallback = b; }
//! Returns whether the Watch needs its callback emitted on the main thread.
bool needsCallback() const { return mNeedsCallback; }
//! Marks the Watch as discarded, will be destroyed the next update loop
void markDiscarded() { mDiscarded = true; }
//! Returns whether the Watch is discarded and should be destroyed.
bool isDiscarded() const { return mDiscarded; }
private:
bool mDiscarded = false;
bool mNeedsCallback = false;
};
//! Handles a single live asset
class WatchSingle : public Watch {
public:
WatchSingle( const ci::fs::path &filePath );
signals::Connection connect( const function<void ( const ci::fs::path& )> &callback ) { return mSignalChanged.connect( callback ); }
void checkCurrent() override;
void unwatch( const fs::path &filePath ) override;
void emitCallback() override;
private:
ci::signals::Signal<void ( const ci::fs::path& )> mSignalChanged;
ci::fs::path mFilePath;
ci::fs::file_time_type mTimeLastWrite;
};
//! Handles multiple live assets. Takes a vector of fs::paths as argument, result function gets an array of resolved filepaths.
class WatchMany : public Watch {
public:
WatchMany( const std::vector<ci::fs::path> &filePaths );
signals::Connection connect( const function<void ( const vector<fs::path>& )> &callback ) { return mSignalChanged.connect( callback ); }
void checkCurrent() override;
void unwatch( const fs::path &filePath ) override;
void emitCallback() override;
size_t getNumFiles() const { return mFilePaths.size(); }
private:
ci::signals::Signal<void ( const std::vector<ci::fs::path>& )> mSignalChanged;
std::vector<ci::fs::path> mFilePaths;
std::vector<ci::fs::file_time_type> mTimeStamps;
};
namespace {
fs::path findFullFilePath( const fs::path &filePath )
{
if( filePath.empty() )
throw FileWatcherException( "empty path" );
if( filePath.is_absolute() && fs::exists( filePath ) )
return filePath;
auto resolvedAssetPath = app::getAssetPath( filePath );
if( ! fs::exists( resolvedAssetPath ) )
throw FileWatcherException( "could not resolve file path: " + filePath.string() );
return resolvedAssetPath;
}
} // anonymous namespace
// ----------------------------------------------------------------------------------------------------
// WatchSingle
// ----------------------------------------------------------------------------------------------------
WatchSingle::WatchSingle( const fs::path &filePath )
{
mFilePath = findFullFilePath( filePath );
mTimeLastWrite = fs::last_write_time( mFilePath );
}
void WatchSingle::checkCurrent()
{
if( ! fs::exists( mFilePath ) )
return;
// Discard when there are no more connected slots
if( mSignalChanged.getNumSlots() == 0 ) {
markDiscarded();
return;
}
auto timeLastWrite = fs::last_write_time( mFilePath );
if( mTimeLastWrite < timeLastWrite ) {
mTimeLastWrite = timeLastWrite;
setNeedsCallback( true );
}
}
void WatchSingle::unwatch( const fs::path &filePath )
{
if( mFilePath == filePath )
markDiscarded();
}
void WatchSingle::emitCallback()
{
mSignalChanged.emit( mFilePath );
setNeedsCallback( false );
}
// ----------------------------------------------------------------------------------------------------
// WatchMany
// ----------------------------------------------------------------------------------------------------
WatchMany::WatchMany( const vector<fs::path> &filePaths )
{
mFilePaths.reserve( filePaths.size() );
mTimeStamps.reserve( filePaths.size() );
for( const auto &fp : filePaths ) {
auto fullPath = findFullFilePath( fp );
mFilePaths.push_back( fullPath );
mTimeStamps.push_back( fs::last_write_time( fullPath ) );
}
}
void WatchMany::checkCurrent()
{
// Discard when there are no more connected slots
if( mSignalChanged.getNumSlots() == 0 ) {
markDiscarded();
return;
}
const size_t numFiles = mFilePaths.size();
for( size_t i = 0; i < numFiles; i++ ) {
const fs::path &fp = mFilePaths[i];
if( fs::exists( fp ) ) {
auto timeLastWrite = fs::last_write_time( fp );
auto ¤tTimeLastWrite = mTimeStamps[i];
if( currentTimeLastWrite < timeLastWrite ) {
currentTimeLastWrite = timeLastWrite;
setNeedsCallback( true );
}
}
}
}
void WatchMany::unwatch( const fs::path &filePath )
{
mFilePaths.erase( remove( mFilePaths.begin(), mFilePaths.end(), filePath ), mFilePaths.end() );
if( mFilePaths.empty() )
markDiscarded();
}
void WatchMany::emitCallback()
{
mSignalChanged.emit( mFilePaths );
setNeedsCallback( false );
}
// ----------------------------------------------------------------------------------------------------
// FileWatcher
// ----------------------------------------------------------------------------------------------------
namespace {
bool sWatchingEnabled = true;
} // anonymous namespace
// static
FileWatcher* FileWatcher::instance()
{
static FileWatcher sInstance;
return &sInstance;
}
FileWatcher::FileWatcher()
{
if( sWatchingEnabled )
startWatching();
}
FileWatcher::~FileWatcher()
{
stopWatching();
}
// static
void FileWatcher::setWatchingEnabled( bool enable )
{
if( sWatchingEnabled == enable )
return;
sWatchingEnabled = enable;
if( enable )
instance()->startWatching();
else
instance()->stopWatching();
}
// static
bool FileWatcher::isWatchingEnabled()
{
return sWatchingEnabled;
}
// static
signals::Connection FileWatcher::load( const fs::path &filePath, const function<void( const fs::path& )> &callback )
{
auto watch = new WatchSingle( filePath );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
watch->emitCallback();
return conn;
}
// static
signals::Connection FileWatcher::load( const vector<fs::path> &filePaths, const function<void ( const vector<fs::path>& )> &callback )
{
auto watch = new WatchMany( filePaths );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
watch->emitCallback();
return conn;
}
// static
signals::Connection FileWatcher::watch( const fs::path &filePath, const function<void( const fs::path& )> &callback )
{
auto watch = new WatchSingle( filePath );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
return watch->connect( callback );
}
// static
signals::Connection FileWatcher::watch( const vector<fs::path> &filePaths, const function<void ( const vector<fs::path>& )> &callback )
{
auto watch = new WatchMany( filePaths );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
return watch->connect( callback );
}
// static
void FileWatcher::unwatch( const fs::path &filePath )
{
auto fullPath = findFullFilePath( filePath );
for( auto &watch : instance()->mWatchList ) {
watch->unwatch( fullPath );
}
}
// static
void FileWatcher::unwatch( const vector<fs::path> &filePaths )
{
for( const auto &filePath : filePaths ) {
unwatch( filePath );
}
}
void FileWatcher::startWatching()
{
if( app::App::get() && ! mUpdateConn.isConnected() )
mUpdateConn = app::App::get()->getSignalUpdate().connect( bind( &FileWatcher::update, this ) );
mThreadShouldQuit = false;
mThread = make_unique<thread>( std::bind( &FileWatcher::threadEntry, this ) );
}
void FileWatcher::stopWatching()
{
mUpdateConn.disconnect();
mThreadShouldQuit = true;
if( mThread && mThread->joinable() ) {
mThread->join();
mThread = nullptr;
}
}
void FileWatcher::threadEntry()
{
while( ! mThreadShouldQuit ) {
LOG_UPDATE( "elapsed seconds: " << app::getElapsedSeconds() );
{
// try-lock, if we fail to acquire the mutex then we skip this update
unique_lock<recursive_mutex> lock( mMutex, std::try_to_lock );
if( ! lock.owns_lock() )
continue;
LOG_UPDATE( "\t - updating watches, elapsed seconds: " << app::getElapsedSeconds() );
try {
for( auto it = mWatchList.begin(); it != mWatchList.end(); /* */ ) {
const auto &watch = *it;
if( watch->isDiscarded() ) {
it = mWatchList.erase( it );
continue;
}
watch->checkCurrent();
++it;
}
}
catch( fs::filesystem_error & ) {
// some file probably got locked by the system. Do nothing this update frame, we'll check again next
}
}
this_thread::sleep_for( chrono::duration<double>( mThreadUpdateInterval ) );
}
}
void FileWatcher::update()
{
LOG_UPDATE( "elapsed seconds: " << app::getElapsedSeconds() );
// try-lock, if we fail to acquire the mutex then we skip this update
unique_lock<recursive_mutex> lock( mMutex, std::try_to_lock );
if( ! lock.owns_lock() )
return;
LOG_UPDATE( "\t - checking watches, elapsed seconds: " << app::getElapsedSeconds() );
CI_PROFILE_CPU( "FileWatcher update" );
for( const auto &watch : mWatchList ) {
if( watch->needsCallback() )
watch->emitCallback();
}
}
const size_t FileWatcher::getNumWatchedFiles() const
{
size_t result = 0;
for( const auto &w : mWatchList ) {
auto many = dynamic_cast<WatchMany *>( w.get() );
if( many )
result += many->getNumFiles();
else
result += 1;
}
return result;
}
} // namespace mason
<commit_msg>Optimize main update loop by moving watches that need a callback to the front of the list.<commit_after>/*
Copyright (c) 2014-15, Richard Eakin - All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "mason/FileWatcher.h"
#include "mason/Profiling.h"
#include "cinder/app/App.h"
#include "cinder/Log.h"
//#define LOG_UPDATE( stream ) CI_LOG_I( stream )
#define LOG_UPDATE( stream ) ( (void)( 0 ) )
using namespace ci;
using namespace std;
namespace mason {
//! Base class for Watch types, which are returned from FileWatcher::load() and watch()
class Watch : public std::enable_shared_from_this<Watch>, private ci::Noncopyable {
public:
virtual ~Watch() = default;
//! Checks if the asset file is up-to-date. Also may discard the Watch if there are no more connected slots.
virtual void checkCurrent() = 0;
//! Remove any watches for \a filePath. If it is the last file associated with this Watch, discard
virtual void unwatch( const fs::path &filePath ) = 0;
//! Emit the signal callback.
virtual void emitCallback() = 0;
//! Marks the Watch as needing its callback to be emitted on the main thread.
void setNeedsCallback( bool b ) { mNeedsCallback = b; }
//! Returns whether the Watch needs its callback emitted on the main thread.
bool needsCallback() const { return mNeedsCallback; }
//! Marks the Watch as discarded, will be destroyed the next update loop
void markDiscarded() { mDiscarded = true; }
//! Returns whether the Watch is discarded and should be destroyed.
bool isDiscarded() const { return mDiscarded; }
private:
bool mDiscarded = false;
bool mNeedsCallback = false;
};
//! Handles a single live asset
class WatchSingle : public Watch {
public:
WatchSingle( const ci::fs::path &filePath );
signals::Connection connect( const function<void ( const ci::fs::path& )> &callback ) { return mSignalChanged.connect( callback ); }
void checkCurrent() override;
void unwatch( const fs::path &filePath ) override;
void emitCallback() override;
const fs::path& getFilePath() const { return mFilePath; }
private:
ci::signals::Signal<void ( const ci::fs::path& )> mSignalChanged;
ci::fs::path mFilePath;
ci::fs::file_time_type mTimeLastWrite;
};
//! Handles multiple live assets. Takes a vector of fs::paths as argument, result function gets an array of resolved filepaths.
class WatchMany : public Watch {
public:
WatchMany( const std::vector<ci::fs::path> &filePaths );
signals::Connection connect( const function<void ( const vector<fs::path>& )> &callback ) { return mSignalChanged.connect( callback ); }
void checkCurrent() override;
void unwatch( const fs::path &filePath ) override;
void emitCallback() override;
size_t getNumFiles() const { return mFilePaths.size(); }
private:
ci::signals::Signal<void ( const std::vector<ci::fs::path>& )> mSignalChanged;
std::vector<ci::fs::path> mFilePaths;
std::vector<ci::fs::file_time_type> mTimeStamps;
};
namespace {
fs::path findFullFilePath( const fs::path &filePath )
{
if( filePath.empty() )
throw FileWatcherException( "empty path" );
if( filePath.is_absolute() && fs::exists( filePath ) )
return filePath;
auto resolvedAssetPath = app::getAssetPath( filePath );
if( ! fs::exists( resolvedAssetPath ) )
throw FileWatcherException( "could not resolve file path: " + filePath.string() );
return resolvedAssetPath;
}
} // anonymous namespace
// ----------------------------------------------------------------------------------------------------
// WatchSingle
// ----------------------------------------------------------------------------------------------------
WatchSingle::WatchSingle( const fs::path &filePath )
{
mFilePath = findFullFilePath( filePath );
mTimeLastWrite = fs::last_write_time( mFilePath );
}
void WatchSingle::checkCurrent()
{
if( ! fs::exists( mFilePath ) )
return;
// Discard when there are no more connected slots
if( mSignalChanged.getNumSlots() == 0 ) {
markDiscarded();
return;
}
auto timeLastWrite = fs::last_write_time( mFilePath );
if( mTimeLastWrite < timeLastWrite ) {
mTimeLastWrite = timeLastWrite;
setNeedsCallback( true );
}
}
void WatchSingle::unwatch( const fs::path &filePath )
{
if( mFilePath == filePath )
markDiscarded();
}
void WatchSingle::emitCallback()
{
mSignalChanged.emit( mFilePath );
setNeedsCallback( false );
}
// ----------------------------------------------------------------------------------------------------
// WatchMany
// ----------------------------------------------------------------------------------------------------
WatchMany::WatchMany( const vector<fs::path> &filePaths )
{
mFilePaths.reserve( filePaths.size() );
mTimeStamps.reserve( filePaths.size() );
for( const auto &fp : filePaths ) {
auto fullPath = findFullFilePath( fp );
mFilePaths.push_back( fullPath );
mTimeStamps.push_back( fs::last_write_time( fullPath ) );
}
}
void WatchMany::checkCurrent()
{
// Discard when there are no more connected slots
if( mSignalChanged.getNumSlots() == 0 ) {
markDiscarded();
return;
}
const size_t numFiles = mFilePaths.size();
for( size_t i = 0; i < numFiles; i++ ) {
const fs::path &fp = mFilePaths[i];
if( fs::exists( fp ) ) {
auto timeLastWrite = fs::last_write_time( fp );
auto ¤tTimeLastWrite = mTimeStamps[i];
if( currentTimeLastWrite < timeLastWrite ) {
currentTimeLastWrite = timeLastWrite;
setNeedsCallback( true );
}
}
}
}
void WatchMany::unwatch( const fs::path &filePath )
{
mFilePaths.erase( remove( mFilePaths.begin(), mFilePaths.end(), filePath ), mFilePaths.end() );
if( mFilePaths.empty() )
markDiscarded();
}
void WatchMany::emitCallback()
{
mSignalChanged.emit( mFilePaths );
setNeedsCallback( false );
}
// ----------------------------------------------------------------------------------------------------
// FileWatcher
// ----------------------------------------------------------------------------------------------------
namespace {
bool sWatchingEnabled = true;
// Used from the debugger.
void debugPrintWatches( const std::list<std::unique_ptr<Watch>>&watchList )
{
int i = 0;
string str;
for( const auto &watch : watchList ) {
string needsCallback = watch->needsCallback() ? "true" : "false";
string discarded = watch->isDiscarded() ? "true" : "false";
auto watchSingle = dynamic_cast<const WatchSingle *>( watch.get() );
string filePath = watchSingle ? watchSingle->getFilePath().string() : "(many)";
str += "[" + to_string( i ) + "] needs callback: " + needsCallback + ", discarded: " + discarded + ", file: " + filePath + "\n";
i++;
}
app::console() << str << std::endl;
}
} // anonymous namespace
// static
FileWatcher* FileWatcher::instance()
{
static FileWatcher sInstance;
return &sInstance;
}
FileWatcher::FileWatcher()
{
if( sWatchingEnabled )
startWatching();
}
FileWatcher::~FileWatcher()
{
stopWatching();
}
// static
void FileWatcher::setWatchingEnabled( bool enable )
{
if( sWatchingEnabled == enable )
return;
sWatchingEnabled = enable;
if( enable )
instance()->startWatching();
else
instance()->stopWatching();
}
// static
bool FileWatcher::isWatchingEnabled()
{
return sWatchingEnabled;
}
// static
signals::Connection FileWatcher::load( const fs::path &filePath, const function<void( const fs::path& )> &callback )
{
auto watch = new WatchSingle( filePath );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
watch->emitCallback();
return conn;
}
// static
signals::Connection FileWatcher::load( const vector<fs::path> &filePaths, const function<void ( const vector<fs::path>& )> &callback )
{
auto watch = new WatchMany( filePaths );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
watch->emitCallback();
return conn;
}
// static
signals::Connection FileWatcher::watch( const fs::path &filePath, const function<void( const fs::path& )> &callback )
{
auto watch = new WatchSingle( filePath );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
return watch->connect( callback );
}
// static
signals::Connection FileWatcher::watch( const vector<fs::path> &filePaths, const function<void ( const vector<fs::path>& )> &callback )
{
auto watch = new WatchMany( filePaths );
auto conn = watch->connect( callback );
auto fw = instance();
lock_guard<recursive_mutex> lock( fw->mMutex );
fw->mWatchList.emplace_back( watch );
return watch->connect( callback );
}
// static
void FileWatcher::unwatch( const fs::path &filePath )
{
auto fullPath = findFullFilePath( filePath );
for( auto &watch : instance()->mWatchList ) {
watch->unwatch( fullPath );
}
}
// static
void FileWatcher::unwatch( const vector<fs::path> &filePaths )
{
for( const auto &filePath : filePaths ) {
unwatch( filePath );
}
}
void FileWatcher::startWatching()
{
if( app::App::get() && ! mUpdateConn.isConnected() )
mUpdateConn = app::App::get()->getSignalUpdate().connect( bind( &FileWatcher::update, this ) );
mThreadShouldQuit = false;
mThread = make_unique<thread>( std::bind( &FileWatcher::threadEntry, this ) );
}
void FileWatcher::stopWatching()
{
mUpdateConn.disconnect();
mThreadShouldQuit = true;
if( mThread && mThread->joinable() ) {
mThread->join();
mThread = nullptr;
}
}
void FileWatcher::threadEntry()
{
while( ! mThreadShouldQuit ) {
LOG_UPDATE( "elapsed seconds: " << app::getElapsedSeconds() );
{
// try-lock, if we fail to acquire the mutex then we skip this update
// TODO: this doesn't help here, we might as well wait until we can aquire the lock
unique_lock<recursive_mutex> lock( mMutex, std::try_to_lock );
if( ! lock.owns_lock() )
continue;
LOG_UPDATE( "\t - updating watches, elapsed seconds: " << app::getElapsedSeconds() );
try {
for( auto it = mWatchList.begin(); it != mWatchList.end(); /* */ ) {
const auto &watch = *it;
// erase discarded
if( watch->isDiscarded() ) {
it = mWatchList.erase( it );
continue;
}
// check if Watch's target has been modified and needs a callback, if not already marked.
if( ! watch->needsCallback() ) {
watch->checkCurrent();
// If the Watch needs a callback, move it to the front of the list
if( watch->needsCallback() && it != mWatchList.begin() ) {
mWatchList.splice( mWatchList.begin(), mWatchList, it );
}
}
++it;
}
}
catch( fs::filesystem_error & ) {
// some file probably got locked by the system. Do nothing this update frame, we'll check again next
}
}
this_thread::sleep_for( chrono::duration<double>( mThreadUpdateInterval ) );
}
}
void FileWatcher::update()
{
LOG_UPDATE( "elapsed seconds: " << app::getElapsedSeconds() );
// try-lock, if we fail to acquire the mutex then we skip this update
unique_lock<recursive_mutex> lock( mMutex, std::try_to_lock );
if( ! lock.owns_lock() )
return;
LOG_UPDATE( "\t - checking watches, elapsed seconds: " << app::getElapsedSeconds() );
CI_PROFILE_CPU( "FileWatcher update" );
// Watches are sorted so that all that need a callback are in the beginning.
// So break when we hit the first one that doesn't need a callback
for( const auto &watch : mWatchList ) {
if( ! watch->needsCallback() )
break;
watch->emitCallback();
}
}
const size_t FileWatcher::getNumWatchedFiles() const
{
size_t result = 0;
for( const auto &w : mWatchList ) {
auto many = dynamic_cast<WatchMany *>( w.get() );
if( many )
result += many->getNumFiles();
else
result += 1;
}
return result;
}
} // namespace mason
<|endoftext|> |
<commit_before>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2013 AudioScience Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* avdecc_cmd_line_main.cpp
*
* AVDECC command line main implementation used for testing command line interface.
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdint>
#include <cinttypes>
#include <stdexcept>
#include "cmd_line.h"
#if defined(__MACH__)
#include <readline/readline.h>
#include <readline/history.h>
#elif defined(__linux__)
#include <readline/readline.h>
#include <readline/history.h>
#endif
#if defined(__MACH__) || defined(__linux__)
#include <unistd.h>
#include <stdio.h>
#include <string.h>
// For TAB-completion
#include "cli_argument.h"
#include <set>
#else
#include "msvc\getopt.h"
#endif
using namespace std;
extern "C" void notification_callback(void * user_obj, int32_t notification_type, uint64_t entity_id, uint16_t cmd_type,
uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status,
void * notification_id)
{
if (notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * desc_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
desc_name = avdecc_lib::utility::aem_desc_value_to_name(desc_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
desc_name = "NULL";
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %s, %s, %d, %s, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_name,
desc_name,
desc_index,
cmd_status_name,
notification_id);
}
else
{
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %d, %d, %d, %d, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_type,
desc_type,
desc_index,
cmd_status,
notification_id);
}
fflush(stdout);
}
extern "C" void acmp_notification_callback(void * user_obj, int32_t notification_type, uint16_t cmd_type,
uint64_t talker_entity_id, uint16_t talker_unique_id,
uint64_t listener_entity_id, uint16_t listener_unique_id,
uint32_t cmd_status, void * notification_id)
{
if (notification_type == avdecc_lib::ACMP_RESPONSE_RECEIVED || notification_type == avdecc_lib::BROADCAST_ACMP_RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, %s, 0x%llx, %d, 0x%llx, %d, %s, %p)\n",
avdecc_lib::utility::acmp_notification_value_to_name(notification_type),
cmd_name,
talker_entity_id,
talker_unique_id,
listener_entity_id,
listener_unique_id,
cmd_status_name,
notification_id);
}
fflush(stdout);
}
extern "C" void log_callback(void * user_obj, int32_t log_level, const char * log_msg, int32_t time_stamp_ms)
{
printf("\n[LOG] %s (%s)\n", avdecc_lib::utility::logging_level_value_to_name(log_level), log_msg);
fflush(stdout);
}
#if defined(__MACH__) || defined(__linux__)
const cli_command * top_level_command;
const cli_command * current_command;
int complettion_arg_index = 0;
void split(const std::string & s, char delim, std::queue<std::string> & elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
elems.push(item);
}
char * command_generator(const char * text, int state)
{
static std::list<std::string> completion_options;
static int len;
if (!current_command)
return NULL;
if (!state)
{
// New word to complete then set up the options to match
// Cache the len for efficiency
len = strlen(text);
// Try the sub-commands of the current command
completion_options = current_command->get_sub_command_names();
if (!completion_options.size())
{
// If there are no sub-commands then try the arguments
std::vector<cli_argument *> args;
std::set<std::string> arg_options;
// There can be multiple arguments at a given index as there
// can be multiple command formats
current_command->get_args(complettion_arg_index, args);
for (std::vector<cli_argument *>::iterator iter = args.begin();
iter != args.end();
++iter)
{
(*iter)->get_completion_options(arg_options);
}
completion_options.insert(completion_options.end(),
arg_options.begin(), arg_options.end());
}
}
// Return the next name which matches from the command list
while (completion_options.size())
{
std::string sub_command = completion_options.front();
completion_options.pop_front();
if (strncmp(sub_command.c_str(), text, len) == 0)
return (strdup(sub_command.c_str()));
}
// There are no matches
return NULL;
}
char ** command_completer(const char * text, int start, int end)
{
if (start == 0)
{
// Start of a new command
current_command = top_level_command;
}
else
{
// In the middle of a command line, use the rest of the line
// to find the right command to provide completion options
std::string cmd_path(rl_line_buffer);
cmd_path = cmd_path.substr(0, start);
std::queue<std::string, std::deque<std::string>> cmd_path_queue;
split(cmd_path, ' ', cmd_path_queue);
std::string prefix;
current_command = top_level_command->get_sub_command(cmd_path_queue, prefix);
// There can be remaining parts of the command which mean that an argument
// value is being completed instead
complettion_arg_index = cmd_path_queue.size();
}
char ** matches = rl_completion_matches(text, command_generator);
return matches;
}
char * null_completer(const char * text, int state)
{
return NULL;
}
#endif
// static function to print the network interfaces
static void print_interfaces()
{
avdecc_lib::net_interface * netif = avdecc_lib::create_net_interface();
for (uint32_t i = 1; i < netif->devs_count() + 1; i++)
{
size_t dev_index = i - 1;
char * dev_desc = netif->get_dev_desc_by_index(dev_index);
printf("%d (%s)", i, dev_desc);
uint64_t dev_mac = netif->get_dev_mac_addr_by_index(dev_index);
if (dev_mac)
{
avdecc_lib::utility::MacAddr mac(dev_mac);
char mac_str[20];
mac.tostring(mac_str);
printf(" (%s)", mac_str);
}
size_t ip_addr_count = netif->device_ip_address_count(dev_index);
if (ip_addr_count > 0)
{
for(size_t ip_index = 0; ip_index < ip_addr_count; ip_index++)
{
const char * dev_ip = netif->get_dev_ip_address_by_index(dev_index, ip_index);
if (dev_ip)
printf(" <%s>", dev_ip);
}
}
printf("\n");
}
}
static void usage(char * argv[])
{
std::cerr << "Usage: " << argv[0] << " [-d] [-i interface]" << std::endl;
std::cerr << " -t : Sets test mode which disables checks" << std::endl;
std::cerr << " -i interface : Sets the network interface to use.\n \
Valid options are IP Address and MAC Address (must be in the form 'n:n:n:n:n:n', where 0<=n<=FF in hexidecimal" << std::endl;
std::cerr << " -l log_level : Sets the log level to use." << std::endl;
std::cerr << log_level_help << std::endl;
exit(1);
}
int main(int argc, char * argv[])
{
bool test_mode = false;
int error = 0;
char * interface = NULL;
int c = 0;
int32_t log_level = avdecc_lib::LOGGING_LEVEL_ERROR;
while ((c = getopt(argc, argv, "pti:l:")) != -1)
{
switch (c)
{
case 'p':
// print the network interfaces and exit
print_interfaces();
exit(EXIT_SUCCESS);
case 't':
test_mode = true;
break;
case 'i':
interface = optarg;
break;
case 'l':
log_level = atoi(optarg);
break;
case ':':
fprintf(stderr, "Option -%c requires an operand\n", optopt);
error++;
break;
case '?':
fprintf(stderr, "Unrecognized option: '-%c'\n", optopt);
error++;
break;
}
}
for (; optind < argc; optind++)
{
error++; // Unused arguments
}
if (error)
{
usage(argv);
}
if (test_mode)
{
// Ensure that stdout is not buffered
setvbuf(stdout, NULL, _IOLBF, 0);
}
cmd_line avdecc_cmd_line_ref(notification_callback, acmp_notification_callback, log_callback,
test_mode, interface, log_level);
std::vector<std::string> input_argv;
size_t pos = 0;
bool done = false;
//bool is_input_valid = false;
std::string cmd_input_orig;
#if defined(__MACH__) || defined(__linux__)
char * input;
// Set up the state for command-line completion
top_level_command = avdecc_cmd_line_ref.get_commands();
rl_attempted_completion_function = command_completer;
#endif
// Override to prevent filename completion
#if defined(__MACH__)
#if defined (READLINE_LIBRARY)
// GNU Readline library
rl_completion_entry_function = (rl_compentry_func_t *)null_completer;
#else
// OSX default libedit library
rl_completion_entry_function = (Function *)null_completer;
#endif
#elif defined(__linux__)
rl_completion_entry_function = null_completer;
#endif
std::cout << "\nEnter \"help\" for a list of valid commands." << std::endl;
while (!done)
{
#if defined(__MACH__) || defined(__linux__)
input = readline("$ ");
if (!input)
break;
if (strlen(input) == 0)
continue;
std::string cmd_input(input);
cmd_input_orig = cmd_input;
add_history(input);
#else
std::string cmd_input;
printf("\n>");
std::getline(std::cin, cmd_input);
cmd_input_orig = cmd_input;
#endif
while ((pos = cmd_input.find(" ")) != std::string::npos)
{
if (pos)
input_argv.push_back(cmd_input.substr(0, pos));
cmd_input.erase(0, pos + 1);
}
if (cmd_input.length() && cmd_input != " ")
{
input_argv.push_back(cmd_input);
}
if (avdecc_cmd_line_ref.is_output_redirected())
{
std::cout << "\n> " << cmd_input_orig << std::endl;
}
done = avdecc_cmd_line_ref.handle(input_argv);
//is_input_valid = false;
input_argv.clear();
#if defined(__MACH__) || defined(__linux__)
free(input);
#endif
}
return 0;
}
<commit_msg>cmdline - msvc - optional cmdline argument to print a new line with an underscore between commands (useful for a script that is using readline() )<commit_after>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2013 AudioScience Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* avdecc_cmd_line_main.cpp
*
* AVDECC command line main implementation used for testing command line interface.
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdint>
#include <cinttypes>
#include <stdexcept>
#include "cmd_line.h"
#if defined(__MACH__)
#include <readline/readline.h>
#include <readline/history.h>
#elif defined(__linux__)
#include <readline/readline.h>
#include <readline/history.h>
#endif
#if defined(__MACH__) || defined(__linux__)
#include <unistd.h>
#include <stdio.h>
#include <string.h>
// For TAB-completion
#include "cli_argument.h"
#include <set>
#else
#include "msvc\getopt.h"
#endif
using namespace std;
extern "C" void notification_callback(void * user_obj, int32_t notification_type, uint64_t entity_id, uint16_t cmd_type,
uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status,
void * notification_id)
{
if (notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * desc_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
desc_name = avdecc_lib::utility::aem_desc_value_to_name(desc_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
desc_name = "NULL";
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %s, %s, %d, %s, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_name,
desc_name,
desc_index,
cmd_status_name,
notification_id);
}
else
{
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %d, %d, %d, %d, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_type,
desc_type,
desc_index,
cmd_status,
notification_id);
}
fflush(stdout);
}
extern "C" void acmp_notification_callback(void * user_obj, int32_t notification_type, uint16_t cmd_type,
uint64_t talker_entity_id, uint16_t talker_unique_id,
uint64_t listener_entity_id, uint16_t listener_unique_id,
uint32_t cmd_status, void * notification_id)
{
if (notification_type == avdecc_lib::ACMP_RESPONSE_RECEIVED || notification_type == avdecc_lib::BROADCAST_ACMP_RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, %s, 0x%llx, %d, 0x%llx, %d, %s, %p)\n",
avdecc_lib::utility::acmp_notification_value_to_name(notification_type),
cmd_name,
talker_entity_id,
talker_unique_id,
listener_entity_id,
listener_unique_id,
cmd_status_name,
notification_id);
}
fflush(stdout);
}
extern "C" void log_callback(void * user_obj, int32_t log_level, const char * log_msg, int32_t time_stamp_ms)
{
printf("\n[LOG] %s (%s)\n", avdecc_lib::utility::logging_level_value_to_name(log_level), log_msg);
fflush(stdout);
}
#if defined(__MACH__) || defined(__linux__)
const cli_command * top_level_command;
const cli_command * current_command;
int complettion_arg_index = 0;
void split(const std::string & s, char delim, std::queue<std::string> & elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
elems.push(item);
}
char * command_generator(const char * text, int state)
{
static std::list<std::string> completion_options;
static int len;
if (!current_command)
return NULL;
if (!state)
{
// New word to complete then set up the options to match
// Cache the len for efficiency
len = strlen(text);
// Try the sub-commands of the current command
completion_options = current_command->get_sub_command_names();
if (!completion_options.size())
{
// If there are no sub-commands then try the arguments
std::vector<cli_argument *> args;
std::set<std::string> arg_options;
// There can be multiple arguments at a given index as there
// can be multiple command formats
current_command->get_args(complettion_arg_index, args);
for (std::vector<cli_argument *>::iterator iter = args.begin();
iter != args.end();
++iter)
{
(*iter)->get_completion_options(arg_options);
}
completion_options.insert(completion_options.end(),
arg_options.begin(), arg_options.end());
}
}
// Return the next name which matches from the command list
while (completion_options.size())
{
std::string sub_command = completion_options.front();
completion_options.pop_front();
if (strncmp(sub_command.c_str(), text, len) == 0)
return (strdup(sub_command.c_str()));
}
// There are no matches
return NULL;
}
char ** command_completer(const char * text, int start, int end)
{
if (start == 0)
{
// Start of a new command
current_command = top_level_command;
}
else
{
// In the middle of a command line, use the rest of the line
// to find the right command to provide completion options
std::string cmd_path(rl_line_buffer);
cmd_path = cmd_path.substr(0, start);
std::queue<std::string, std::deque<std::string>> cmd_path_queue;
split(cmd_path, ' ', cmd_path_queue);
std::string prefix;
current_command = top_level_command->get_sub_command(cmd_path_queue, prefix);
// There can be remaining parts of the command which mean that an argument
// value is being completed instead
complettion_arg_index = cmd_path_queue.size();
}
char ** matches = rl_completion_matches(text, command_generator);
return matches;
}
char * null_completer(const char * text, int state)
{
return NULL;
}
#endif
// static function to print the network interfaces
static void print_interfaces()
{
avdecc_lib::net_interface * netif = avdecc_lib::create_net_interface();
for (uint32_t i = 1; i < netif->devs_count() + 1; i++)
{
size_t dev_index = i - 1;
char * dev_desc = netif->get_dev_desc_by_index(dev_index);
printf("%d (%s)", i, dev_desc);
uint64_t dev_mac = netif->get_dev_mac_addr_by_index(dev_index);
if (dev_mac)
{
avdecc_lib::utility::MacAddr mac(dev_mac);
char mac_str[20];
mac.tostring(mac_str);
printf(" (%s)", mac_str);
}
size_t ip_addr_count = netif->device_ip_address_count(dev_index);
if (ip_addr_count > 0)
{
for(size_t ip_index = 0; ip_index < ip_addr_count; ip_index++)
{
const char * dev_ip = netif->get_dev_ip_address_by_index(dev_index, ip_index);
if (dev_ip)
printf(" <%s>", dev_ip);
}
}
printf("\n");
}
}
static void usage(char * argv[])
{
std::cerr << "Usage: " << argv[0] << " [-d] [-i interface]" << std::endl;
std::cerr << " -t : Sets test mode which disables checks" << std::endl;
std::cerr << " -i interface : Sets the network interface to use.\n \
Valid options are IP Address and MAC Address (must be in the form 'n:n:n:n:n:n', where 0<=n<=FF in hexidecimal" << std::endl;
std::cerr << " -l log_level : Sets the log level to use." << std::endl;
std::cerr << log_level_help << std::endl;
exit(1);
}
int main(int argc, char * argv[])
{
bool show_cmd_separator = false;
bool test_mode = false;
int error = 0;
char * interface = NULL;
int c = 0;
int32_t log_level = avdecc_lib::LOGGING_LEVEL_ERROR;
while ((c = getopt(argc, argv, "spti:l:")) != -1)
{
switch (c)
{
case 'p':
// print the network interfaces and exit
print_interfaces();
exit(EXIT_SUCCESS);
case 's':
show_cmd_separator = true;
break;
case 't':
test_mode = true;
break;
case 'i':
interface = optarg;
break;
case 'l':
log_level = atoi(optarg);
break;
case ':':
fprintf(stderr, "Option -%c requires an operand\n", optopt);
error++;
break;
case '?':
fprintf(stderr, "Unrecognized option: '-%c'\n", optopt);
error++;
break;
}
}
for (; optind < argc; optind++)
{
error++; // Unused arguments
}
if (error)
{
usage(argv);
}
if (test_mode)
{
// Ensure that stdout is not buffered
setvbuf(stdout, NULL, _IOLBF, 0);
}
cmd_line avdecc_cmd_line_ref(notification_callback, acmp_notification_callback, log_callback,
test_mode, interface, log_level);
std::vector<std::string> input_argv;
size_t pos = 0;
bool done = false;
//bool is_input_valid = false;
std::string cmd_input_orig;
#if defined(__MACH__) || defined(__linux__)
char * input;
// Set up the state for command-line completion
top_level_command = avdecc_cmd_line_ref.get_commands();
rl_attempted_completion_function = command_completer;
#endif
// Override to prevent filename completion
#if defined(__MACH__)
#if defined (READLINE_LIBRARY)
// GNU Readline library
rl_completion_entry_function = (rl_compentry_func_t *)null_completer;
#else
// OSX default libedit library
rl_completion_entry_function = (Function *)null_completer;
#endif
#elif defined(__linux__)
rl_completion_entry_function = null_completer;
#endif
std::cout << "\nEnter \"help\" for a list of valid commands." << std::endl;
while (!done)
{
#if defined(__MACH__) || defined(__linux__)
input = readline("$ ");
if (!input)
break;
if (strlen(input) == 0)
continue;
std::string cmd_input(input);
cmd_input_orig = cmd_input;
add_history(input);
#else
std::string cmd_input;
if (show_cmd_separator)
printf("\n_\n");
printf("\n>");
std::getline(std::cin, cmd_input);
cmd_input_orig = cmd_input;
#endif
while ((pos = cmd_input.find(" ")) != std::string::npos)
{
if (pos)
input_argv.push_back(cmd_input.substr(0, pos));
cmd_input.erase(0, pos + 1);
}
if (cmd_input.length() && cmd_input != " ")
{
input_argv.push_back(cmd_input);
}
if (avdecc_cmd_line_ref.is_output_redirected())
{
std::cout << "\n> " << cmd_input_orig << std::endl;
}
done = avdecc_cmd_line_ref.handle(input_argv);
//is_input_valid = false;
input_argv.clear();
#if defined(__MACH__) || defined(__linux__)
free(input);
#endif
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2013 AudioScience Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* avdecc_cmd_line_main.cpp
*
* AVDECC command line main implementation used for testing command line interface.
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdint>
#include <cinttypes>
#include <stdexcept>
#include "cmd_line.h"
#if defined(__MACH__)
#include <readline/readline.h>
#include <readline/history.h>
#elif defined(__linux__)
#include <readline/readline.h>
#include <readline/history.h>
#endif
#if defined(__MACH__) || defined(__linux__)
#include <unistd.h>
#include <stdio.h>
#include <string.h>
// For TAB-completion
#include "cli_argument.h"
#include <set>
#else
#include "msvc\getopt.h"
#endif
using namespace std;
extern "C" void notification_callback(void * user_obj, int32_t notification_type, uint64_t entity_id, uint16_t cmd_type,
uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status,
void * notification_id)
{
if (notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * desc_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
desc_name = avdecc_lib::utility::aem_desc_value_to_name(desc_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
desc_name = "NULL";
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %s, %s, %d, %s, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_name,
desc_name,
desc_index,
cmd_status_name,
notification_id);
}
else
{
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %d, %d, %d, %d, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_type,
desc_type,
desc_index,
cmd_status,
notification_id);
}
}
extern "C" void acmp_notification_callback(void * user_obj, int32_t notification_type, uint16_t cmd_type,
uint64_t talker_entity_id, uint16_t talker_unique_id,
uint64_t listener_entity_id, uint16_t listener_unique_id,
uint32_t cmd_status, void * notification_id)
{
if (notification_type == avdecc_lib::ACMP_RESPONSE_RECEIVED || notification_type == avdecc_lib::BROADCAST_ACMP_RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, %s, 0x%llx, %d, 0x%llx, %d, %s, %p)\n",
avdecc_lib::utility::acmp_notification_value_to_name(notification_type),
cmd_name,
talker_entity_id,
talker_unique_id,
listener_entity_id,
listener_unique_id,
cmd_status_name,
notification_id);
}
}
extern "C" void log_callback(void * user_obj, int32_t log_level, const char * log_msg, int32_t time_stamp_ms)
{
printf("\n[LOG] %s (%s)\n", avdecc_lib::utility::logging_level_value_to_name(log_level), log_msg);
}
#if defined(__MACH__) || defined(__linux__)
const cli_command * top_level_command;
const cli_command * current_command;
int complettion_arg_index = 0;
void split(const std::string & s, char delim, std::queue<std::string> & elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
elems.push(item);
}
char * command_generator(const char * text, int state)
{
static std::list<std::string> completion_options;
static int len;
if (!current_command)
return NULL;
if (!state)
{
// New word to complete then set up the options to match
// Cache the len for efficiency
len = strlen(text);
// Try the sub-commands of the current command
completion_options = current_command->get_sub_command_names();
if (!completion_options.size())
{
// If there are no sub-commands then try the arguments
std::vector<cli_argument *> args;
std::set<std::string> arg_options;
// There can be multiple arguments at a given index as there
// can be multiple command formats
current_command->get_args(complettion_arg_index, args);
for (std::vector<cli_argument *>::iterator iter = args.begin();
iter != args.end();
++iter)
{
(*iter)->get_completion_options(arg_options);
}
completion_options.insert(completion_options.end(),
arg_options.begin(), arg_options.end());
}
}
// Return the next name which matches from the command list
while (completion_options.size())
{
std::string sub_command = completion_options.front();
completion_options.pop_front();
if (strncmp(sub_command.c_str(), text, len) == 0)
return (strdup(sub_command.c_str()));
}
// There are no matches
return NULL;
}
char ** command_completer(const char * text, int start, int end)
{
if (start == 0)
{
// Start of a new command
current_command = top_level_command;
}
else
{
// In the middle of a command line, use the rest of the line
// to find the right command to provide completion options
std::string cmd_path(rl_line_buffer);
cmd_path = cmd_path.substr(0, start);
std::queue<std::string, std::deque<std::string>> cmd_path_queue;
split(cmd_path, ' ', cmd_path_queue);
std::string prefix;
current_command = top_level_command->get_sub_command(cmd_path_queue, prefix);
// There can be remaining parts of the command which mean that an argument
// value is being completed instead
complettion_arg_index = cmd_path_queue.size();
}
char ** matches = rl_completion_matches(text, command_generator);
return matches;
}
char * null_completer(const char * text, int state)
{
return NULL;
}
#endif
static void usage(char * argv[])
{
std::cerr << "Usage: " << argv[0] << " [-d] [-i interface]" << std::endl;
std::cerr << " -t : Sets test mode which disables checks" << std::endl;
std::cerr << " -i interface : Sets the name of the interface to use" << std::endl;
std::cerr << " -l log_level : Sets the log level to use." << std::endl;
std::cerr << log_level_help << std::endl;
exit(1);
}
int main(int argc, char * argv[])
{
bool test_mode = false;
int error = 0;
char * interface = NULL;
int c = 0;
int32_t log_level = avdecc_lib::LOGGING_LEVEL_ERROR;
while ((c = getopt(argc, argv, "ti:l:")) != -1)
{
switch (c)
{
case 't':
test_mode = true;
break;
case 'i':
interface = optarg;
break;
case 'l':
log_level = atoi(optarg);
break;
case ':':
fprintf(stderr, "Option -%c requires an operand\n", optopt);
error++;
break;
case '?':
fprintf(stderr, "Unrecognized option: '-%c'\n", optopt);
error++;
break;
}
}
for (; optind < argc; optind++)
{
error++; // Unused arguments
}
if (error)
{
usage(argv);
}
if (test_mode)
{
// Ensure that stdout is not buffered
setvbuf(stdout, NULL, _IOLBF, 0);
}
cmd_line avdecc_cmd_line_ref(notification_callback, acmp_notification_callback, log_callback,
test_mode, interface, log_level);
std::vector<std::string> input_argv;
size_t pos = 0;
bool done = false;
//bool is_input_valid = false;
std::string cmd_input_orig;
#if defined(__MACH__) || defined(__linux__)
char * input;
// Set up the state for command-line completion
top_level_command = avdecc_cmd_line_ref.get_commands();
rl_attempted_completion_function = command_completer;
#endif
// Override to prevent filename completion
#if defined(__MACH__)
rl_completion_entry_function = (Function *)null_completer;
#elif defined(__linux__)
rl_completion_entry_function = null_completer;
#endif
std::cout << "\nEnter \"help\" for a list of valid commands." << std::endl;
while (!done)
{
#if defined(__MACH__) || defined(__linux__)
input = readline("$ ");
if (!input)
break;
if (strlen(input) == 0)
continue;
std::string cmd_input(input);
cmd_input_orig = cmd_input;
add_history(input);
#else
std::string cmd_input;
printf("\n>");
std::getline(std::cin, cmd_input);
cmd_input_orig = cmd_input;
#endif
while ((pos = cmd_input.find(" ")) != std::string::npos)
{
if (pos)
input_argv.push_back(cmd_input.substr(0, pos));
cmd_input.erase(0, pos + 1);
}
if (cmd_input.length() && cmd_input != " ")
{
input_argv.push_back(cmd_input);
}
if (avdecc_cmd_line_ref.is_output_redirected())
{
std::cout << "\n> " << cmd_input_orig << std::endl;
}
done = avdecc_cmd_line_ref.handle(input_argv);
//is_input_valid = false;
input_argv.clear();
#if defined(__MACH__) || defined(__linux__)
free(input);
#endif
}
return 0;
}
<commit_msg>cmd_line_main - support both libedit and GNU Readline libraries<commit_after>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2013 AudioScience Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* avdecc_cmd_line_main.cpp
*
* AVDECC command line main implementation used for testing command line interface.
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdint>
#include <cinttypes>
#include <stdexcept>
#include "cmd_line.h"
#if defined(__MACH__)
#include <readline/readline.h>
#include <readline/history.h>
#elif defined(__linux__)
#include <readline/readline.h>
#include <readline/history.h>
#endif
#if defined(__MACH__) || defined(__linux__)
#include <unistd.h>
#include <stdio.h>
#include <string.h>
// For TAB-completion
#include "cli_argument.h"
#include <set>
#else
#include "msvc\getopt.h"
#endif
using namespace std;
extern "C" void notification_callback(void * user_obj, int32_t notification_type, uint64_t entity_id, uint16_t cmd_type,
uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status,
void * notification_id)
{
if (notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * desc_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
desc_name = avdecc_lib::utility::aem_desc_value_to_name(desc_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
desc_name = "NULL";
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %s, %s, %d, %s, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_name,
desc_name,
desc_index,
cmd_status_name,
notification_id);
}
else
{
printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %d, %d, %d, %d, %p)\n",
avdecc_lib::utility::notification_value_to_name(notification_type),
entity_id,
cmd_type,
desc_type,
desc_index,
cmd_status,
notification_id);
}
}
extern "C" void acmp_notification_callback(void * user_obj, int32_t notification_type, uint16_t cmd_type,
uint64_t talker_entity_id, uint16_t talker_unique_id,
uint64_t listener_entity_id, uint16_t listener_unique_id,
uint32_t cmd_status, void * notification_id)
{
if (notification_type == avdecc_lib::ACMP_RESPONSE_RECEIVED || notification_type == avdecc_lib::BROADCAST_ACMP_RESPONSE_RECEIVED)
{
const char * cmd_name;
const char * cmd_status_name;
if (cmd_type < avdecc_lib::CMD_LOOKUP)
{
cmd_name = avdecc_lib::utility::aem_cmd_value_to_name(cmd_type);
cmd_status_name = avdecc_lib::utility::aem_cmd_status_value_to_name(cmd_status);
}
else
{
cmd_name = avdecc_lib::utility::acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);
cmd_status_name = avdecc_lib::utility::acmp_cmd_status_value_to_name(cmd_status);
}
printf("\n[NOTIFICATION] (%s, %s, 0x%llx, %d, 0x%llx, %d, %s, %p)\n",
avdecc_lib::utility::acmp_notification_value_to_name(notification_type),
cmd_name,
talker_entity_id,
talker_unique_id,
listener_entity_id,
listener_unique_id,
cmd_status_name,
notification_id);
}
}
extern "C" void log_callback(void * user_obj, int32_t log_level, const char * log_msg, int32_t time_stamp_ms)
{
printf("\n[LOG] %s (%s)\n", avdecc_lib::utility::logging_level_value_to_name(log_level), log_msg);
}
#if defined(__MACH__) || defined(__linux__)
const cli_command * top_level_command;
const cli_command * current_command;
int complettion_arg_index = 0;
void split(const std::string & s, char delim, std::queue<std::string> & elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
elems.push(item);
}
char * command_generator(const char * text, int state)
{
static std::list<std::string> completion_options;
static int len;
if (!current_command)
return NULL;
if (!state)
{
// New word to complete then set up the options to match
// Cache the len for efficiency
len = strlen(text);
// Try the sub-commands of the current command
completion_options = current_command->get_sub_command_names();
if (!completion_options.size())
{
// If there are no sub-commands then try the arguments
std::vector<cli_argument *> args;
std::set<std::string> arg_options;
// There can be multiple arguments at a given index as there
// can be multiple command formats
current_command->get_args(complettion_arg_index, args);
for (std::vector<cli_argument *>::iterator iter = args.begin();
iter != args.end();
++iter)
{
(*iter)->get_completion_options(arg_options);
}
completion_options.insert(completion_options.end(),
arg_options.begin(), arg_options.end());
}
}
// Return the next name which matches from the command list
while (completion_options.size())
{
std::string sub_command = completion_options.front();
completion_options.pop_front();
if (strncmp(sub_command.c_str(), text, len) == 0)
return (strdup(sub_command.c_str()));
}
// There are no matches
return NULL;
}
char ** command_completer(const char * text, int start, int end)
{
if (start == 0)
{
// Start of a new command
current_command = top_level_command;
}
else
{
// In the middle of a command line, use the rest of the line
// to find the right command to provide completion options
std::string cmd_path(rl_line_buffer);
cmd_path = cmd_path.substr(0, start);
std::queue<std::string, std::deque<std::string>> cmd_path_queue;
split(cmd_path, ' ', cmd_path_queue);
std::string prefix;
current_command = top_level_command->get_sub_command(cmd_path_queue, prefix);
// There can be remaining parts of the command which mean that an argument
// value is being completed instead
complettion_arg_index = cmd_path_queue.size();
}
char ** matches = rl_completion_matches(text, command_generator);
return matches;
}
char * null_completer(const char * text, int state)
{
return NULL;
}
#endif
static void usage(char * argv[])
{
std::cerr << "Usage: " << argv[0] << " [-d] [-i interface]" << std::endl;
std::cerr << " -t : Sets test mode which disables checks" << std::endl;
std::cerr << " -i interface : Sets the name of the interface to use" << std::endl;
std::cerr << " -l log_level : Sets the log level to use." << std::endl;
std::cerr << log_level_help << std::endl;
exit(1);
}
int main(int argc, char * argv[])
{
bool test_mode = false;
int error = 0;
char * interface = NULL;
int c = 0;
int32_t log_level = avdecc_lib::LOGGING_LEVEL_ERROR;
while ((c = getopt(argc, argv, "ti:l:")) != -1)
{
switch (c)
{
case 't':
test_mode = true;
break;
case 'i':
interface = optarg;
break;
case 'l':
log_level = atoi(optarg);
break;
case ':':
fprintf(stderr, "Option -%c requires an operand\n", optopt);
error++;
break;
case '?':
fprintf(stderr, "Unrecognized option: '-%c'\n", optopt);
error++;
break;
}
}
for (; optind < argc; optind++)
{
error++; // Unused arguments
}
if (error)
{
usage(argv);
}
if (test_mode)
{
// Ensure that stdout is not buffered
setvbuf(stdout, NULL, _IOLBF, 0);
}
cmd_line avdecc_cmd_line_ref(notification_callback, acmp_notification_callback, log_callback,
test_mode, interface, log_level);
std::vector<std::string> input_argv;
size_t pos = 0;
bool done = false;
//bool is_input_valid = false;
std::string cmd_input_orig;
#if defined(__MACH__) || defined(__linux__)
char * input;
// Set up the state for command-line completion
top_level_command = avdecc_cmd_line_ref.get_commands();
rl_attempted_completion_function = command_completer;
#endif
// Override to prevent filename completion
#if defined(__MACH__)
#if defined (READLINE_LIBRARY)
// GNU Readline library
rl_completion_entry_function = (rl_compentry_func_t *)null_completer;
#else
// OSX default libedit library
rl_completion_entry_function = (Function *)null_completer;
#endif
#elif defined(__linux__)
rl_completion_entry_function = null_completer;
#endif
std::cout << "\nEnter \"help\" for a list of valid commands." << std::endl;
while (!done)
{
#if defined(__MACH__) || defined(__linux__)
input = readline("$ ");
if (!input)
break;
if (strlen(input) == 0)
continue;
std::string cmd_input(input);
cmd_input_orig = cmd_input;
add_history(input);
#else
std::string cmd_input;
printf("\n>");
std::getline(std::cin, cmd_input);
cmd_input_orig = cmd_input;
#endif
while ((pos = cmd_input.find(" ")) != std::string::npos)
{
if (pos)
input_argv.push_back(cmd_input.substr(0, pos));
cmd_input.erase(0, pos + 1);
}
if (cmd_input.length() && cmd_input != " ")
{
input_argv.push_back(cmd_input);
}
if (avdecc_cmd_line_ref.is_output_redirected())
{
std::cout << "\n> " << cmd_input_orig << std::endl;
}
done = avdecc_cmd_line_ref.handle(input_argv);
//is_input_valid = false;
input_argv.clear();
#if defined(__MACH__) || defined(__linux__)
free(input);
#endif
}
return 0;
}
<|endoftext|> |
<commit_before>#include "multihtmlreporter.h"
#include "htmlreporter.h"
#include "common.h"
#include <chrono>
#include "globalsettings.h"
#include <sys/stat.h>
MultiHtmlReporter::MultiHtmlReporter(string filename, vector<Mutation>& mutationList, vector<Match*> *mutationMatches){
mMutationList = mutationList;
mMutationMatches = mutationMatches;
mFilename = filename;
mFolderName = mFilename + ".files";
mkdir(mFolderName.c_str(), 0777);
stat();
}
MultiHtmlReporter::~MultiHtmlReporter(){
}
void MultiHtmlReporter::stat(){
mTotalCount = 0;
for(int m=0; m<mMutationList.size(); m++) {
vector<Match*> matches = mMutationMatches[m];
if(matches.size()>0) {
mTotalCount++;
string chr = mMutationList[m].mChr;
if(mChrCount.count(chr)==0)
mChrCount[chr]=1;
else
mChrCount[chr]++;
}
}
}
void MultiHtmlReporter::run() {
printMutationHtml();
printChrHtml();
printMainFrame();
printIndexPage();
printMainPage();
}
void MultiHtmlReporter::printMainFrame() {
ofstream file;
file.open(mFilename.c_str(), ifstream::out);
file << "<html><frameset cols='20%,80%' frameborder='yes' framespacing='1'><frame name='_index' src='";
file << mFolderName + "/index.html";
file << "'/><frame name='_main' src='";
file << mFolderName + "/main.html";
file << "'/></frameset></html>";
file.close();
}
void MultiHtmlReporter::printMainPage() {
ofstream file;
string mainFile = mFolderName + "/main.html";
file.open(mainFile.c_str(), ifstream::out);
printHeader(file);
printAllChromosomeLink(file);
printFooter(file);
file.close();
}
void MultiHtmlReporter::printAllChromosomeLink(ofstream& file) {
map<string, int>::iterator iter;
file << "<ul id='menu'>";
for(iter= mChrCount.begin(); iter!= mChrCount.end(); iter++){
printChrLink(file, iter->first);
}
file << "</ul>";
}
void MultiHtmlReporter::printChrLink(ofstream& file, string chr) {
for(int m=0; m<mMutationList.size(); m++) {
vector<Match*> matches = mMutationMatches[m];
if(matches.size()>0) {
if(chr == mMutationList[m].mChr) {
string filename = chr + "/" + to_string(m) + ".html";
file << "<li class='menu_item'><a href='" << filename << "'>" << mMutationList[m].mName;
file<< " (" << matches.size() << " reads support, " << Match::countUnique(matches) << " unique)"
<< " </a></li>";
}
}
}
}
void MultiHtmlReporter::printMutationHtml() {
for(int m=0; m<mMutationList.size(); m++) {
vector<Match*> matches = mMutationMatches[m];
if(matches.size()>0) {
string chr = mMutationList[m].mChr;
string folder = mFolderName + "/" + chr;
string filename = folder + "/" + to_string(m) + ".html";
vector<Mutation> mutList;
mutList.push_back(mMutationList[m]);
HtmlReporter hr(filename, mutList, mMutationMatches+m);
hr.run();
}
}
}
void MultiHtmlReporter::printIndexPage() {
ofstream file;
string indexFile = mFolderName + "/index.html";
file.open(indexFile.c_str(), ifstream::out);
printHeader(file);
file << "<ul id='menu'>";
file << "<li class='menu_item'><a href='main.html' target='_main'>All (" << mTotalCount << " mutations)</a></li>";
map<string, int>::iterator iter;
for(iter= mChrCount.begin(); iter!= mChrCount.end(); iter++){
file << "<li class='menu_item'><a href='" << iter->first << ".html' target='_main'>" << iter->first << " (" << iter->second << " mutations)</a></li>";
}
file << "</ul>";
printFooter(file);
file.close();
}
void MultiHtmlReporter::printChrHtml() {
map<string, int>::iterator iter;
for(iter= mChrCount.begin(); iter!= mChrCount.end(); iter++){
string chr = iter->first;
string folder = mFolderName + "/" + chr;
mkdir(folder.c_str(), 0777);
ofstream file;
string chrFilename = mFolderName + "/" + chr + ".html";
file.open(chrFilename.c_str(), ifstream::out);
printHeader(file);
file << "<ul id='menu'>";
printChrLink(file, chr);
file << "</ul>";
printFooter(file);
file.close();
}
}
void MultiHtmlReporter::printHelper(ofstream& file) {
file << "<div id='helper'><p>Helpful tips:</p><ul>";
file << "<li> Base color indicates quality: <font color='#78C6B9'>extremely high (Q40+)</font>, <font color='#33BBE2'>high (Q30+)</font>, <font color='#666666'>moderate (Q20+)</font>, <font color='#E99E5B'>low (Q15+)</font>, <font color='#FF0000'>extremely low (0~Q14)</font> </li>";
file << "<li> Move mouse over the base, it will show the quality value</li>";
if(GlobalSettings::outputOriginalReads)
file << "<li> Click on any row, the original read/pair will be displayed</li>";
file << "<li> In first column, <i>d</i> means the edit distance of match, and --> means forward, <-- means reverse </li>";
file << "<li> For pair-end sequencing, MutScan tries to merge each pair, and the overlapped bases will be assigned higher qualities </li>";
file << "</ul></div>";
}
void MultiHtmlReporter::printHeader(ofstream& file){
file << "<html><head><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />";
file << "<title>MutScan report</title>";
printJS(file);
printCSS(file);
file << "</head>";
file << "<body><div id='container'>";
}
void MultiHtmlReporter::printCSS(ofstream& file){
file << "<style type=\"text/css\">";
file << "td {border:1px solid #dddddd;padding-left:2px;padding-right:2px;font-size:10px;}";
file << "table {border:1px solid #999999;padding:2x;border-collapse:collapse;}";
file << "img {padding:30px;}";
file << ".alignleft {text-align:left;}";
file << ".alignright {text-align:right;}";
file << ".header {color:#ffffff;padding:1px;height:20px;background:#000000;}";
file << ".figuretitle {color:#996657;font-size:20px;padding:50px;}";
file << "#container {text-align:center;padding:1px;font-family:Arial;}";
file << "#menu {padding-top:10px;padding-bottom:10px;text-align:left;}";
file << ".menu_item {text-align:left;padding-top:5px;font-size:18px;}";
file << ".highlight {text-align:left;padding-top:30px;padding-bottom:30px;font-size:20px;line-height:35px;}";
file << ".mutation_head {text-align:left;color:#0092FF;font-family:Arial;padding-top:20px;padding-bottom:5px;}";
file << ".mutation_block {}";
file << ".match_brief {font-size:8px}";
file << ".mutation_point {color:#FFCCAA}";
file << "#helper {text-align:left;border:1px dotted #fafafa;color:#777777;}";
file << "#footer {text-align:left;padding-left:10px;padding-top:20px;color:#777777;font-size:10px;}";
file << "</style>";
}
void MultiHtmlReporter::printJS(ofstream& file){
file << "\n<script type=\"text/javascript\">" << endl;
file << "function toggle(targetid){ \n\
if (document.getElementById){ \n\
target=document.getElementById(targetid); \n\
if (target.style.display=='table-row'){ \n\
target.style.display='none'; \n\
} else { \n\
target.style.display='table-row'; \n\
} \n\
} \n\
}";
file << "function toggle_target_list(targetid){ \n\
if (document.getElementById){ \n\
target=document.getElementById(targetid); \n\
if (target.style.display=='block'){ \n\
target.style.display='none'; \n\
document.getElementById('target_view_btn').value='view';\n\
} else { \n\
document.getElementById('target_view_btn').value='hide';\n\
target.style.display='block'; \n\
} \n\
} \n\
}";
file << "</script>";
}
string MultiHtmlReporter::getCurrentSystemTime()
{
auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
struct tm* ptm = localtime(&tt);
char date[60] = {0};
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",
(int)ptm->tm_year + 1900,(int)ptm->tm_mon + 1,(int)ptm->tm_mday,
(int)ptm->tm_hour,(int)ptm->tm_min,(int)ptm->tm_sec);
return std::string(date);
}
extern string command;
void MultiHtmlReporter::printFooter(ofstream& file){
file << "\n<div id='footer'> ";
file << "<p>"<<command<<"</p>";
printScanTargets(file);
file << "MutScan " << MUTSCAN_VER << ", at " << getCurrentSystemTime() << " </div>";
file << "</div></body></html>";
}
void MultiHtmlReporter::printScanTargets(ofstream& file){
file << "\n<div id='targets'> ";
file << "<p> scanned " << mMutationList.size() << " mutation spots...<input type='button' id='target_view_btn', onclick=toggle_target_list('target_list'); value='show'></input></p>";
file << "<ul id='target_list' style='display:none'>";
int id=0;
for(int i=0;i<mMutationList.size();i++){
id++;
file<<"<li> " << id << ", " << mMutationList[i].mName << "</li>";
}
file << "</ul></div>";
}<commit_msg>mkdir chr folder first<commit_after>#include "multihtmlreporter.h"
#include "htmlreporter.h"
#include "common.h"
#include <chrono>
#include "globalsettings.h"
#include <sys/stat.h>
MultiHtmlReporter::MultiHtmlReporter(string filename, vector<Mutation>& mutationList, vector<Match*> *mutationMatches){
mMutationList = mutationList;
mMutationMatches = mutationMatches;
mFilename = filename;
mFolderName = mFilename + ".files";
mkdir(mFolderName.c_str(), 0777);
stat();
}
MultiHtmlReporter::~MultiHtmlReporter(){
}
void MultiHtmlReporter::stat(){
mTotalCount = 0;
for(int m=0; m<mMutationList.size(); m++) {
vector<Match*> matches = mMutationMatches[m];
if(matches.size()>0) {
mTotalCount++;
string chr = mMutationList[m].mChr;
if(mChrCount.count(chr)==0)
mChrCount[chr]=1;
else
mChrCount[chr]++;
}
}
}
void MultiHtmlReporter::run() {
printChrHtml();
printMutationHtml();
printMainFrame();
printIndexPage();
printMainPage();
}
void MultiHtmlReporter::printMainFrame() {
ofstream file;
file.open(mFilename.c_str(), ifstream::out);
file << "<html><frameset cols='20%,80%' frameborder='yes' framespacing='1'><frame name='_index' src='";
file << mFolderName + "/index.html";
file << "'/><frame name='_main' src='";
file << mFolderName + "/main.html";
file << "'/></frameset></html>";
file.close();
}
void MultiHtmlReporter::printMainPage() {
ofstream file;
string mainFile = mFolderName + "/main.html";
file.open(mainFile.c_str(), ifstream::out);
printHeader(file);
printAllChromosomeLink(file);
printFooter(file);
file.close();
}
void MultiHtmlReporter::printAllChromosomeLink(ofstream& file) {
map<string, int>::iterator iter;
file << "<ul id='menu'>";
for(iter= mChrCount.begin(); iter!= mChrCount.end(); iter++){
printChrLink(file, iter->first);
}
file << "</ul>";
}
void MultiHtmlReporter::printChrLink(ofstream& file, string chr) {
for(int m=0; m<mMutationList.size(); m++) {
vector<Match*> matches = mMutationMatches[m];
if(matches.size()>0) {
if(chr == mMutationList[m].mChr) {
string filename = chr + "/" + to_string(m) + ".html";
file << "<li class='menu_item'><a href='" << filename << "'>" << mMutationList[m].mName;
file<< " (" << matches.size() << " reads support, " << Match::countUnique(matches) << " unique)"
<< " </a></li>";
}
}
}
}
void MultiHtmlReporter::printMutationHtml() {
for(int m=0; m<mMutationList.size(); m++) {
vector<Match*> matches = mMutationMatches[m];
if(matches.size()>0) {
string chr = mMutationList[m].mChr;
string folder = mFolderName + "/" + chr;
string filename = folder + "/" + to_string(m) + ".html";
vector<Mutation> mutList;
mutList.push_back(mMutationList[m]);
HtmlReporter hr(filename, mutList, mMutationMatches+m);
hr.run();
}
}
}
void MultiHtmlReporter::printIndexPage() {
ofstream file;
string indexFile = mFolderName + "/index.html";
file.open(indexFile.c_str(), ifstream::out);
printHeader(file);
file << "<ul id='menu'>";
file << "<li class='menu_item'><a href='main.html' target='_main'>All (" << mTotalCount << " mutations)</a></li>";
map<string, int>::iterator iter;
for(iter= mChrCount.begin(); iter!= mChrCount.end(); iter++){
file << "<li class='menu_item'><a href='" << iter->first << ".html' target='_main'>" << iter->first << " (" << iter->second << " mutations)</a></li>";
}
file << "</ul>";
printFooter(file);
file.close();
}
void MultiHtmlReporter::printChrHtml() {
map<string, int>::iterator iter;
for(iter= mChrCount.begin(); iter!= mChrCount.end(); iter++){
string chr = iter->first;
string folder = mFolderName + "/" + chr;
mkdir(folder.c_str(), 0777);
ofstream file;
string chrFilename = mFolderName + "/" + chr + ".html";
file.open(chrFilename.c_str(), ifstream::out);
printHeader(file);
file << "<ul id='menu'>";
printChrLink(file, chr);
file << "</ul>";
printFooter(file);
file.close();
}
}
void MultiHtmlReporter::printHelper(ofstream& file) {
file << "<div id='helper'><p>Helpful tips:</p><ul>";
file << "<li> Base color indicates quality: <font color='#78C6B9'>extremely high (Q40+)</font>, <font color='#33BBE2'>high (Q30+)</font>, <font color='#666666'>moderate (Q20+)</font>, <font color='#E99E5B'>low (Q15+)</font>, <font color='#FF0000'>extremely low (0~Q14)</font> </li>";
file << "<li> Move mouse over the base, it will show the quality value</li>";
if(GlobalSettings::outputOriginalReads)
file << "<li> Click on any row, the original read/pair will be displayed</li>";
file << "<li> In first column, <i>d</i> means the edit distance of match, and --> means forward, <-- means reverse </li>";
file << "<li> For pair-end sequencing, MutScan tries to merge each pair, and the overlapped bases will be assigned higher qualities </li>";
file << "</ul></div>";
}
void MultiHtmlReporter::printHeader(ofstream& file){
file << "<html><head><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />";
file << "<title>MutScan report</title>";
printJS(file);
printCSS(file);
file << "</head>";
file << "<body><div id='container'>";
}
void MultiHtmlReporter::printCSS(ofstream& file){
file << "<style type=\"text/css\">";
file << "td {border:1px solid #dddddd;padding-left:2px;padding-right:2px;font-size:10px;}";
file << "table {border:1px solid #999999;padding:2x;border-collapse:collapse;}";
file << "img {padding:30px;}";
file << ".alignleft {text-align:left;}";
file << ".alignright {text-align:right;}";
file << ".header {color:#ffffff;padding:1px;height:20px;background:#000000;}";
file << ".figuretitle {color:#996657;font-size:20px;padding:50px;}";
file << "#container {text-align:center;padding:1px;font-family:Arial;}";
file << "#menu {padding-top:10px;padding-bottom:10px;text-align:left;}";
file << ".menu_item {text-align:left;padding-top:5px;font-size:18px;}";
file << ".highlight {text-align:left;padding-top:30px;padding-bottom:30px;font-size:20px;line-height:35px;}";
file << ".mutation_head {text-align:left;color:#0092FF;font-family:Arial;padding-top:20px;padding-bottom:5px;}";
file << ".mutation_block {}";
file << ".match_brief {font-size:8px}";
file << ".mutation_point {color:#FFCCAA}";
file << "#helper {text-align:left;border:1px dotted #fafafa;color:#777777;}";
file << "#footer {text-align:left;padding-left:10px;padding-top:20px;color:#777777;font-size:10px;}";
file << "</style>";
}
void MultiHtmlReporter::printJS(ofstream& file){
file << "\n<script type=\"text/javascript\">" << endl;
file << "function toggle(targetid){ \n\
if (document.getElementById){ \n\
target=document.getElementById(targetid); \n\
if (target.style.display=='table-row'){ \n\
target.style.display='none'; \n\
} else { \n\
target.style.display='table-row'; \n\
} \n\
} \n\
}";
file << "function toggle_target_list(targetid){ \n\
if (document.getElementById){ \n\
target=document.getElementById(targetid); \n\
if (target.style.display=='block'){ \n\
target.style.display='none'; \n\
document.getElementById('target_view_btn').value='view';\n\
} else { \n\
document.getElementById('target_view_btn').value='hide';\n\
target.style.display='block'; \n\
} \n\
} \n\
}";
file << "</script>";
}
string MultiHtmlReporter::getCurrentSystemTime()
{
auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
struct tm* ptm = localtime(&tt);
char date[60] = {0};
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",
(int)ptm->tm_year + 1900,(int)ptm->tm_mon + 1,(int)ptm->tm_mday,
(int)ptm->tm_hour,(int)ptm->tm_min,(int)ptm->tm_sec);
return std::string(date);
}
extern string command;
void MultiHtmlReporter::printFooter(ofstream& file){
file << "\n<div id='footer'> ";
file << "<p>"<<command<<"</p>";
printScanTargets(file);
file << "MutScan " << MUTSCAN_VER << ", at " << getCurrentSystemTime() << " </div>";
file << "</div></body></html>";
}
void MultiHtmlReporter::printScanTargets(ofstream& file){
file << "\n<div id='targets'> ";
file << "<p> scanned " << mMutationList.size() << " mutation spots...<input type='button' id='target_view_btn', onclick=toggle_target_list('target_list'); value='show'></input></p>";
file << "<ul id='target_list' style='display:none'>";
int id=0;
for(int i=0;i<mMutationList.size();i++){
id++;
file<<"<li> " << id << ", " << mMutationList[i].mName << "</li>";
}
file << "</ul></div>";
}<|endoftext|> |
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#include <nvcore/Ptr.h>
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/Containers.h>
#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>
#include <nvimage/FloatImage.h>
#include <nvimage/Filter.h>
#include <nvimage/DirectDrawSurface.h>
#include <nvmath/Color.h>
#include <nvmath/Vector.h>
#include <math.h>
#include "cmdline.h"
static bool loadImage(nv::Image & image, const char * fileName)
{
if (nv::strCaseCmp(nv::Path::extension(fileName), ".dds") == 0)
{
nv::DirectDrawSurface dds(fileName);
if (!dds.isValid())
{
printf("The file '%s' is not a valid DDS file.\n", fileName);
return false;
}
dds.mipmap(&image, 0, 0); // get first image
}
else
{
// Regular image.
if (!image.load(fileName))
{
printf("The file '%s' is not a supported image type.\n", fileName);
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
//MyAssertHandler assertHandler;
MyMessageHandler messageHandler;
float scale = 0.5f;
nv::Path input;
nv::Path output;
// Parse arguments.
for (int i = 1; i < argc; i++)
{
// Input options.
if (strcmp("-s", argv[i]) == 0)
{
if (i+1 < argc && argv[i+1][0] != '-') {
scale = atof(argv[i+1]);
i++;
}
}
else if (argv[i][0] != '-')
{
input = argv[i];
if (i+1 < argc && argv[i+1][0] != '-') {
output = argv[i+1];
}
break;
}
}
if (input.isNull() || output.isNull())
{
printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");
printf("usage: resize [options] input [output]\n\n");
printf("Diff options:\n");
printf(" -s scale \tScale factor (default = 0.5).\n");
return 1;
}
nv::Image image;
if (!loadImage(image, input)) return 0;
nv::FloatImage fimage(&image);
// fimage.toLinear(0, 3);
// nv::AutoPtr<nv::FloatImage> fresult(fimage.fastDownSample());
// nv::Kernel1 k(10);
// k.initKaiser(4, scale, 20);
// nv::AutoPtr<nv::FloatImage> fresult(fimage.downSample(k, image.width() * scale, image.height() * scale, nv::FloatImage::WrapMode_Clamp));
nv::BoxFilter filter;
nv::AutoPtr<nv::FloatImage> fresult(fimage.downSample(filter, image.width() * scale, image.height() * scale, nv::FloatImage::WrapMode_Mirror));
nv::AutoPtr<nv::Image> result(fresult->createImageGammaCorrect(1.0));
nv::StdOutputStream stream(output);
nv::ImageIO::saveTGA(stream, result.ptr());
return 0;
}
<commit_msg>Add nvzoom tool.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#include <nvcore/Ptr.h>
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/Containers.h>
#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>
#include <nvimage/FloatImage.h>
#include <nvimage/Filter.h>
#include <nvimage/DirectDrawSurface.h>
#include <nvmath/Color.h>
#include <nvmath/Vector.h>
#include <math.h>
#include "cmdline.h"
static bool loadImage(nv::Image & image, const char * fileName)
{
if (nv::strCaseCmp(nv::Path::extension(fileName), ".dds") == 0)
{
nv::DirectDrawSurface dds(fileName);
if (!dds.isValid())
{
printf("The file '%s' is not a valid DDS file.\n", fileName);
return false;
}
dds.mipmap(&image, 0, 0); // get first image
}
else
{
// Regular image.
if (!image.load(fileName))
{
printf("The file '%s' is not a supported image type.\n", fileName);
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
//MyAssertHandler assertHandler;
MyMessageHandler messageHandler;
float scale = 0.5f;
float gamma = 2.2f;
nv::Filter * filter = NULL;
nv::Path input;
nv::Path output;
// Parse arguments.
for (int i = 1; i < argc; i++)
{
// Input options.
if (strcmp("-s", argv[i]) == 0)
{
if (i+1 < argc && argv[i+1][0] != '-') {
scale = atof(argv[i+1]);
i++;
}
}
else if (strcmp("-g", argv[i]) == 0)
{
if (i+1 < argc && argv[i+1][0] != '-') {
gamma = atof(argv[i+1]);
i++;
}
}
else if (strcmp("-f", argv[i]) == 0)
{
if (i+1 == argc) break;
i++;
if (strcmp("box", argv[i]) == 0) filter = new nv::BoxFilter();
else if (strcmp("triangle", argv[i]) == 0) filter = new nv::TriangleFilter();
else if (strcmp("quadratic", argv[i]) == 0) filter = new nv::QuadraticFilter();
else if (strcmp("bspline", argv[i]) == 0) filter = new nv::BSplineFilter();
else if (strcmp("mitchell", argv[i]) == 0) filter = new nv::MitchellFilter();
else if (strcmp("lanczos", argv[i]) == 0) filter = new nv::LanczosFilter();
else if (strcmp("kaiser", argv[i]) == 0) {
filter = new nv::KaiserFilter(5);
((nv::KaiserFilter *)filter)->setParameters(4.0f, 1.0f);
}
}
else if (argv[i][0] != '-')
{
input = argv[i];
if (i+1 < argc && argv[i+1][0] != '-') {
output = argv[i+1];
}
break;
}
}
if (input.isNull() || output.isNull())
{
printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");
printf("usage: nvzoom [options] input [output]\n\n");
printf("Options:\n");
printf(" -s scale Scale factor (default = 0.5)\n");
printf(" -g gamma Gamma correction (default = 2.2)\n");
printf(" -f filter One of the following: (default = 'box')\n");
printf(" * box\n");
printf(" * triangle\n");
printf(" * quadratic\n");
printf(" * bspline\n");
printf(" * mitchell\n");
printf(" * lanczos\n");
printf(" * kaiser\n");
return 1;
}
if (filter == NULL)
{
filter = new nv::BoxFilter();
}
nv::Image image;
if (!loadImage(image, input)) return 0;
nv::FloatImage fimage(&image);
fimage.toLinear(0, 3, gamma);
nv::AutoPtr<nv::FloatImage> fresult(fimage.downSample(*filter, image.width() * scale, image.height() * scale, nv::FloatImage::WrapMode_Mirror));
nv::AutoPtr<nv::Image> result(fresult->createImageGammaCorrect(gamma));
nv::StdOutputStream stream(output);
nv::ImageIO::saveTGA(stream, result.ptr()); // @@ Add generic save function. Add support for png too.
delete filter;
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) 2018, Jan Koester jan.koester@gmx.net
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 <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "thread.h"
libhttppp::Thread::Thread(){
_ThreadId = -1;
_nextThread=NULL;
}
libhttppp::Thread::~Thread(){
}
void libhttppp::Thread::Create(LPTHREAD_START_ROUTINE function, void* arguments) {
HTTPException httpexception;
_Thread = CreateThread(NULL, 0, function, arguments, 0, &_ThreadId);
if (_Thread == NULL) {
httpexception.Critical("Can't create Thread!", GetLastError());
throw httpexception;
}
}
void libhttppp::Thread::Detach() {
HTTPException httpexception;
httpexception.Note("Detach not support by this OS");
}
DWORD libhttppp::Thread::getThreadID() {
return _ThreadId;
}
HANDLE libhttppp::Thread::getHandle() {
return _Thread;
}
void libhttppp::Thread::Join(){
}
libhttppp::Thread *libhttppp::Thread::nextThread(){
return _nextThread;
}
<commit_msg>first adds for threadpool support<commit_after>/*******************************************************************************
Copyright (c) 2018, Jan Koester jan.koester@gmx.net
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 <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "thread.h"
libhttppp::Thread::Thread(){
_ThreadId = -1;
_nextThread=NULL;
}
libhttppp::Thread::~Thread(){
}
void libhttppp::Thread::Create(LPTHREAD_START_ROUTINE function, void* arguments) {
HTTPException httpexception;
_Thread = CreateThread(NULL, 0, function, arguments, 0, &_ThreadId);
if (_Thread == NULL) {
httpexception.Critical("Can't create Thread!", GetLastError());
throw httpexception;
}
}
void libhttppp::Thread::Detach() {
HTTPException httpexception;
httpexception.Note("Detach not support by this OS");
}
DWORD libhttppp::Thread::getThreadID() {
return _ThreadId;
}
HANDLE libhttppp::Thread::getHandle() {
return _Thread;
}
void libhttppp::Thread::Join(){
WaitForSingleObject(_Thread, INFINITE);
}
libhttppp::Thread *libhttppp::Thread::nextThread(){
return _nextThread;
}
<|endoftext|> |
<commit_before>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "preferences_dialog.h"
#include "wx/filepicker.h"
#include "wx/stdpaths.h"
#include "wx/xrc/xmlres.h"
BEGIN_EVENT_TABLE(PreferencesDialog, wxDialog)
EVT_BUTTON(wxID_CANCEL, PreferencesDialog::OnButtonCancel)
EVT_BUTTON(wxID_OK, PreferencesDialog::OnButtonOk)
EVT_CLOSE(PreferencesDialog::OnClose)
END_EVENT_TABLE()
PreferencesDialog::PreferencesDialog(
wxWindow* parent,
SpanAnalyzerConfig* config) {
// loads dialog from virtual xrc file system
wxXmlResource::Get()->LoadDialog(this, parent,
"span_analyzer_preferences_dialog");
// saves doc reference
config_ = config;
// updates the cable directory
wxDirPickerCtrl* dirpickerctrl = XRCCTRL(*this, "dirpickerctrl_cable",
wxDirPickerCtrl);
/// \todo replace this with commented text below
dirpickerctrl->SetPath(config_->cable_directory);
//// takes the relative directory path and makes absolute
//wxFileName dir(wxGetCwd(), data_config->cable_directory, wxPATH_NATIVE);
//dirpickerctrl->SetPath(dir.GetFullPath());
// disables the metric option and selects imperial
wxRadioBox* radiobox = XRCCTRL(*this, "radiobox_units", wxRadioBox);
radiobox->Enable(0, false);
radiobox->SetSelection(1);
// fits the dialog around the sizers
this->Fit();
}
PreferencesDialog::~PreferencesDialog() {
}
/// \brief Handles the cancel button event.
/// \param[in] event
/// The event.
void PreferencesDialog::OnButtonCancel(wxCommandEvent& event) {
EndModal(wxID_CANCEL);
}
/// \brief Handles the Ok button event.
/// \param[in] event
/// The event.
void PreferencesDialog::OnButtonOk(wxCommandEvent& event) {
// transfers units
wxRadioBox* radiobox = XRCCTRL(*this, "radiobox_units", wxRadioBox);
if (radiobox->GetSelection() == 0) {
config_->units = units::UnitSystem::kMetric;
} else if (radiobox->GetSelection() == 1) {
config_->units = units::UnitSystem::kImperial;
}
// transfers cable directory
// gets absolute file location from dialog and converts to relative path
wxDirPickerCtrl* dirpickerctrl = XRCCTRL(*this, "dirpickerctrl_cable",
wxDirPickerCtrl);
wxFileName dir(dirpickerctrl->GetPath());
dir.MakeRelativeTo(wxGetCwd());
config_->cable_directory = dir.GetFullPath(wxPATH_UNIX);
EndModal(wxID_OK);
}
/// \brief Handles the close event.
/// \param[in] event
/// The event.
void PreferencesDialog::OnClose(wxCloseEvent& event) {
EndModal(wxID_CLOSE);
}
<commit_msg>Updated PreferencesDialog to convert config cable directory to absolute before passing to dirpickerctrl.<commit_after>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "preferences_dialog.h"
#include "wx/filepicker.h"
#include "wx/stdpaths.h"
#include "wx/xrc/xmlres.h"
BEGIN_EVENT_TABLE(PreferencesDialog, wxDialog)
EVT_BUTTON(wxID_CANCEL, PreferencesDialog::OnButtonCancel)
EVT_BUTTON(wxID_OK, PreferencesDialog::OnButtonOk)
EVT_CLOSE(PreferencesDialog::OnClose)
END_EVENT_TABLE()
PreferencesDialog::PreferencesDialog(
wxWindow* parent,
SpanAnalyzerConfig* config) {
// loads dialog from virtual xrc file system
wxXmlResource::Get()->LoadDialog(this, parent,
"span_analyzer_preferences_dialog");
// saves doc reference
config_ = config;
// updates the cable directory
wxDirPickerCtrl* dirpickerctrl = XRCCTRL(*this, "dirpickerctrl_cable",
wxDirPickerCtrl);
// takes the relative config directory path and makes absolute
wxFileName dir(config_->cable_directory);
dir.MakeAbsolute(wxFileName::GetCwd());
dirpickerctrl->SetPath(dir.GetFullPath());
// disables the metric option and selects imperial
wxRadioBox* radiobox = XRCCTRL(*this, "radiobox_units", wxRadioBox);
radiobox->Enable(0, false);
radiobox->SetSelection(1);
// fits the dialog around the sizers
this->Fit();
}
PreferencesDialog::~PreferencesDialog() {
}
/// \brief Handles the cancel button event.
/// \param[in] event
/// The event.
void PreferencesDialog::OnButtonCancel(wxCommandEvent& event) {
EndModal(wxID_CANCEL);
}
/// \brief Handles the Ok button event.
/// \param[in] event
/// The event.
void PreferencesDialog::OnButtonOk(wxCommandEvent& event) {
// transfers units
wxRadioBox* radiobox = XRCCTRL(*this, "radiobox_units", wxRadioBox);
if (radiobox->GetSelection() == 0) {
config_->units = units::UnitSystem::kMetric;
} else if (radiobox->GetSelection() == 1) {
config_->units = units::UnitSystem::kImperial;
}
// transfers cable directory
// gets application working directory and converts to relative path
wxDirPickerCtrl* dirpickerctrl = XRCCTRL(*this, "dirpickerctrl_cable",
wxDirPickerCtrl);
wxFileName dir(dirpickerctrl->GetPath());
dir.MakeRelativeTo(wxFileName::GetCwd());
config_->cable_directory = dir.GetFullPath(wxPATH_UNIX);
EndModal(wxID_OK);
}
/// \brief Handles the close event.
/// \param[in] event
/// The event.
void PreferencesDialog::OnClose(wxCloseEvent& event) {
EndModal(wxID_CLOSE);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/sendcoinsentry.h>
#include <qt/forms/ui_sendcoinsentry.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
if (platformStyle->getUseExtraSpacing())
ui->payToLayout->setSpacing(4);
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
// These icons are needed on Mac also!
ui->addressBookButton->setIcon(QIcon(":/icons/address-book"));
ui->pasteButton->setIcon(QIcon(":/icons/editpaste"));
ui->deleteButton->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_is->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_s->setIcon(QIcon(":/icons/remove"));
// normal dash address field
GUIUtil::setupAddressWidget(ui->payTo, this, true);
// just a label for displaying dash address(es)
ui->payTo_is->setFont(GUIUtil::fixedPitchFont());
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->checkboxSubtractFeeFromAmount, SIGNAL(toggled(bool)), this, SIGNAL(subtractFeeFromAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->useAvailableBalanceButton, SIGNAL(clicked()), this, SLOT(useAvailableBalanceClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
SendCoinsRecipient rcp;
if (GUIUtil::parseBitcoinURI(address, &rcp)) {
ui->payTo->blockSignals(true);
setValue(rcp);
ui->payTo->blockSignals(false);
} else {
updateLabel(rcp.address);
}
}
void SendCoinsEntry::setModel(WalletModel *_model)
{
this->model = _model;
if (_model && _model->getOptionsModel())
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::checkSubtractFeeFromAmount()
{
ui->checkboxSubtractFeeFromAmount->setChecked(true);
}
void SendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
void SendCoinsEntry::useAvailableBalanceClicked()
{
Q_EMIT useAvailableBalance(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked);
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount);
QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->payTo->setText(recipient.address);
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
updateLabel(recipient.address);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
void SendCoinsEntry::setAmount(const CAmount &amount)
{
ui->payAmount->setValue(amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<commit_msg>qt: Fix label updates in SendCoinsEntry (#3523)<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/sendcoinsentry.h>
#include <qt/forms/ui_sendcoinsentry.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
if (platformStyle->getUseExtraSpacing())
ui->payToLayout->setSpacing(4);
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
// These icons are needed on Mac also!
ui->addressBookButton->setIcon(QIcon(":/icons/address-book"));
ui->pasteButton->setIcon(QIcon(":/icons/editpaste"));
ui->deleteButton->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_is->setIcon(QIcon(":/icons/remove"));
ui->deleteButton_s->setIcon(QIcon(":/icons/remove"));
// normal dash address field
GUIUtil::setupAddressWidget(ui->payTo, this, true);
// just a label for displaying dash address(es)
ui->payTo_is->setFont(GUIUtil::fixedPitchFont());
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->checkboxSubtractFeeFromAmount, SIGNAL(toggled(bool)), this, SIGNAL(subtractFeeFromAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->useAvailableBalanceButton, SIGNAL(clicked()), this, SLOT(useAvailableBalanceClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
SendCoinsRecipient rcp;
if (GUIUtil::parseBitcoinURI(address, &rcp)) {
ui->payTo->blockSignals(true);
setValue(rcp);
ui->payTo->blockSignals(false);
} else {
updateLabel(address);
}
}
void SendCoinsEntry::setModel(WalletModel *_model)
{
this->model = _model;
if (_model && _model->getOptionsModel())
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::checkSubtractFeeFromAmount()
{
ui->checkboxSubtractFeeFromAmount->setChecked(true);
}
void SendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
void SendCoinsEntry::useAvailableBalanceClicked()
{
Q_EMIT useAvailableBalance(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked);
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount);
QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->payTo->setText(recipient.address);
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
updateLabel(recipient.address);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
void SendCoinsEntry::setAmount(const CAmount &amount)
{
ui->payAmount->setValue(amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.