text
stringlengths 54
60.6k
|
---|
<commit_before>#include "AirwaySegmentation.hpp"
#include "FAST/Algorithms/GaussianSmoothingFilter/GaussianSmoothingFilter.hpp"
#include "FAST/Data/Segmentation.hpp"
#include <unordered_set>
#include <stack>
namespace fast {
AirwaySegmentation::AirwaySegmentation() {
createInputPort<Image>(0);
createOutputPort<Segmentation>(0, OUTPUT_DEPENDS_ON_INPUT, 0);
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "Algorithms/AirwaySegmentation/AirwaySegmentation.cl");
}
Vector3i findSeedVoxel(Image::pointer volume) {
ImageAccess::pointer access = volume->getImageAccess(ACCESS_READ);
short* data = (short*)access->get();
int slice = volume->getDepth()*0.6;
int threshold = -700;
int Tseed = -1000;
float minArea = 7.5f*7.5f*3.14f; // min radius of 7.5
float maxArea = 25.0f*25.0f*3.14f; // max radius of 25.0
Vector3i currentSeed(0,0,0);
float currentCentricity = 99999.0f; // Distance from center
float spacing = 1.0f;//volume->getSpacing().x();
std::unordered_set<int> visited;
int width = volume->getWidth();
int height = volume->getHeight();
int depth = volume->getDepth();
for(int x = width*0.25; x < width*0.75; ++x) {
for(int y = height*0.25; y < height*0.75; ++y) {
Vector3i testSeed(x,y,slice);
if(data[testSeed.x() + testSeed.y()*width + testSeed.z()*width*height] > Tseed)
continue;
std::stack<Vector3i> stack;
stack.push(testSeed);
int perimenter = 0;
bool invalid = false;
visited.clear();
visited.insert(testSeed.x()+testSeed.y()*width);
while(!stack.empty() && !invalid) {
Vector3i v = stack.top();
stack.pop();
for(int a = -1; a < 2 && !invalid; ++a) {
for(int b = -1; b < 2; ++b) {
Vector3i c(v.x()+a, v.y()+b, v.z());
if(c.x() < 0 || c.y() < 0 ||
c.x() >= width || c.y() >= height) {
invalid = true;
break;
}
if(data[c.x() + c.y()*width + c.z()*width*height] <= threshold && visited.find(c.x()+c.y()*volume->getWidth()) == visited.end()) {
visited.insert(c.x()+c.y()*volume->getWidth());
stack.push(c);
if(visited.size()*spacing*spacing > maxArea) {
invalid = true;
break;
}
}
}}
}
//float compaction = (4.0f*3.14*area)/(perimenter*perimenter);
if(!invalid && visited.size()*spacing*spacing > minArea) {
float centricity = sqrt(pow(testSeed.x()-volume->getWidth()*0.5f,2.0f)+pow(testSeed.y()-volume->getHeight()*0.5f,2.0f));
if(centricity < currentCentricity) {
// Accept as new seed
currentSeed = testSeed;
currentCentricity = centricity;
}
}
}
}
return currentSeed;
}
int grow(uchar* segmentation, const Vector3i neighbors[25], std::vector<Vector3i>* voxels, short* data, float threshold, int width, int height, int depth) {
std::vector<Vector3i>::iterator it;
std::stack<Vector3i> stack;
// TODO voxels coming in here consists of all voxels, should only need to add the front..
for(it = voxels->begin(); it != voxels->end(); it++) {
stack.push(*it);
}
while(!stack.empty()) {
Vector3i x = stack.top();
stack.pop();
segmentation[x.x() + x.y()*width + x.z()*width*height] = 1; // TODO is this needed?
// Add 26 neighbors
for(int i = 0; i < 25; ++i) {
Vector3i neighbor = neighbors[i];
Vector3i y(x.x()+neighbor.x(), x.y()+neighbor.y(), x.z()+neighbor.z());
if(y.x() < 0 || y.y() < 0 || y.z() < 0 ||
y.x() >= width || y.y() >= height || y.z() >= depth) {
continue;
}
if(data[y.x() + y.y()*width + y.z()*width*height] <= threshold && segmentation[y.x() + y.y()*width + y.z()*width*height] == 0) {
segmentation[y.x() + y.y()*width + y.z()*width*height] = 1;
voxels->push_back(y);
stack.push(y);
}
}
}
return voxels->size();
}
void regionGrowing(Image::pointer volume, Segmentation::pointer segmentation, Vector3i seed) {
int width = volume->getWidth();
int height = volume->getHeight();
int depth = volume->getDepth();
segmentation->createFromImage(volume);
ImageAccess::pointer access = volume->getImageAccess(ACCESS_READ);
short* data = (short*)access->get();
ImageAccess::pointer access2 = segmentation->getImageAccess(ACCESS_READ_WRITE);
uchar* segmentationData = (uchar*)access2->get();
memset(segmentationData, 0, width*height*depth);
std::vector<Vector3i> voxels;
segmentationData[seed.x() + seed.y()*width + seed.z()*width*height] = 1;
voxels.push_back(seed);
float threshold = data[seed.x() + seed.y()*width + seed.z()*width*height];
float volumeIncreaseLimit = 20000.0f;
float volumeMinimum = 100000.0f;
float VT = 0.0f; // volume with given threshold
float deltaT = 2.0f;
float spacing = 1.0f;
// Create neighbor list
Vector3i neighbors[25];
int counter = 0;
for(int a = -1; a < 2; a++) {
for(int b = -1; b < 2; b++) {
for(int c = -1; c < 2; c++) {
if(a == 0 && b == 0 && c == 0)
continue;
neighbors[counter] = Vector3i(a,b,c);
counter++;
}}}
float Vnew = spacing*grow(segmentationData, neighbors, &voxels, data, threshold, width, height, depth);
// Loop until explosion is detected
do {
VT = Vnew;
threshold += deltaT;
Vnew = spacing*grow(segmentationData, neighbors, &voxels, data, threshold, width, height, depth);
Reporter::info() << "using threshold: " << threshold << Reporter::end;
Reporter::info() << "gives volume size: " << Vnew << Reporter::end;
} while(Vnew-VT < volumeIncreaseLimit || Vnew < volumeMinimum);
float explosionVolume = Vnew;
Reporter::info() << "Ungrowing.." << Vnew << Reporter::end;
threshold -= deltaT;
VT = Vnew;
// Ungrow until the volume is less than 95% of V
while(VT >= 0.95f*explosionVolume) {
voxels.clear();
voxels.push_back(seed);
memset(segmentationData, 0, width*height*depth);
segmentationData[seed.x() + seed.y()*width + seed.z()*width*height] = 1;
VT = spacing*grow(segmentationData, neighbors, &voxels, data, threshold, width, height, depth);
Reporter::info() << "using threshold: " << threshold << Reporter::end;
Reporter::info() << "gives volume size: " << VT << Reporter::end;
threshold -= deltaT;
}
}
Image::pointer AirwaySegmentation::convertToHU(Image::pointer image) {
// TODO need support for no 3d write
OpenCLDevice::pointer device = getMainDevice();
cl::Program program = getOpenCLProgram(device);
OpenCLImageAccess::pointer input = image->getOpenCLImageAccess(ACCESS_READ, device);
Image::pointer newImage = Image::New();
newImage->create(image->getSize(), TYPE_INT16, 1);
newImage->setSpacing(image->getSpacing());
SceneGraph::setParentNode(newImage, image);
cl::Kernel kernel(program, "convertToHU");
kernel.setArg(0, *input->get3DImage());
if(device->isWritingTo3DTexturesSupported()) {
OpenCLImageAccess::pointer output = newImage->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
kernel.setArg(1, *output->get3DImage());
} else {
OpenCLBufferAccess::pointer output = newImage->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
kernel.setArg(1, *output->get());
}
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(image->getWidth(), image->getHeight(), image->getDepth()),
cl::NullRange
);
return newImage;
}
void AirwaySegmentation::morphologicalClosing(Segmentation::pointer segmentation) {
int width = segmentation->getWidth();
int height = segmentation->getHeight();
int depth = segmentation->getDepth();
// TODO need support for no 3d write
OpenCLDevice::pointer device = getMainDevice();
cl::Program program = getOpenCLProgram(device);
Segmentation::pointer segmentation2 = Segmentation::New();
segmentation2->create(segmentation->getSize(), TYPE_UINT8, 1);
ImageAccess::pointer access = segmentation2->getImageAccess(ACCESS_READ_WRITE);
uchar* data = (uchar*)access->get();
memset(data, 0, width*height*depth);
access->release();
cl::Kernel dilateKernel(program, "dilate");
cl::Kernel erodeKernel(program, "erode");
if(device->isWritingTo3DTexturesSupported()) {
OpenCLImageAccess::pointer input = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
OpenCLImageAccess::pointer input2 = segmentation2->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
dilateKernel.setArg(0, *input->get3DImage());
dilateKernel.setArg(1, *input2->get3DImage());
} else {
OpenCLImageAccess::pointer input = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
OpenCLBufferAccess::pointer input2 = segmentation2->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
dilateKernel.setArg(0, *input->get3DImage());
dilateKernel.setArg(1, *input2->get());
}
device->getCommandQueue().enqueueNDRangeKernel(
dilateKernel,
cl::NullRange,
cl::NDRange(width, height, depth),
cl::NullRange
);
if(device->isWritingTo3DTexturesSupported()) {
OpenCLImageAccess::pointer input = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
OpenCLImageAccess::pointer input2 = segmentation2->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
erodeKernel.setArg(0, *input2->get3DImage());
erodeKernel.setArg(1, *input->get3DImage());
} else {
OpenCLBufferAccess::pointer input = segmentation->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
OpenCLImageAccess::pointer input2 = segmentation2->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
erodeKernel.setArg(0, *input2->get3DImage());
erodeKernel.setArg(1, *input->get());
}
device->getCommandQueue().enqueueNDRangeKernel(
erodeKernel,
cl::NullRange,
cl::NDRange(width, height, depth),
cl::NullRange
);
}
void AirwaySegmentation::execute() {
Image::pointer image = getStaticInputData<Image>();
// Convert to signed HU if unsigned
if(image->getDataType() == TYPE_UINT16) {
image = convertToHU(image);
}
// Smooth image
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setInputData(image);
filter->setStandardDeviation(0.5);
filter->update();
image = filter->getOutputData<Image>();
// Find seed voxel
Vector3i seed = findSeedVoxel(image);
if(seed == Vector3i::Zero()) {
throw Exception("No seed found.");
}
reportInfo() << "Seed found at " << seed.transpose() << reportEnd();
// Do the region growing
Segmentation::pointer segmentation = getStaticOutputData<Segmentation>();
regionGrowing(image, segmentation, seed);
// Do morphological closing to remove holes in segmentation
morphologicalClosing(segmentation);
}
}
<commit_msg>fixed a bug on mac in airway seg<commit_after>#include "AirwaySegmentation.hpp"
#include "FAST/Algorithms/GaussianSmoothingFilter/GaussianSmoothingFilter.hpp"
#include "FAST/Data/Segmentation.hpp"
#include <unordered_set>
#include <stack>
namespace fast {
AirwaySegmentation::AirwaySegmentation() {
createInputPort<Image>(0);
createOutputPort<Segmentation>(0, OUTPUT_DEPENDS_ON_INPUT, 0);
createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "Algorithms/AirwaySegmentation/AirwaySegmentation.cl");
}
Vector3i findSeedVoxel(Image::pointer volume) {
ImageAccess::pointer access = volume->getImageAccess(ACCESS_READ);
short* data = (short*)access->get();
int slice = volume->getDepth()*0.6;
int threshold = -700;
int Tseed = -1000;
float minArea = 7.5f*7.5f*3.14f; // min radius of 7.5
float maxArea = 25.0f*25.0f*3.14f; // max radius of 25.0
Vector3i currentSeed(0,0,0);
float currentCentricity = 99999.0f; // Distance from center
float spacing = 1.0f;//volume->getSpacing().x();
std::unordered_set<int> visited;
int width = volume->getWidth();
int height = volume->getHeight();
int depth = volume->getDepth();
for(int x = width*0.25; x < width*0.75; ++x) {
for(int y = height*0.25; y < height*0.75; ++y) {
Vector3i testSeed(x,y,slice);
if(data[testSeed.x() + testSeed.y()*width + testSeed.z()*width*height] > Tseed)
continue;
std::stack<Vector3i> stack;
stack.push(testSeed);
int perimenter = 0;
bool invalid = false;
visited.clear();
visited.insert(testSeed.x()+testSeed.y()*width);
while(!stack.empty() && !invalid) {
Vector3i v = stack.top();
stack.pop();
for(int a = -1; a < 2 && !invalid; ++a) {
for(int b = -1; b < 2; ++b) {
Vector3i c(v.x()+a, v.y()+b, v.z());
if(c.x() < 0 || c.y() < 0 ||
c.x() >= width || c.y() >= height) {
invalid = true;
break;
}
if(data[c.x() + c.y()*width + c.z()*width*height] <= threshold && visited.find(c.x()+c.y()*volume->getWidth()) == visited.end()) {
visited.insert(c.x()+c.y()*volume->getWidth());
stack.push(c);
if(visited.size()*spacing*spacing > maxArea) {
invalid = true;
break;
}
}
}}
}
//float compaction = (4.0f*3.14*area)/(perimenter*perimenter);
if(!invalid && visited.size()*spacing*spacing > minArea) {
float centricity = sqrt(pow(testSeed.x()-volume->getWidth()*0.5f,2.0f)+pow(testSeed.y()-volume->getHeight()*0.5f,2.0f));
if(centricity < currentCentricity) {
// Accept as new seed
currentSeed = testSeed;
currentCentricity = centricity;
}
}
}
}
return currentSeed;
}
int grow(uchar* segmentation, std::vector<Vector3i> neighbors, std::vector<Vector3i>* voxels, short* data, float threshold, int width, int height, int depth) {
std::vector<Vector3i>::iterator it;
std::stack<Vector3i> stack;
// TODO voxels coming in here consists of all voxels, should only need to add the front..
for(it = voxels->begin(); it != voxels->end(); it++) {
stack.push(*it);
}
while(!stack.empty()) {
Vector3i x = stack.top();
stack.pop();
segmentation[x.x() + x.y()*width + x.z()*width*height] = 1; // TODO is this needed?
// Add 26 neighbors
for(int i = 0; i < 25; ++i) {
Vector3i neighbor = neighbors[i];
Vector3i y(x.x()+neighbor.x(), x.y()+neighbor.y(), x.z()+neighbor.z());
if(y.x() < 0 || y.y() < 0 || y.z() < 0 ||
y.x() >= width || y.y() >= height || y.z() >= depth) {
continue;
}
if(data[y.x() + y.y()*width + y.z()*width*height] <= threshold && segmentation[y.x() + y.y()*width + y.z()*width*height] == 0) {
segmentation[y.x() + y.y()*width + y.z()*width*height] = 1;
voxels->push_back(y);
stack.push(y);
}
}
}
return voxels->size();
}
void regionGrowing(Image::pointer volume, Segmentation::pointer segmentation, Vector3i seed) {
int width = volume->getWidth();
int height = volume->getHeight();
int depth = volume->getDepth();
segmentation->createFromImage(volume);
ImageAccess::pointer access = volume->getImageAccess(ACCESS_READ);
short* data = (short*)access->get();
ImageAccess::pointer access2 = segmentation->getImageAccess(ACCESS_READ_WRITE);
uchar* segmentationData = (uchar*)access2->get();
memset(segmentationData, 0, width*height*depth);
std::vector<Vector3i> voxels;
segmentationData[seed.x() + seed.y()*width + seed.z()*width*height] = 1;
voxels.push_back(seed);
float threshold = data[seed.x() + seed.y()*width + seed.z()*width*height];
float volumeIncreaseLimit = 20000.0f;
float volumeMinimum = 100000.0f;
float VT = 0.0f; // volume with given threshold
float deltaT = 2.0f;
float spacing = 1.0f;
// Create neighbor list
std::vector<Vector3i> neighbors;
for(int a = -1; a < 2; a++) {
for(int b = -1; b < 2; b++) {
for(int c = -1; c < 2; c++) {
if(a == 0 && b == 0 && c == 0)
continue;
neighbors.push_back(Vector3i(a,b,c));
}}}
float Vnew = spacing*grow(segmentationData, neighbors, &voxels, data, threshold, width, height, depth);
// Loop until explosion is detected
do {
VT = Vnew;
threshold += deltaT;
Vnew = spacing*grow(segmentationData, neighbors, &voxels, data, threshold, width, height, depth);
Reporter::info() << "using threshold: " << threshold << Reporter::end;
Reporter::info() << "gives volume size: " << Vnew << Reporter::end;
} while(Vnew-VT < volumeIncreaseLimit || Vnew < volumeMinimum);
float explosionVolume = Vnew;
Reporter::info() << "Ungrowing.." << Vnew << Reporter::end;
threshold -= deltaT;
VT = Vnew;
// Ungrow until the volume is less than 95% of V
while(VT >= 0.95f*explosionVolume) {
voxels.clear();
voxels.push_back(seed);
memset(segmentationData, 0, width*height*depth);
segmentationData[seed.x() + seed.y()*width + seed.z()*width*height] = 1;
VT = spacing*grow(segmentationData, neighbors, &voxels, data, threshold, width, height, depth);
Reporter::info() << "using threshold: " << threshold << Reporter::end;
Reporter::info() << "gives volume size: " << VT << Reporter::end;
threshold -= deltaT;
}
}
Image::pointer AirwaySegmentation::convertToHU(Image::pointer image) {
// TODO need support for no 3d write
OpenCLDevice::pointer device = getMainDevice();
cl::Program program = getOpenCLProgram(device);
OpenCLImageAccess::pointer input = image->getOpenCLImageAccess(ACCESS_READ, device);
Image::pointer newImage = Image::New();
newImage->create(image->getSize(), TYPE_INT16, 1);
newImage->setSpacing(image->getSpacing());
SceneGraph::setParentNode(newImage, image);
cl::Kernel kernel(program, "convertToHU");
kernel.setArg(0, *input->get3DImage());
if(device->isWritingTo3DTexturesSupported()) {
OpenCLImageAccess::pointer output = newImage->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
kernel.setArg(1, *output->get3DImage());
} else {
OpenCLBufferAccess::pointer output = newImage->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
kernel.setArg(1, *output->get());
}
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(image->getWidth(), image->getHeight(), image->getDepth()),
cl::NullRange
);
return newImage;
}
void AirwaySegmentation::morphologicalClosing(Segmentation::pointer segmentation) {
int width = segmentation->getWidth();
int height = segmentation->getHeight();
int depth = segmentation->getDepth();
// TODO need support for no 3d write
OpenCLDevice::pointer device = getMainDevice();
cl::Program program = getOpenCLProgram(device);
Segmentation::pointer segmentation2 = Segmentation::New();
segmentation2->create(segmentation->getSize(), TYPE_UINT8, 1);
ImageAccess::pointer access = segmentation2->getImageAccess(ACCESS_READ_WRITE);
uchar* data = (uchar*)access->get();
memset(data, 0, width*height*depth);
access->release();
cl::Kernel dilateKernel(program, "dilate");
cl::Kernel erodeKernel(program, "erode");
if(device->isWritingTo3DTexturesSupported()) {
OpenCLImageAccess::pointer input = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
OpenCLImageAccess::pointer input2 = segmentation2->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
dilateKernel.setArg(0, *input->get3DImage());
dilateKernel.setArg(1, *input2->get3DImage());
} else {
OpenCLImageAccess::pointer input = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
OpenCLBufferAccess::pointer input2 = segmentation2->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
dilateKernel.setArg(0, *input->get3DImage());
dilateKernel.setArg(1, *input2->get());
}
device->getCommandQueue().enqueueNDRangeKernel(
dilateKernel,
cl::NullRange,
cl::NDRange(width, height, depth),
cl::NullRange
);
if(device->isWritingTo3DTexturesSupported()) {
OpenCLImageAccess::pointer input = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
OpenCLImageAccess::pointer input2 = segmentation2->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
erodeKernel.setArg(0, *input2->get3DImage());
erodeKernel.setArg(1, *input->get3DImage());
} else {
OpenCLBufferAccess::pointer input = segmentation->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
OpenCLImageAccess::pointer input2 = segmentation2->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
erodeKernel.setArg(0, *input2->get3DImage());
erodeKernel.setArg(1, *input->get());
}
device->getCommandQueue().enqueueNDRangeKernel(
erodeKernel,
cl::NullRange,
cl::NDRange(width, height, depth),
cl::NullRange
);
}
void AirwaySegmentation::execute() {
Image::pointer image = getStaticInputData<Image>();
// Convert to signed HU if unsigned
if(image->getDataType() == TYPE_UINT16) {
image = convertToHU(image);
}
// Smooth image
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setInputData(image);
filter->setStandardDeviation(0.5);
filter->update();
image = filter->getOutputData<Image>();
// Find seed voxel
Vector3i seed = findSeedVoxel(image);
if(seed == Vector3i::Zero()) {
throw Exception("No seed found.");
}
reportInfo() << "Seed found at " << seed.transpose() << reportEnd();
// Do the region growing
Segmentation::pointer segmentation = getStaticOutputData<Segmentation>();
regionGrowing(image, segmentation, seed);
// Do morphological closing to remove holes in segmentation
morphologicalClosing(segmentation);
}
}
<|endoftext|> |
<commit_before>//******************************************************************
//
// Copyright 2017 Intel Corporation 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 "Interfaces.h"
#include "DeviceConfigurationResource.h"
#include "PlatformConfigurationResource.h"
#include "octypes.h"
#include <string.h>
namespace ajn {
namespace org {
namespace alljoyn {
namespace Config {
const char *InterfaceXml =
"<interface name='org.alljoyn.Config'>"
" <method name='FactoryReset'>"
" <annotation name='org.freedesktop.DBus.Method.NoReply' value='true'/>"
" </method>"
" <method name='GetConfigurations'>"
" <arg name='languageTag' type='s' direction='in'/>"
" <arg name='languages' type='a{sv}' direction='out'/>"
" </method>"
" <method name='ResetConfigurations'>"
" <arg name='languageTag' type='s' direction='in'/>"
" <arg name='fieldList' type='as' direction='in'/>"
" </method>"
" <method name='Restart'>"
" <annotation name='org.freedesktop.DBus.Method.NoReply' value='true'/>"
" </method>"
" <method name='SetPasscode'>"
" <arg name='DaemonRealm' type='s' direction='in'/>"
" <arg name='newPasscode' type='ay' direction='in'/>"
" </method>"
" <method name='UpdateConfigurations'>"
" <arg name='languageTag' type='s' direction='in'/>"
" <arg name='configMap' type='a{sv}' direction='in'/>"
" </method>"
" <property name='Version' type='q' access='read'/>"
// TODO " <annotation name='org.alljoyn.Bus.Secure' value='true'/>"
"</interface>";
}
}
}
}
bool IsInterfaceInWellDefinedSet(const char *name)
{
const char *wellDefined[] = {
/* OCF ASA Mapping */
"Environment.CurrentAirQuality", "Environment.CurrentAirQualityLevel",
"Environment.CurrentHumidity", "Environment.CurrentTemperature",
"Environment.TargetHumidity", "Environment.TargetTemperature",
"Environment.TargetTemperatureLevel", "Environment.WaterLevel", "Environment.WindDirection",
"Operation.AirRecirculationMode", "Operation.Alerts", "Operation.AudioVideoInput",
"Operation.AudioVolume", "Operation.BatteryStatus", "Operation.Channel",
"Operation.ClimateControlMode", "Operation.ClosedStatus", "Operation.CurrentPower",
"Operation.CycleControl", "Operation.DishWashingCyclePhase", "Operation.EnergyUsage",
"Operation.FanSpeedLevel", "Operation.FilterStatus", "Operation.HeatingZone",
"Operation.HvacFanMode", "Operation.LaundryCyclePhase", "Operation.MoistureOutputLevel",
"Operation.OffControl", "Operation.OnControl", "Operation.OnOffStatus",
"Operation.OvenCyclePhase", "Operation.PlugInUnits", "Operation.RapidMode",
"Operation.RemoteControllability", "Operation.RepeatMode", "Operation.ResourceSaving",
"Operation.RobotCleaningCyclePhase", "Operation.SoilLevel", "Operation.SpinSpeedLevel",
"Operation.Timer"
};
for (size_t i = 0; i < sizeof(wellDefined) / sizeof(wellDefined[0]); ++i)
{
if (!strcmp(wellDefined[i], name))
{
return true;
}
}
return false;
}
bool IsResourceTypeInWellDefinedSet(const char *name)
{
const char *wellDefined[] = {
/* OCF ASA Mapping */
"oic.r.airflow", "oic.r.airqualitycollection", "oic.r.audio", "oic.r.door", "oic.r.ecomode",
"oic.r.energy.battery", "oic.r.energy.usage", "oic.r.heatingzonecollection",
"oic.r.humidity", "oic.r.humidity", "oic.r.icemaker", "oic.r.media.input", "oic.r.mode",
"oic.r.operational.state", "oic.r.operationalstate", "oic.r.refrigeration", "oic.r.scanner",
"oic.r.selectablelevels", "oic.r.switch.binary", "oic.r.temperature", "oic.r.time.period"
};
for (size_t i = 0; i < sizeof(wellDefined) / sizeof(wellDefined[0]); ++i)
{
if (!strcmp(wellDefined[i], name))
{
return true;
}
}
return false;
}
bool TranslateInterface(const char *name)
{
const char *doNotTranslatePrefix[] = {
"org.alljoyn.Bus", "org.freedesktop.DBus"
};
for (size_t i = 0; i < sizeof(doNotTranslatePrefix) / sizeof(doNotTranslatePrefix[0]); ++i)
{
if (!strncmp(doNotTranslatePrefix[i], name, strlen(doNotTranslatePrefix[i])))
{
return false;
}
}
const char *doNotTranslate[] = {
"org.alljoyn.About", "org.alljoyn.Daemon", "org.alljoyn.Debug", "org.alljoyn.Icon",
"org.allseen.Introspectable"
};
for (size_t i = 0; i < sizeof(doNotTranslate) / sizeof(doNotTranslate[0]); ++i)
{
if (!strcmp(doNotTranslate[i], name))
{
return false;
}
}
const char *doDeepTranslation[] = {
"org.alljoyn.Config"
};
for (size_t i = 0; i < sizeof(doDeepTranslation) / sizeof(doDeepTranslation[0]); ++i)
{
if (!strcmp(doDeepTranslation[i], name))
{
return true;
}
}
return !IsInterfaceInWellDefinedSet(name);
}
bool TranslateResourceType(const char *name)
{
const char *doNotTranslate[] = {
"oic.d.bridge",
OC_RSRVD_RESOURCE_TYPE_COLLECTION, OC_RSRVD_RESOURCE_TYPE_DEVICE,
OC_RSRVD_RESOURCE_TYPE_INTROSPECTION, OC_RSRVD_RESOURCE_TYPE_PLATFORM,
OC_RSRVD_RESOURCE_TYPE_RD, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH, OC_RSRVD_RESOURCE_TYPE_RES,
"oic.r.alljoynobject", "oic.r.acl", "oic.r.acl2", "oic.r.amacl", "oic.r.cred", "oic.r.crl",
"oic.r.csr", "oic.r.doxm", "oic.r.pstat", "oic.r.roles", "oic.r.securemode"
};
for (size_t i = 0; i < sizeof(doNotTranslate) / sizeof(doNotTranslate[0]); ++i)
{
if (!strcmp(doNotTranslate[i], name))
{
return false;
}
}
const char *doDeepTranslation[] = {
OC_RSRVD_RESOURCE_TYPE_DEVICE_CONFIGURATION, OC_RSRVD_RESOURCE_TYPE_MAINTENANCE,
OC_RSRVD_RESOURCE_TYPE_PLATFORM_CONFIGURATION
};
for (size_t i = 0; i < sizeof(doDeepTranslation) / sizeof(doDeepTranslation[0]); ++i)
{
if (!strcmp(doDeepTranslation[i], name))
{
return true;
}
}
return !IsResourceTypeInWellDefinedSet(name);
}
<commit_msg>Translate devices that only include /oic/{d,p}.<commit_after>//******************************************************************
//
// Copyright 2017 Intel Corporation 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 "Interfaces.h"
#include "DeviceConfigurationResource.h"
#include "PlatformConfigurationResource.h"
#include "octypes.h"
#include <string.h>
namespace ajn {
namespace org {
namespace alljoyn {
namespace Config {
const char *InterfaceXml =
"<interface name='org.alljoyn.Config'>"
" <method name='FactoryReset'>"
" <annotation name='org.freedesktop.DBus.Method.NoReply' value='true'/>"
" </method>"
" <method name='GetConfigurations'>"
" <arg name='languageTag' type='s' direction='in'/>"
" <arg name='languages' type='a{sv}' direction='out'/>"
" </method>"
" <method name='ResetConfigurations'>"
" <arg name='languageTag' type='s' direction='in'/>"
" <arg name='fieldList' type='as' direction='in'/>"
" </method>"
" <method name='Restart'>"
" <annotation name='org.freedesktop.DBus.Method.NoReply' value='true'/>"
" </method>"
" <method name='SetPasscode'>"
" <arg name='DaemonRealm' type='s' direction='in'/>"
" <arg name='newPasscode' type='ay' direction='in'/>"
" </method>"
" <method name='UpdateConfigurations'>"
" <arg name='languageTag' type='s' direction='in'/>"
" <arg name='configMap' type='a{sv}' direction='in'/>"
" </method>"
" <property name='Version' type='q' access='read'/>"
// TODO " <annotation name='org.alljoyn.Bus.Secure' value='true'/>"
"</interface>";
}
}
}
}
bool IsInterfaceInWellDefinedSet(const char *name)
{
const char *wellDefined[] = {
/* OCF ASA Mapping */
"Environment.CurrentAirQuality", "Environment.CurrentAirQualityLevel",
"Environment.CurrentHumidity", "Environment.CurrentTemperature",
"Environment.TargetHumidity", "Environment.TargetTemperature",
"Environment.TargetTemperatureLevel", "Environment.WaterLevel", "Environment.WindDirection",
"Operation.AirRecirculationMode", "Operation.Alerts", "Operation.AudioVideoInput",
"Operation.AudioVolume", "Operation.BatteryStatus", "Operation.Channel",
"Operation.ClimateControlMode", "Operation.ClosedStatus", "Operation.CurrentPower",
"Operation.CycleControl", "Operation.DishWashingCyclePhase", "Operation.EnergyUsage",
"Operation.FanSpeedLevel", "Operation.FilterStatus", "Operation.HeatingZone",
"Operation.HvacFanMode", "Operation.LaundryCyclePhase", "Operation.MoistureOutputLevel",
"Operation.OffControl", "Operation.OnControl", "Operation.OnOffStatus",
"Operation.OvenCyclePhase", "Operation.PlugInUnits", "Operation.RapidMode",
"Operation.RemoteControllability", "Operation.RepeatMode", "Operation.ResourceSaving",
"Operation.RobotCleaningCyclePhase", "Operation.SoilLevel", "Operation.SpinSpeedLevel",
"Operation.Timer"
};
for (size_t i = 0; i < sizeof(wellDefined) / sizeof(wellDefined[0]); ++i)
{
if (!strcmp(wellDefined[i], name))
{
return true;
}
}
return false;
}
bool IsResourceTypeInWellDefinedSet(const char *name)
{
const char *wellDefined[] = {
/* OCF ASA Mapping */
"oic.r.airflow", "oic.r.airqualitycollection", "oic.r.audio", "oic.r.door", "oic.r.ecomode",
"oic.r.energy.battery", "oic.r.energy.usage", "oic.r.heatingzonecollection",
"oic.r.humidity", "oic.r.humidity", "oic.r.icemaker", "oic.r.media.input", "oic.r.mode",
"oic.r.operational.state", "oic.r.operationalstate", "oic.r.refrigeration", "oic.r.scanner",
"oic.r.selectablelevels", "oic.r.switch.binary", "oic.r.temperature", "oic.r.time.period"
};
for (size_t i = 0; i < sizeof(wellDefined) / sizeof(wellDefined[0]); ++i)
{
if (!strcmp(wellDefined[i], name))
{
return true;
}
}
return false;
}
bool TranslateInterface(const char *name)
{
const char *doNotTranslatePrefix[] = {
"org.alljoyn.Bus", "org.freedesktop.DBus"
};
for (size_t i = 0; i < sizeof(doNotTranslatePrefix) / sizeof(doNotTranslatePrefix[0]); ++i)
{
if (!strncmp(doNotTranslatePrefix[i], name, strlen(doNotTranslatePrefix[i])))
{
return false;
}
}
const char *doNotTranslate[] = {
"org.alljoyn.About", "org.alljoyn.Daemon", "org.alljoyn.Debug", "org.alljoyn.Icon",
"org.allseen.Introspectable"
};
for (size_t i = 0; i < sizeof(doNotTranslate) / sizeof(doNotTranslate[0]); ++i)
{
if (!strcmp(doNotTranslate[i], name))
{
return false;
}
}
const char *doDeepTranslation[] = {
"org.alljoyn.Config"
};
for (size_t i = 0; i < sizeof(doDeepTranslation) / sizeof(doDeepTranslation[0]); ++i)
{
if (!strcmp(doDeepTranslation[i], name))
{
return true;
}
}
return !IsInterfaceInWellDefinedSet(name);
}
bool TranslateResourceType(const char *name)
{
const char *doNotTranslate[] = {
"oic.d.bridge",
OC_RSRVD_RESOURCE_TYPE_COLLECTION, OC_RSRVD_RESOURCE_TYPE_INTROSPECTION,
OC_RSRVD_RESOURCE_TYPE_RD, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH, OC_RSRVD_RESOURCE_TYPE_RES,
"oic.r.alljoynobject", "oic.r.acl", "oic.r.acl2", "oic.r.amacl", "oic.r.cred", "oic.r.crl",
"oic.r.csr", "oic.r.doxm", "oic.r.pstat", "oic.r.roles", "oic.r.securemode"
};
for (size_t i = 0; i < sizeof(doNotTranslate) / sizeof(doNotTranslate[0]); ++i)
{
if (!strcmp(doNotTranslate[i], name))
{
return false;
}
}
const char *doDeepTranslation[] = {
OC_RSRVD_RESOURCE_TYPE_DEVICE, OC_RSRVD_RESOURCE_TYPE_DEVICE_CONFIGURATION,
OC_RSRVD_RESOURCE_TYPE_MAINTENANCE, OC_RSRVD_RESOURCE_TYPE_PLATFORM,
OC_RSRVD_RESOURCE_TYPE_PLATFORM_CONFIGURATION
};
for (size_t i = 0; i < sizeof(doDeepTranslation) / sizeof(doDeepTranslation[0]); ++i)
{
if (!strcmp(doDeepTranslation[i], name))
{
return true;
}
}
return !IsResourceTypeInWellDefinedSet(name);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysetbase.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 00:05:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#include "propertysetbase.hxx"
#include <cppuhelper/typeprovider.hxx> // for getImplementationId()
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/uno/Reference.hxx>
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <vector>
using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::beans::Property;
using com::sun::star::beans::XPropertySetInfo;
oslInterlockedCount SAL_CALL PropertyAccessorBase::acquire()
{
return ++m_refCount;
}
oslInterlockedCount SAL_CALL PropertyAccessorBase::release()
{
if ( --m_refCount == 0 )
{
delete this;
return 0;
}
return m_refCount;
}
PropertySetBase::PropertySetBase( )
:m_pProperties( NULL )
{
}
PropertySetBase::~PropertySetBase( )
{
DELETEZ( m_pProperties );
}
cppu::IPropertyArrayHelper& SAL_CALL PropertySetBase::getInfoHelper()
{
if ( !m_pProperties )
{
DBG_ASSERT( !m_aProperties.empty(), "PropertySetBase::getInfoHelper: no registered properties!" );
m_pProperties = new cppu::OPropertyArrayHelper( &m_aProperties[0], m_aProperties.size(), sal_False );
}
return *m_pProperties;
}
Reference< XPropertySetInfo > SAL_CALL PropertySetBase::getPropertySetInfo( ) throw(RuntimeException)
{
return cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper() );
}
void PropertySetBase::registerProperty( const Property& rProperty,
const ::rtl::Reference< PropertyAccessorBase >& rAccessor )
{
DBG_ASSERT( rAccessor.get(), "PropertySetBase::registerProperty: invalid property accessor, this will crash!" );
m_aAccessors.insert( PropertyAccessors::value_type( rProperty.Handle, rAccessor ) );
DBG_ASSERT( ( rAccessor->isWriteable() == true )
== ( ( rProperty.Attributes & com::sun::star::beans::PropertyAttribute::READONLY ) == 0 ),
"PropertySetBase::registerProperty: inconsistence!" );
m_aProperties.push_back( rProperty );
}
void PropertySetBase::notifyAndCachePropertyValue( sal_Int32 nHandle )
{
::osl::ClearableMutexGuard aGuard( GetMutex() );
PropertyValueCache::iterator aPos = m_aCache.find( nHandle );
if ( aPos == m_aCache.end() )
{ // method has never before been invoked for this property
try
{
// determine the type of this property
::cppu::IPropertyArrayHelper& rPropertyMetaData = getInfoHelper();
::rtl::OUString sPropName;
OSL_VERIFY( rPropertyMetaData.fillPropertyMembersByHandle( &sPropName, NULL, nHandle ) );
Property aProperty = rPropertyMetaData.getPropertyByName( sPropName );
// default construct a value of this type
Any aEmptyValue( NULL, aProperty.Type );
// insert into the cache
aPos = m_aCache.insert( PropertyValueCache::value_type( nHandle, aEmptyValue ) ).first;
}
catch( Exception& )
{
DBG_ERROR( "PropertySetBase::notifyAndCachePropertyValue: this is not expected to fail!" );
}
}
Any aOldValue = aPos->second;
// determine the current value
Any aNewValue;
getFastPropertyValue( aNewValue, nHandle );
// remember the old value
aPos->second = aNewValue;
aGuard.clear();
if ( aNewValue != aOldValue )
firePropertyChange( nHandle, aNewValue, aOldValue );
}
void PropertySetBase::initializePropertyValueCache( sal_Int32 nHandle )
{
Any aCurrentValue;
getFastPropertyValue( aCurrentValue, nHandle );
#if OSL_DEBUG_LEVEL > 0
::std::pair< PropertyValueCache::iterator, bool > aInsertResult =
#endif
m_aCache.insert( PropertyValueCache::value_type( nHandle, aCurrentValue ) );
DBG_ASSERT( aInsertResult.second, "PropertySetBase::initializePropertyValueCache: already cached a value for this property!" );
}
PropertyAccessorBase& PropertySetBase::locatePropertyHandler( sal_Int32 nHandle ) const
{
PropertyAccessors::const_iterator aPropertyPos = m_aAccessors.find( nHandle );
DBG_ASSERT( aPropertyPos != m_aAccessors.end() && aPropertyPos->second.get(),
"PropertySetBase::locatePropertyHandler: accessor map is corrupted!" );
// neither should this be called for handles where there is no accessor, nor should a
// NULL accssor be in the map
return *aPropertyPos->second;
}
sal_Bool SAL_CALL PropertySetBase::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle,
const Any& rValue )
throw (IllegalArgumentException)
{
PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
if ( !rAccessor.approveValue( rValue ) )
throw IllegalArgumentException( ::rtl::OUString(), *this, 0 );
rAccessor.getValue( rOldValue );
if ( rOldValue != rValue )
{
rConvertedValue = rValue; // no conversion at all
return sal_True;
}
return sal_False;
}
void SAL_CALL PropertySetBase::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue )
throw (Exception)
{
PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
rAccessor.setValue( rValue );
}
void SAL_CALL PropertySetBase::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const
{
PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
rAccessor.getValue( rValue );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.134); FILE MERGED 2008/04/01 15:16:41 thb 1.6.134.2: #i85898# Stripping all external header guards 2008/03/31 13:11:45 rt 1.6.134.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysetbase.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#include "propertysetbase.hxx"
#include <cppuhelper/typeprovider.hxx> // for getImplementationId()
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <tools/debug.hxx>
#include <vector>
using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::beans::Property;
using com::sun::star::beans::XPropertySetInfo;
oslInterlockedCount SAL_CALL PropertyAccessorBase::acquire()
{
return ++m_refCount;
}
oslInterlockedCount SAL_CALL PropertyAccessorBase::release()
{
if ( --m_refCount == 0 )
{
delete this;
return 0;
}
return m_refCount;
}
PropertySetBase::PropertySetBase( )
:m_pProperties( NULL )
{
}
PropertySetBase::~PropertySetBase( )
{
DELETEZ( m_pProperties );
}
cppu::IPropertyArrayHelper& SAL_CALL PropertySetBase::getInfoHelper()
{
if ( !m_pProperties )
{
DBG_ASSERT( !m_aProperties.empty(), "PropertySetBase::getInfoHelper: no registered properties!" );
m_pProperties = new cppu::OPropertyArrayHelper( &m_aProperties[0], m_aProperties.size(), sal_False );
}
return *m_pProperties;
}
Reference< XPropertySetInfo > SAL_CALL PropertySetBase::getPropertySetInfo( ) throw(RuntimeException)
{
return cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper() );
}
void PropertySetBase::registerProperty( const Property& rProperty,
const ::rtl::Reference< PropertyAccessorBase >& rAccessor )
{
DBG_ASSERT( rAccessor.get(), "PropertySetBase::registerProperty: invalid property accessor, this will crash!" );
m_aAccessors.insert( PropertyAccessors::value_type( rProperty.Handle, rAccessor ) );
DBG_ASSERT( ( rAccessor->isWriteable() == true )
== ( ( rProperty.Attributes & com::sun::star::beans::PropertyAttribute::READONLY ) == 0 ),
"PropertySetBase::registerProperty: inconsistence!" );
m_aProperties.push_back( rProperty );
}
void PropertySetBase::notifyAndCachePropertyValue( sal_Int32 nHandle )
{
::osl::ClearableMutexGuard aGuard( GetMutex() );
PropertyValueCache::iterator aPos = m_aCache.find( nHandle );
if ( aPos == m_aCache.end() )
{ // method has never before been invoked for this property
try
{
// determine the type of this property
::cppu::IPropertyArrayHelper& rPropertyMetaData = getInfoHelper();
::rtl::OUString sPropName;
OSL_VERIFY( rPropertyMetaData.fillPropertyMembersByHandle( &sPropName, NULL, nHandle ) );
Property aProperty = rPropertyMetaData.getPropertyByName( sPropName );
// default construct a value of this type
Any aEmptyValue( NULL, aProperty.Type );
// insert into the cache
aPos = m_aCache.insert( PropertyValueCache::value_type( nHandle, aEmptyValue ) ).first;
}
catch( Exception& )
{
DBG_ERROR( "PropertySetBase::notifyAndCachePropertyValue: this is not expected to fail!" );
}
}
Any aOldValue = aPos->second;
// determine the current value
Any aNewValue;
getFastPropertyValue( aNewValue, nHandle );
// remember the old value
aPos->second = aNewValue;
aGuard.clear();
if ( aNewValue != aOldValue )
firePropertyChange( nHandle, aNewValue, aOldValue );
}
void PropertySetBase::initializePropertyValueCache( sal_Int32 nHandle )
{
Any aCurrentValue;
getFastPropertyValue( aCurrentValue, nHandle );
#if OSL_DEBUG_LEVEL > 0
::std::pair< PropertyValueCache::iterator, bool > aInsertResult =
#endif
m_aCache.insert( PropertyValueCache::value_type( nHandle, aCurrentValue ) );
DBG_ASSERT( aInsertResult.second, "PropertySetBase::initializePropertyValueCache: already cached a value for this property!" );
}
PropertyAccessorBase& PropertySetBase::locatePropertyHandler( sal_Int32 nHandle ) const
{
PropertyAccessors::const_iterator aPropertyPos = m_aAccessors.find( nHandle );
DBG_ASSERT( aPropertyPos != m_aAccessors.end() && aPropertyPos->second.get(),
"PropertySetBase::locatePropertyHandler: accessor map is corrupted!" );
// neither should this be called for handles where there is no accessor, nor should a
// NULL accssor be in the map
return *aPropertyPos->second;
}
sal_Bool SAL_CALL PropertySetBase::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle,
const Any& rValue )
throw (IllegalArgumentException)
{
PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
if ( !rAccessor.approveValue( rValue ) )
throw IllegalArgumentException( ::rtl::OUString(), *this, 0 );
rAccessor.getValue( rOldValue );
if ( rOldValue != rValue )
{
rConvertedValue = rValue; // no conversion at all
return sal_True;
}
return sal_False;
}
void SAL_CALL PropertySetBase::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue )
throw (Exception)
{
PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
rAccessor.setValue( rValue );
}
void SAL_CALL PropertySetBase::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const
{
PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
rAccessor.getValue( rValue );
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <algorithm>
#include "formula/formulahelper.hxx"
#include <unotools/charclass.hxx>
#include <unotools/syslocale.hxx>
#include <boost/scoped_ptr.hpp>
namespace formula
{
namespace
{
class OEmptyFunctionDescription : public IFunctionDescription
{
public:
OEmptyFunctionDescription(){}
virtual ~OEmptyFunctionDescription(){}
virtual OUString getFunctionName() const SAL_OVERRIDE { return OUString(); }
virtual const IFunctionCategory* getCategory() const SAL_OVERRIDE { return NULL; }
virtual OUString getDescription() const SAL_OVERRIDE { return OUString(); }
virtual sal_Int32 getSuppressedArgumentCount() const SAL_OVERRIDE { return 0; }
virtual OUString getFormula(const ::std::vector< OUString >& ) const SAL_OVERRIDE { return OUString(); }
virtual void fillVisibleArgumentMapping(::std::vector<sal_uInt16>& ) const SAL_OVERRIDE {}
virtual void initArgumentInfo() const SAL_OVERRIDE {}
virtual OUString getSignature() const SAL_OVERRIDE { return OUString(); }
virtual OString getHelpId() const SAL_OVERRIDE { return ""; }
virtual sal_uInt32 getParameterCount() const SAL_OVERRIDE { return 0; }
virtual OUString getParameterName(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
virtual OUString getParameterDescription(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
virtual bool isParameterOptional(sal_uInt32 ) const SAL_OVERRIDE { return false; }
};
}
// class FormulaHelper - static Method
#define FUNC_NOTFOUND 0xffff
FormulaHelper::FormulaHelper(const IFunctionManager* _pFunctionManager)
:m_pSysLocale(new SvtSysLocale)
,m_pFunctionManager(_pFunctionManager)
,open(_pFunctionManager->getSingleToken(IFunctionManager::eOk))
,close(_pFunctionManager->getSingleToken(IFunctionManager::eClose))
,sep(_pFunctionManager->getSingleToken(IFunctionManager::eSep))
,arrayOpen(_pFunctionManager->getSingleToken(IFunctionManager::eArrayOpen))
,arrayClose(_pFunctionManager->getSingleToken(IFunctionManager::eArrayClose))
{
m_pCharClass = m_pSysLocale->GetCharClassPtr();
}
bool FormulaHelper::GetNextFunc( const OUString& rFormula,
bool bBack,
sal_Int32& rFStart, // Input and output
sal_Int32* pFEnd, // = NULL
const IFunctionDescription** ppFDesc, // = NULL
::std::vector< OUString>* pArgs ) const // = NULL
{
sal_Int32 nOldStart = rFStart;
OUString aFname;
rFStart = GetFunctionStart( rFormula, rFStart, bBack, ppFDesc ? &aFname : NULL );
bool bFound = ( rFStart != FUNC_NOTFOUND );
if ( bFound )
{
if ( pFEnd )
*pFEnd = GetFunctionEnd( rFormula, rFStart );
if ( ppFDesc )
{
*ppFDesc = NULL;
const OUString sTemp( aFname );
const sal_uInt32 nCategoryCount = m_pFunctionManager->getCount();
for(sal_uInt32 j= 0; j < nCategoryCount && !*ppFDesc; ++j)
{
boost::scoped_ptr<const IFunctionCategory> pCategory(m_pFunctionManager->getCategory(j));
const sal_uInt32 nCount = pCategory->getCount();
for(sal_uInt32 i = 0 ; i < nCount; ++i)
{
const IFunctionDescription* pCurrent = pCategory->getFunction(i);
if ( pCurrent->getFunctionName().equalsIgnoreAsciiCase(sTemp) )
{
*ppFDesc = pCurrent;
break;
}
}// for(sal_uInt32 i = 0 ; i < nCount; ++i)
}
if ( *ppFDesc && pArgs )
{
GetArgStrings( *pArgs,rFormula, rFStart, static_cast<sal_uInt16>((*ppFDesc)->getParameterCount() ));
}
else
{
static OEmptyFunctionDescription s_aFunctionDescription;
*ppFDesc = &s_aFunctionDescription;
}
}
}
else
rFStart = nOldStart;
return bFound;
}
void FormulaHelper::FillArgStrings( const OUString& rFormula,
sal_Int32 nFuncPos,
sal_uInt16 nArgs,
::std::vector< OUString >& _rArgs ) const
{
sal_Int32 nStart = 0;
sal_Int32 nEnd = 0;
sal_uInt16 i;
bool bLast = false;
for ( i=0; i<nArgs && !bLast; i++ )
{
nStart = GetArgStart( rFormula, nFuncPos, i );
if ( i+1<nArgs ) // last argument?
{
nEnd = GetArgStart( rFormula, nFuncPos, i+1 );
if ( nEnd != nStart )
_rArgs.push_back(rFormula.copy( nStart, nEnd-1-nStart ));
else
_rArgs.push_back(OUString()), bLast = true;
}
else
{
nEnd = GetFunctionEnd( rFormula, nFuncPos )-1;
if ( nStart < nEnd )
_rArgs.push_back( rFormula.copy( nStart, nEnd-nStart ) );
else
_rArgs.push_back(OUString());
}
}
if ( bLast )
for ( ; i<nArgs; i++ )
_rArgs.push_back(OUString());
}
void FormulaHelper::GetArgStrings( ::std::vector< OUString >& _rArgs,
const OUString& rFormula,
sal_Int32 nFuncPos,
sal_uInt16 nArgs ) const
{
if (nArgs)
{
FillArgStrings( rFormula, nFuncPos, nArgs, _rArgs );
}
}
inline bool IsFormulaText( const CharClass* _pCharClass,const OUString& rStr, sal_Int32 nPos )
{
if( _pCharClass->isLetterNumeric( rStr, nPos ) )
return true;
else
{ // In internationalized versions function names may contain a dot
// and in every version also an underscore... ;-)
sal_Unicode c = rStr[nPos];
return c == '.' || c == '_';
}
}
sal_Int32 FormulaHelper::GetFunctionStart( const OUString& rFormula,
sal_Int32 nStart,
bool bBack,
OUString* pFuncName ) const
{
sal_Int32 nStrLen = rFormula.getLength();
if ( nStrLen < nStart )
return nStart;
sal_Int32 nFStart = FUNC_NOTFOUND;
sal_Int32 nParPos = bBack ? ::std::min( nStart, nStrLen - 1) : nStart;
bool bRepeat;
do
{
bool bFound = false;
bRepeat = false;
if ( bBack )
{
while ( !bFound && (nParPos > 0) )
{
if ( rFormula[nParPos] == '"' )
{
nParPos--;
while ( (nParPos > 0) && rFormula[nParPos] != '"' )
nParPos--;
if (nParPos > 0)
nParPos--;
}
else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
nParPos--;
}
}
else
{
while ( !bFound && (nParPos < nStrLen) )
{
if ( rFormula[nParPos] == '"' )
{
nParPos++;
while ( (nParPos < nStrLen) && rFormula[nParPos] != '"' )
nParPos++;
nParPos++;
}
else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
nParPos++;
}
}
if ( bFound && (nParPos > 0) )
{
nFStart = nParPos-1;
while ( (nFStart > 0) && IsFormulaText(m_pCharClass, rFormula, nFStart ))
nFStart--;
}
nFStart++;
if ( bFound )
{
if ( IsFormulaText( m_pCharClass,rFormula, nFStart ) )
{
// Function found
if ( pFuncName )
*pFuncName = rFormula.copy( nFStart, nParPos-nFStart );
}
else // Brackets without function -> keep searching
{
bRepeat = true;
if ( !bBack )
nParPos++;
else if (nParPos > 0)
nParPos--;
else
bRepeat = false;
}
}
else // No brackets found
{
nFStart = FUNC_NOTFOUND;
if ( pFuncName )
pFuncName->clear();
}
}
while(bRepeat);
return nFStart;
}
sal_Int32 FormulaHelper::GetFunctionEnd( const OUString& rStr, sal_Int32 nStart ) const
{
sal_Int32 nStrLen = rStr.getLength();
if ( nStrLen < nStart )
return nStart;
short nParCount = 0;
bool bInArray = false;
bool bFound = false;
while ( !bFound && (nStart < nStrLen) )
{
sal_Unicode c = rStr[nStart];
if ( c == '"' )
{
nStart++;
while ( (nStart < nStrLen) && rStr[nStart] != '"' )
nStart++;
}
else if ( c == open )
nParCount++;
else if ( c == close )
{
nParCount--;
if ( nParCount == 0 )
bFound = true;
else if ( nParCount < 0 )
{
bFound = true;
nStart--; // read one too far
}
}
else if ( c == arrayOpen )
{
bInArray = true;
}
else if ( c == arrayClose )
{
bInArray = false;
}
else if ( c == sep )
{
if ( !bInArray && nParCount == 0 )
{
bFound = true;
nStart--; // read one too far
}
}
nStart++; // Set behind found position
}
return nStart;
}
sal_Int32 FormulaHelper::GetArgStart( const OUString& rStr, sal_Int32 nStart, sal_uInt16 nArg ) const
{
sal_Int32 nStrLen = rStr.getLength();
if ( nStrLen < nStart )
return nStart;
short nParCount = 0;
bool bInArray = false;
bool bFound = false;
while ( !bFound && (nStart < nStrLen) )
{
sal_Unicode c = rStr[nStart];
if ( c == '"' )
{
nStart++;
while ( (nStart < nStrLen) && rStr[nStart] != '"' )
nStart++;
}
else if ( c == open )
{
bFound = ( nArg == 0 );
nParCount++;
}
else if ( c == close )
{
nParCount--;
bFound = ( nParCount == 0 );
}
else if ( c == arrayOpen )
{
bInArray = true;
}
else if ( c == arrayClose )
{
bInArray = false;
}
else if ( c == sep )
{
if ( !bInArray && nParCount == 1 )
{
nArg--;
bFound = ( nArg == 0 );
}
}
nStart++;
}
return nStart;
}
} // formula
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>most likely formulas won't be longer than 64k characters, but...<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <algorithm>
#include "formula/formulahelper.hxx"
#include <unotools/charclass.hxx>
#include <unotools/syslocale.hxx>
#include <boost/scoped_ptr.hpp>
namespace formula
{
namespace
{
class OEmptyFunctionDescription : public IFunctionDescription
{
public:
OEmptyFunctionDescription(){}
virtual ~OEmptyFunctionDescription(){}
virtual OUString getFunctionName() const SAL_OVERRIDE { return OUString(); }
virtual const IFunctionCategory* getCategory() const SAL_OVERRIDE { return NULL; }
virtual OUString getDescription() const SAL_OVERRIDE { return OUString(); }
virtual sal_Int32 getSuppressedArgumentCount() const SAL_OVERRIDE { return 0; }
virtual OUString getFormula(const ::std::vector< OUString >& ) const SAL_OVERRIDE { return OUString(); }
virtual void fillVisibleArgumentMapping(::std::vector<sal_uInt16>& ) const SAL_OVERRIDE {}
virtual void initArgumentInfo() const SAL_OVERRIDE {}
virtual OUString getSignature() const SAL_OVERRIDE { return OUString(); }
virtual OString getHelpId() const SAL_OVERRIDE { return ""; }
virtual sal_uInt32 getParameterCount() const SAL_OVERRIDE { return 0; }
virtual OUString getParameterName(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
virtual OUString getParameterDescription(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
virtual bool isParameterOptional(sal_uInt32 ) const SAL_OVERRIDE { return false; }
};
}
// class FormulaHelper - static Method
#define FUNC_NOTFOUND -1
FormulaHelper::FormulaHelper(const IFunctionManager* _pFunctionManager)
:m_pSysLocale(new SvtSysLocale)
,m_pFunctionManager(_pFunctionManager)
,open(_pFunctionManager->getSingleToken(IFunctionManager::eOk))
,close(_pFunctionManager->getSingleToken(IFunctionManager::eClose))
,sep(_pFunctionManager->getSingleToken(IFunctionManager::eSep))
,arrayOpen(_pFunctionManager->getSingleToken(IFunctionManager::eArrayOpen))
,arrayClose(_pFunctionManager->getSingleToken(IFunctionManager::eArrayClose))
{
m_pCharClass = m_pSysLocale->GetCharClassPtr();
}
bool FormulaHelper::GetNextFunc( const OUString& rFormula,
bool bBack,
sal_Int32& rFStart, // Input and output
sal_Int32* pFEnd, // = NULL
const IFunctionDescription** ppFDesc, // = NULL
::std::vector< OUString>* pArgs ) const // = NULL
{
sal_Int32 nOldStart = rFStart;
OUString aFname;
rFStart = GetFunctionStart( rFormula, rFStart, bBack, ppFDesc ? &aFname : NULL );
bool bFound = ( rFStart != FUNC_NOTFOUND );
if ( bFound )
{
if ( pFEnd )
*pFEnd = GetFunctionEnd( rFormula, rFStart );
if ( ppFDesc )
{
*ppFDesc = NULL;
const OUString sTemp( aFname );
const sal_uInt32 nCategoryCount = m_pFunctionManager->getCount();
for(sal_uInt32 j= 0; j < nCategoryCount && !*ppFDesc; ++j)
{
boost::scoped_ptr<const IFunctionCategory> pCategory(m_pFunctionManager->getCategory(j));
const sal_uInt32 nCount = pCategory->getCount();
for(sal_uInt32 i = 0 ; i < nCount; ++i)
{
const IFunctionDescription* pCurrent = pCategory->getFunction(i);
if ( pCurrent->getFunctionName().equalsIgnoreAsciiCase(sTemp) )
{
*ppFDesc = pCurrent;
break;
}
}// for(sal_uInt32 i = 0 ; i < nCount; ++i)
}
if ( *ppFDesc && pArgs )
{
GetArgStrings( *pArgs,rFormula, rFStart, static_cast<sal_uInt16>((*ppFDesc)->getParameterCount() ));
}
else
{
static OEmptyFunctionDescription s_aFunctionDescription;
*ppFDesc = &s_aFunctionDescription;
}
}
}
else
rFStart = nOldStart;
return bFound;
}
void FormulaHelper::FillArgStrings( const OUString& rFormula,
sal_Int32 nFuncPos,
sal_uInt16 nArgs,
::std::vector< OUString >& _rArgs ) const
{
sal_Int32 nStart = 0;
sal_Int32 nEnd = 0;
sal_uInt16 i;
bool bLast = false;
for ( i=0; i<nArgs && !bLast; i++ )
{
nStart = GetArgStart( rFormula, nFuncPos, i );
if ( i+1<nArgs ) // last argument?
{
nEnd = GetArgStart( rFormula, nFuncPos, i+1 );
if ( nEnd != nStart )
_rArgs.push_back(rFormula.copy( nStart, nEnd-1-nStart ));
else
_rArgs.push_back(OUString()), bLast = true;
}
else
{
nEnd = GetFunctionEnd( rFormula, nFuncPos )-1;
if ( nStart < nEnd )
_rArgs.push_back( rFormula.copy( nStart, nEnd-nStart ) );
else
_rArgs.push_back(OUString());
}
}
if ( bLast )
for ( ; i<nArgs; i++ )
_rArgs.push_back(OUString());
}
void FormulaHelper::GetArgStrings( ::std::vector< OUString >& _rArgs,
const OUString& rFormula,
sal_Int32 nFuncPos,
sal_uInt16 nArgs ) const
{
if (nArgs)
{
FillArgStrings( rFormula, nFuncPos, nArgs, _rArgs );
}
}
inline bool IsFormulaText( const CharClass* _pCharClass,const OUString& rStr, sal_Int32 nPos )
{
if( _pCharClass->isLetterNumeric( rStr, nPos ) )
return true;
else
{ // In internationalized versions function names may contain a dot
// and in every version also an underscore... ;-)
sal_Unicode c = rStr[nPos];
return c == '.' || c == '_';
}
}
sal_Int32 FormulaHelper::GetFunctionStart( const OUString& rFormula,
sal_Int32 nStart,
bool bBack,
OUString* pFuncName ) const
{
sal_Int32 nStrLen = rFormula.getLength();
if ( nStrLen < nStart )
return nStart;
sal_Int32 nFStart = FUNC_NOTFOUND;
sal_Int32 nParPos = bBack ? ::std::min( nStart, nStrLen - 1) : nStart;
bool bRepeat;
do
{
bool bFound = false;
bRepeat = false;
if ( bBack )
{
while ( !bFound && (nParPos > 0) )
{
if ( rFormula[nParPos] == '"' )
{
nParPos--;
while ( (nParPos > 0) && rFormula[nParPos] != '"' )
nParPos--;
if (nParPos > 0)
nParPos--;
}
else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
nParPos--;
}
}
else
{
while ( !bFound && (nParPos < nStrLen) )
{
if ( rFormula[nParPos] == '"' )
{
nParPos++;
while ( (nParPos < nStrLen) && rFormula[nParPos] != '"' )
nParPos++;
nParPos++;
}
else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
nParPos++;
}
}
if ( bFound && (nParPos > 0) )
{
nFStart = nParPos-1;
while ( (nFStart > 0) && IsFormulaText(m_pCharClass, rFormula, nFStart ))
nFStart--;
}
nFStart++;
if ( bFound )
{
if ( IsFormulaText( m_pCharClass,rFormula, nFStart ) )
{
// Function found
if ( pFuncName )
*pFuncName = rFormula.copy( nFStart, nParPos-nFStart );
}
else // Brackets without function -> keep searching
{
bRepeat = true;
if ( !bBack )
nParPos++;
else if (nParPos > 0)
nParPos--;
else
bRepeat = false;
}
}
else // No brackets found
{
nFStart = FUNC_NOTFOUND;
if ( pFuncName )
pFuncName->clear();
}
}
while(bRepeat);
return nFStart;
}
sal_Int32 FormulaHelper::GetFunctionEnd( const OUString& rStr, sal_Int32 nStart ) const
{
sal_Int32 nStrLen = rStr.getLength();
if ( nStrLen < nStart )
return nStart;
short nParCount = 0;
bool bInArray = false;
bool bFound = false;
while ( !bFound && (nStart < nStrLen) )
{
sal_Unicode c = rStr[nStart];
if ( c == '"' )
{
nStart++;
while ( (nStart < nStrLen) && rStr[nStart] != '"' )
nStart++;
}
else if ( c == open )
nParCount++;
else if ( c == close )
{
nParCount--;
if ( nParCount == 0 )
bFound = true;
else if ( nParCount < 0 )
{
bFound = true;
nStart--; // read one too far
}
}
else if ( c == arrayOpen )
{
bInArray = true;
}
else if ( c == arrayClose )
{
bInArray = false;
}
else if ( c == sep )
{
if ( !bInArray && nParCount == 0 )
{
bFound = true;
nStart--; // read one too far
}
}
nStart++; // Set behind found position
}
return nStart;
}
sal_Int32 FormulaHelper::GetArgStart( const OUString& rStr, sal_Int32 nStart, sal_uInt16 nArg ) const
{
sal_Int32 nStrLen = rStr.getLength();
if ( nStrLen < nStart )
return nStart;
short nParCount = 0;
bool bInArray = false;
bool bFound = false;
while ( !bFound && (nStart < nStrLen) )
{
sal_Unicode c = rStr[nStart];
if ( c == '"' )
{
nStart++;
while ( (nStart < nStrLen) && rStr[nStart] != '"' )
nStart++;
}
else if ( c == open )
{
bFound = ( nArg == 0 );
nParCount++;
}
else if ( c == close )
{
nParCount--;
bFound = ( nParCount == 0 );
}
else if ( c == arrayOpen )
{
bInArray = true;
}
else if ( c == arrayClose )
{
bInArray = false;
}
else if ( c == sep )
{
if ( !bInArray && nParCount == 1 )
{
nArg--;
bFound = ( nArg == 0 );
}
}
nStart++;
}
return nStart;
}
} // formula
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2013 Intel Corporation. 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.h"
#include <string>
#include "base/files/file_enumerator.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/site_instance.h"
#include "net/base/net_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/warp_handler.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_ui_delegate.h"
#include "xwalk/runtime/browser/xwalk_browser_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#if defined(OS_TIZEN)
#include "xwalk/application/browser/application_tizen.h"
#endif
using content::RenderProcessHost;
namespace xwalk {
namespace keys = application_manifest_keys;
namespace widget_keys = application_widget_keys;
namespace {
const char* kDefaultWidgetEntryPage[] = {
"index.html",
"index.htm",
"index.svg",
"index.xhtml",
"index.xht"};
GURL GetDefaultWidgetEntryPage(
scoped_refptr<xwalk::application::ApplicationData> data) {
base::ThreadRestrictions::SetIOAllowed(true);
base::FileEnumerator iter(
data->path(), true,
base::FileEnumerator::FILES,
FILE_PATH_LITERAL("index.*"));
size_t priority = arraysize(kDefaultWidgetEntryPage);
std::string source;
for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
i < priority) {
source = kDefaultWidgetEntryPage[i];
priority = i;
}
}
}
return source.empty() ? GURL() : data->GetResourceURL(source);
}
} // namespace
namespace application {
scoped_ptr<Application> Application::Create(
scoped_refptr<ApplicationData> data,
XWalkBrowserContext* context) {
#if defined(OS_TIZEN)
return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
#else
return make_scoped_ptr(new Application(data, context));
#endif
}
Application::Application(
scoped_refptr<ApplicationData> data,
XWalkBrowserContext* browser_context)
: data_(data),
render_process_host_(NULL),
web_contents_(NULL),
security_mode_enabled_(false),
browser_context_(browser_context),
observer_(NULL),
remote_debugging_enabled_(false),
weak_factory_(this) {
DCHECK(browser_context_);
DCHECK(data_.get());
}
Application::~Application() {
Terminate();
if (render_process_host_)
render_process_host_->RemoveObserver(this);
}
template<>
GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
#if defined(OS_TIZEN)
if (data_->IsHostedApp()) {
std::string source;
GURL url;
if (data_->GetManifest()->GetString(
widget_keys::kLaunchLocalPathKey, &source)) {
url = GURL(source);
}
if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
return url;
}
#endif
GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
if (url.is_valid())
return url;
LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
<< "trying to find default entry page.";
url = GetDefaultWidgetEntryPage(data_);
if (url.is_valid())
return url;
LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
return GURL();
}
template<>
GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
if (data_->IsHostedApp()) {
std::string source;
// Not trying to get a relative path for the "fake" application.
if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
return GURL(source);
return GURL();
}
GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
if (url.is_valid())
return url;
url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
if (url.is_valid())
return url;
url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
if (url.is_valid()) {
LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
<< "' found. Please migrate to using '" << keys::kStartURLKey
<< "' instead.";
return url;
}
LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
return GURL();
}
template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
const LaunchParams& params) {
if (params.force_fullscreen)
return ui::SHOW_STATE_FULLSCREEN;
const Manifest* manifest = data_->GetManifest();
std::string view_modes_string;
if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
// FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
// If the first user prefererence is 'fullscreen', set window show state
// FULLSCREEN, otherwise set the default window show state.
std::vector<std::string> modes;
base::SplitString(view_modes_string, ' ', &modes);
if (!modes.empty() && modes[0] == "fullscreen")
return ui::SHOW_STATE_FULLSCREEN;
}
return ui::SHOW_STATE_DEFAULT;
}
template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
const LaunchParams& params) {
if (params.force_fullscreen)
return ui::SHOW_STATE_FULLSCREEN;
const Manifest* manifest = data_->GetManifest();
std::string display_string;
if (manifest->GetString(keys::kDisplay, &display_string)) {
// FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
// values are supported.
if (display_string.find("fullscreen") != std::string::npos)
return ui::SHOW_STATE_FULLSCREEN;
}
return ui::SHOW_STATE_DEFAULT;
}
bool Application::Launch(const LaunchParams& launch_params) {
if (!runtimes_.empty()) {
LOG(ERROR) << "Attempt to launch app with id " << id()
<< ", but it is already running.";
return false;
}
CHECK(!render_process_host_);
bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
GetStartURL<Manifest::TYPE_MANIFEST>();
if (!url.is_valid())
return false;
remote_debugging_enabled_ = launch_params.remote_debugging;
auto site = content::SiteInstance::CreateForURL(browser_context_, url);
Runtime* runtime = Runtime::Create(browser_context_, site);
runtime->set_observer(this);
runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
runtimes_.push_back(runtime);
render_process_host_ = runtime->GetRenderProcessHost();
render_process_host_->AddObserver(this);
web_contents_ = runtime->web_contents();
InitSecurityPolicy();
runtime->LoadURL(url);
NativeAppWindow::CreateParams params;
params.net_wm_pid = launch_params.launcher_pid;
params.state = is_wgt ?
GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params) :
GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);
window_show_params_ = params;
// Only the first runtime can have a launch screen.
params.splash_screen_path = GetSplashScreenPath();
runtime->set_ui_delegate(DefaultRuntimeUIDelegate::Create(runtime, params));
// We call "Show" after RP is initialized to reduce
// the application start up time.
return true;
}
GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
const Manifest* manifest = data_->GetManifest();
std::string source;
if (!manifest->GetString(key, &source) || source.empty())
return GURL();
return data_->GetResourceURL(source);
}
void Application::Terminate() {
std::vector<Runtime*> to_be_closed(runtimes_.get());
for (Runtime* runtime : to_be_closed)
runtime->Close();
}
int Application::GetRenderProcessHostID() const {
DCHECK(render_process_host_);
return render_process_host_->GetID();
}
void Application::OnNewRuntimeAdded(Runtime* runtime) {
runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
runtime->set_observer(this);
runtime->set_ui_delegate(
DefaultRuntimeUIDelegate::Create(runtime, window_show_params_));
runtime->Show();
runtimes_.push_back(runtime);
}
void Application::OnRuntimeClosed(Runtime* runtime) {
auto found = std::find(runtimes_.begin(), runtimes_.end(), runtime);
CHECK(found != runtimes_.end());
LOG(INFO) << "Application::OnRuntimeClosed " << runtime;
runtimes_.erase(found);
if (runtimes_.empty())
base::MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(&Application::NotifyTermination,
weak_factory_.GetWeakPtr()));
}
void Application::RenderProcessExited(RenderProcessHost* host,
base::ProcessHandle,
base::TerminationStatus,
int) {
DCHECK(render_process_host_ == host);
VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
}
void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
DCHECK(render_process_host_ == host);
render_process_host_ = NULL;
web_contents_ = NULL;
}
void Application::NotifyTermination() {
CHECK(!render_process_host_);
if (observer_)
observer_->OnApplicationTerminated(this);
}
void Application::RenderChannelCreated() {
CHECK(!runtimes_.empty());
runtimes_.front()->Show();
}
bool Application::UseExtension(const std::string& extension_name) const {
// TODO(Bai): Tells whether the application contains the specified extension
return true;
}
bool Application::RegisterPermissions(const std::string& extension_name,
const std::string& perm_table) {
// TODO(Bai): Parse the permission table and fill in the name_perm_map_
// The perm_table format is a simple JSON string, like
// [{"permission_name":"echo","apis":["add","remove","get"]}]
scoped_ptr<base::Value> root;
root.reset(base::JSONReader().ReadToValue(perm_table));
if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
return false;
base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
if (permission_list->GetSize() == 0)
return false;
for (base::ListValue::const_iterator iter = permission_list->begin();
iter != permission_list->end(); ++iter) {
if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
return false;
base::DictionaryValue* dict_val =
static_cast<base::DictionaryValue*>(*iter);
std::string permission_name;
if (!dict_val->GetString("permission_name", &permission_name))
return false;
base::ListValue* api_list = NULL;
if (!dict_val->GetList("apis", &api_list))
return false;
for (base::ListValue::const_iterator api_iter = api_list->begin();
api_iter != api_list->end(); ++api_iter) {
std::string api;
if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
&& (*api_iter)->GetAsString(&api)))
return false;
// register the permission and api
name_perm_map_[api] = permission_name;
DLOG(INFO) << "Permission Registered [PERM] " << permission_name
<< " [API] " << api;
}
}
return true;
}
std::string Application::GetRegisteredPermissionName(
const std::string& extension_name,
const std::string& api_name) const {
std::map<std::string, std::string>::const_iterator iter =
name_perm_map_.find(api_name);
if (iter == name_perm_map_.end())
return std::string("");
return iter->second;
}
StoredPermission Application::GetPermission(PermissionType type,
const std::string& permission_name) const {
if (type == SESSION_PERMISSION) {
StoredPermissionMap::const_iterator iter =
permission_map_.find(permission_name);
if (iter == permission_map_.end())
return UNDEFINED_STORED_PERM;
return iter->second;
}
if (type == PERSISTENT_PERMISSION) {
return data_->GetPermission(permission_name);
}
NOTREACHED();
return UNDEFINED_STORED_PERM;
}
bool Application::SetPermission(PermissionType type,
const std::string& permission_name,
StoredPermission perm) {
if (type == SESSION_PERMISSION) {
permission_map_[permission_name] = perm;
return true;
}
if (type == PERSISTENT_PERMISSION)
return data_->SetPermission(permission_name, perm);
NOTREACHED();
return false;
}
void Application::InitSecurityPolicy() {
// CSP policy takes precedence over WARP.
if (data_->HasCSPDefined())
security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
security_policy_.reset(new ApplicationSecurityPolicyWARP(this));
if (security_policy_)
security_policy_->Enforce();
}
bool Application::CanRequestURL(const GURL& url) const {
if (security_policy_)
return security_policy_->IsAccessAllowed(url);
return true;
}
base::FilePath Application::GetSplashScreenPath() {
return base::FilePath();
}
} // namespace application
} // namespace xwalk
<commit_msg>Speed up GetDefaultWidgetEntryPage function<commit_after>// Copyright (c) 2013 Intel Corporation. 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.h"
#include <string>
#include "base/files/file_enumerator.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/site_instance.h"
#include "net/base/net_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/warp_handler.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_ui_delegate.h"
#include "xwalk/runtime/browser/xwalk_browser_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#if defined(OS_TIZEN)
#include "xwalk/application/browser/application_tizen.h"
#endif
using content::RenderProcessHost;
namespace xwalk {
namespace keys = application_manifest_keys;
namespace widget_keys = application_widget_keys;
namespace {
const char* kDefaultWidgetEntryPage[] = {
"index.html",
"index.htm",
"index.svg",
"index.xhtml",
"index.xht"};
GURL GetDefaultWidgetEntryPage(
scoped_refptr<xwalk::application::ApplicationData> data) {
base::ThreadRestrictions::SetIOAllowed(true);
base::FileEnumerator iter(
data->path(), true,
base::FileEnumerator::FILES,
FILE_PATH_LITERAL("index.*"));
size_t priority = arraysize(kDefaultWidgetEntryPage);
std::string source;
for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
for (size_t i = 0; i < priority; ++i) {
if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i]) {
source = kDefaultWidgetEntryPage[i];
priority = i;
break;
}
}
if (!priority)
break;
}
return source.empty() ? GURL() : data->GetResourceURL(source);
}
} // namespace
namespace application {
scoped_ptr<Application> Application::Create(
scoped_refptr<ApplicationData> data,
XWalkBrowserContext* context) {
#if defined(OS_TIZEN)
return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
#else
return make_scoped_ptr(new Application(data, context));
#endif
}
Application::Application(
scoped_refptr<ApplicationData> data,
XWalkBrowserContext* browser_context)
: data_(data),
render_process_host_(NULL),
web_contents_(NULL),
security_mode_enabled_(false),
browser_context_(browser_context),
observer_(NULL),
remote_debugging_enabled_(false),
weak_factory_(this) {
DCHECK(browser_context_);
DCHECK(data_.get());
}
Application::~Application() {
Terminate();
if (render_process_host_)
render_process_host_->RemoveObserver(this);
}
template<>
GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
#if defined(OS_TIZEN)
if (data_->IsHostedApp()) {
std::string source;
GURL url;
if (data_->GetManifest()->GetString(
widget_keys::kLaunchLocalPathKey, &source)) {
url = GURL(source);
}
if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
return url;
}
#endif
GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
if (url.is_valid())
return url;
LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
<< "trying to find default entry page.";
url = GetDefaultWidgetEntryPage(data_);
if (url.is_valid())
return url;
LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
return GURL();
}
template<>
GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
if (data_->IsHostedApp()) {
std::string source;
// Not trying to get a relative path for the "fake" application.
if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
return GURL(source);
return GURL();
}
GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
if (url.is_valid())
return url;
url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
if (url.is_valid())
return url;
url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
if (url.is_valid()) {
LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
<< "' found. Please migrate to using '" << keys::kStartURLKey
<< "' instead.";
return url;
}
LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
return GURL();
}
template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
const LaunchParams& params) {
if (params.force_fullscreen)
return ui::SHOW_STATE_FULLSCREEN;
const Manifest* manifest = data_->GetManifest();
std::string view_modes_string;
if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
// FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
// If the first user prefererence is 'fullscreen', set window show state
// FULLSCREEN, otherwise set the default window show state.
std::vector<std::string> modes;
base::SplitString(view_modes_string, ' ', &modes);
if (!modes.empty() && modes[0] == "fullscreen")
return ui::SHOW_STATE_FULLSCREEN;
}
return ui::SHOW_STATE_DEFAULT;
}
template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
const LaunchParams& params) {
if (params.force_fullscreen)
return ui::SHOW_STATE_FULLSCREEN;
const Manifest* manifest = data_->GetManifest();
std::string display_string;
if (manifest->GetString(keys::kDisplay, &display_string)) {
// FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
// values are supported.
if (display_string.find("fullscreen") != std::string::npos)
return ui::SHOW_STATE_FULLSCREEN;
}
return ui::SHOW_STATE_DEFAULT;
}
bool Application::Launch(const LaunchParams& launch_params) {
if (!runtimes_.empty()) {
LOG(ERROR) << "Attempt to launch app with id " << id()
<< ", but it is already running.";
return false;
}
CHECK(!render_process_host_);
bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
GetStartURL<Manifest::TYPE_MANIFEST>();
if (!url.is_valid())
return false;
remote_debugging_enabled_ = launch_params.remote_debugging;
auto site = content::SiteInstance::CreateForURL(browser_context_, url);
Runtime* runtime = Runtime::Create(browser_context_, site);
runtime->set_observer(this);
runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
runtimes_.push_back(runtime);
render_process_host_ = runtime->GetRenderProcessHost();
render_process_host_->AddObserver(this);
web_contents_ = runtime->web_contents();
InitSecurityPolicy();
runtime->LoadURL(url);
NativeAppWindow::CreateParams params;
params.net_wm_pid = launch_params.launcher_pid;
params.state = is_wgt ?
GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params) :
GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);
window_show_params_ = params;
// Only the first runtime can have a launch screen.
params.splash_screen_path = GetSplashScreenPath();
runtime->set_ui_delegate(DefaultRuntimeUIDelegate::Create(runtime, params));
// We call "Show" after RP is initialized to reduce
// the application start up time.
return true;
}
GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
const Manifest* manifest = data_->GetManifest();
std::string source;
if (!manifest->GetString(key, &source) || source.empty())
return GURL();
return data_->GetResourceURL(source);
}
void Application::Terminate() {
std::vector<Runtime*> to_be_closed(runtimes_.get());
for (Runtime* runtime : to_be_closed)
runtime->Close();
}
int Application::GetRenderProcessHostID() const {
DCHECK(render_process_host_);
return render_process_host_->GetID();
}
void Application::OnNewRuntimeAdded(Runtime* runtime) {
runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
runtime->set_observer(this);
runtime->set_ui_delegate(
DefaultRuntimeUIDelegate::Create(runtime, window_show_params_));
runtime->Show();
runtimes_.push_back(runtime);
}
void Application::OnRuntimeClosed(Runtime* runtime) {
auto found = std::find(runtimes_.begin(), runtimes_.end(), runtime);
CHECK(found != runtimes_.end());
LOG(INFO) << "Application::OnRuntimeClosed " << runtime;
runtimes_.erase(found);
if (runtimes_.empty())
base::MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(&Application::NotifyTermination,
weak_factory_.GetWeakPtr()));
}
void Application::RenderProcessExited(RenderProcessHost* host,
base::ProcessHandle,
base::TerminationStatus,
int) {
DCHECK(render_process_host_ == host);
VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
}
void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
DCHECK(render_process_host_ == host);
render_process_host_ = NULL;
web_contents_ = NULL;
}
void Application::NotifyTermination() {
CHECK(!render_process_host_);
if (observer_)
observer_->OnApplicationTerminated(this);
}
void Application::RenderChannelCreated() {
CHECK(!runtimes_.empty());
runtimes_.front()->Show();
}
bool Application::UseExtension(const std::string& extension_name) const {
// TODO(Bai): Tells whether the application contains the specified extension
return true;
}
bool Application::RegisterPermissions(const std::string& extension_name,
const std::string& perm_table) {
// TODO(Bai): Parse the permission table and fill in the name_perm_map_
// The perm_table format is a simple JSON string, like
// [{"permission_name":"echo","apis":["add","remove","get"]}]
scoped_ptr<base::Value> root;
root.reset(base::JSONReader().ReadToValue(perm_table));
if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
return false;
base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
if (permission_list->GetSize() == 0)
return false;
for (base::ListValue::const_iterator iter = permission_list->begin();
iter != permission_list->end(); ++iter) {
if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
return false;
base::DictionaryValue* dict_val =
static_cast<base::DictionaryValue*>(*iter);
std::string permission_name;
if (!dict_val->GetString("permission_name", &permission_name))
return false;
base::ListValue* api_list = NULL;
if (!dict_val->GetList("apis", &api_list))
return false;
for (base::ListValue::const_iterator api_iter = api_list->begin();
api_iter != api_list->end(); ++api_iter) {
std::string api;
if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
&& (*api_iter)->GetAsString(&api)))
return false;
// register the permission and api
name_perm_map_[api] = permission_name;
DLOG(INFO) << "Permission Registered [PERM] " << permission_name
<< " [API] " << api;
}
}
return true;
}
std::string Application::GetRegisteredPermissionName(
const std::string& extension_name,
const std::string& api_name) const {
std::map<std::string, std::string>::const_iterator iter =
name_perm_map_.find(api_name);
if (iter == name_perm_map_.end())
return std::string();
return iter->second;
}
StoredPermission Application::GetPermission(PermissionType type,
const std::string& permission_name) const {
if (type == SESSION_PERMISSION) {
StoredPermissionMap::const_iterator iter =
permission_map_.find(permission_name);
if (iter == permission_map_.end())
return UNDEFINED_STORED_PERM;
return iter->second;
}
if (type == PERSISTENT_PERMISSION) {
return data_->GetPermission(permission_name);
}
NOTREACHED();
return UNDEFINED_STORED_PERM;
}
bool Application::SetPermission(PermissionType type,
const std::string& permission_name,
StoredPermission perm) {
if (type == SESSION_PERMISSION) {
permission_map_[permission_name] = perm;
return true;
}
if (type == PERSISTENT_PERMISSION)
return data_->SetPermission(permission_name, perm);
NOTREACHED();
return false;
}
void Application::InitSecurityPolicy() {
// CSP policy takes precedence over WARP.
if (data_->HasCSPDefined())
security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
security_policy_.reset(new ApplicationSecurityPolicyWARP(this));
if (security_policy_)
security_policy_->Enforce();
}
bool Application::CanRequestURL(const GURL& url) const {
if (security_policy_)
return security_policy_->IsAccessAllowed(url);
return true;
}
base::FilePath Application::GetSplashScreenPath() {
return base::FilePath();
}
} // namespace application
} // namespace xwalk
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: menuconfiguration.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:53:09 $
*
* 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 __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
#define __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#include <vcl/menu.hxx>
#include <vcl/toolbox.hxx>
#define BOOKMARK_NEWMENU ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_new" ))
#define BOOKMARK_WIZARDMENU ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_wizard" ))
#define ADDONS_POPUPMENU ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_addons_popup" ))
// Prepare for inclusion by framework and sfx
// Please consider that there is a corresponding define also in sfxsids.hrc!! (SID_SFX_START)/(SID_ADDONS)
#define FWK_SID_SFX_START 5000
#define FWK_SID_ADDONS (FWK_SID_SFX_START+1678)
#define FWK_SID_ADDONHELP (FWK_SID_SFX_START+1684)
const USHORT START_ITEMID_PICKLIST = 4500;
const USHORT END_ITEMID_PICKLIST = 4599;
const USHORT MAX_ITEMCOUNT_PICKLIST = 99; // difference between START_... & END_... for picklist / must be changed too, if these values are changed!
const USHORT START_ITEMID_WINDOWLIST = 4600;
const USHORT END_ITEMID_WINDOWLIST = 4699;
const USHORT ITEMID_ADDONLIST = FWK_SID_ADDONS;
const USHORT ITEMID_ADDONHELP = FWK_SID_ADDONHELP;
namespace framework
{
class MenuConfiguration
{
public:
struct Attributes
{
Attributes( const ::rtl::OUString& aFrame, const ::rtl::OUString& aImageIdStr ) :
aTargetFrame( aFrame ), aImageId( aImageIdStr ) {}
::rtl::OUString aTargetFrame;
::rtl::OUString aImageId;
};
MenuConfiguration(
// #110897#-1 use const when giving a uno reference by reference
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rServiceManager );
virtual ~MenuConfiguration();
::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > CreateMenuBarConfigurationFromXML(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
PopupMenu* CreateBookmarkMenu(
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
const ::rtl::OUString& aURL )
throw ( ::com::sun::star::lang::WrappedTargetException );
ToolBox* CreateToolBoxFromConfiguration(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
void StoreMenuBarConfigurationToXML( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rMenuBarConfiguration,
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
void StoreToolBox( ToolBox* pToolBox,
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
static BOOL IsPickListItemId( USHORT nId );
static BOOL IsWindowListItemId( USHORT nId );
private:
// #110897#-1 do not hold the uno reference by reference
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& m_rxServiceManager;
};
}
#endif // __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
<commit_msg>INTEGRATION: CWS chart2mst3 (1.4.16); FILE MERGED 2006/10/27 07:25:05 cd 1.4.16.1: #i65734# Support menu merging with non-sfx based application modules using provided dispatch providers<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: menuconfiguration.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-05-22 15:26:26 $
*
* 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 __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
#define __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#include <com/sun/star/frame/XDispatchProvider.hpp>
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#include <cppuhelper/weak.hxx>
#include <vcl/menu.hxx>
#include <vcl/toolbox.hxx>
#define BOOKMARK_NEWMENU ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_new" ))
#define BOOKMARK_WIZARDMENU ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_wizard" ))
#define ADDONS_POPUPMENU ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_addons_popup" ))
// Prepare for inclusion by framework and sfx
// Please consider that there is a corresponding define also in sfxsids.hrc!! (SID_SFX_START)/(SID_ADDONS)
#define FWK_SID_SFX_START 5000
#define FWK_SID_ADDONS (FWK_SID_SFX_START+1678)
#define FWK_SID_ADDONHELP (FWK_SID_SFX_START+1684)
const USHORT START_ITEMID_PICKLIST = 4500;
const USHORT END_ITEMID_PICKLIST = 4599;
const USHORT MAX_ITEMCOUNT_PICKLIST = 99; // difference between START_... & END_... for picklist / must be changed too, if these values are changed!
const USHORT START_ITEMID_WINDOWLIST = 4600;
const USHORT END_ITEMID_WINDOWLIST = 4699;
const USHORT ITEMID_ADDONLIST = FWK_SID_ADDONS;
const USHORT ITEMID_ADDONHELP = FWK_SID_ADDONHELP;
namespace framework
{
class MenuConfiguration
{
public:
struct Attributes
{
Attributes() {}
Attributes( const ::rtl::OUString& aFrame, const ::rtl::OUString& aImageIdStr ) :
aTargetFrame( aFrame ), aImageId( aImageIdStr ) {}
::rtl::OUString aTargetFrame;
::rtl::OUString aImageId;
::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XDispatchProvider > xDispatchProvider;
};
MenuConfiguration(
// #110897#-1 use const when giving a uno reference by reference
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rServiceManager );
virtual ~MenuConfiguration();
::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > CreateMenuBarConfigurationFromXML(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
PopupMenu* CreateBookmarkMenu(
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
const ::rtl::OUString& aURL )
throw ( ::com::sun::star::lang::WrappedTargetException );
ToolBox* CreateToolBoxFromConfiguration(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
void StoreMenuBarConfigurationToXML( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rMenuBarConfiguration,
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
void StoreToolBox( ToolBox* pToolBox,
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
throw ( ::com::sun::star::lang::WrappedTargetException );
static BOOL IsPickListItemId( USHORT nId );
static BOOL IsWindowListItemId( USHORT nId );
private:
// #110897#-1 do not hold the uno reference by reference
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& m_rxServiceManager;
};
}
#endif // __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
<|endoftext|> |
<commit_before>// SciTE - Scintilla based Text Editor
// LexBullant.cxx - lexer for Bullant
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
char s[100];
for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
s[i] = static_cast<char>(tolower(styler[start + i]));
s[i + 1] = '\0';
}
int lev= 0;
char chAttr = SCE_C_IDENTIFIER;
if (isdigit(s[0]) || (s[0] == '.')){
chAttr = SCE_C_NUMBER;
}
else {
if (keywords.InList(s)) {
chAttr = SCE_C_WORD;
/* if (strcmp(s, "end method") == 0 ||
strcmp(s, "end case") == 0 ||
strcmp(s, "end class") == 0 ||
strcmp(s, "end debug") == 0 ||
strcmp(s, "end test") == 0 ||
strcmp(s, "end if") == 0 ||
strcmp(s, "end lock") == 0 ||
strcmp(s, "end transaction") == 0 ||
strcmp(s, "end trap") == 0 ||
strcmp(s, "end until") == 0 ||
strcmp(s, "end while") == 0)
lev = -1;*/
if (strcmp(s, "end") == 0)
lev = -1;
else if (strcmp(s, "method") == 0 ||
strcmp(s, "case") == 0 ||
strcmp(s, "class") == 0 ||
strcmp(s, "debug") == 0 ||
strcmp(s, "test") == 0 ||
strcmp(s, "if") == 0 ||
strcmp(s, "lock") == 0 ||
strcmp(s, "transaction") == 0 ||
strcmp(s, "trap") == 0 ||
strcmp(s, "until") == 0 ||
strcmp(s, "while") == 0)
lev = 1;
}
}
styler.ColourTo(end, chAttr);
return lev;
}
static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
bool fold = styler.GetPropertyInt("fold") != 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
int state = initStyle;
if (state == SCE_C_STRINGEOL) // Does not leak onto next line
state = SCE_C_DEFAULT;
char chPrev = ' ';
char chNext = styler[startPos];
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
// int blockChange = 0;
styler.StartSegment(startPos);
int endFoundThisLine = 0;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
// Avoid triggering two times on Dos/Win
// End of line
endFoundThisLine = 0;
if (state == SCE_C_STRINGEOL) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
if (fold) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
levelPrev = levelCurrent;
}
visibleChars = 0;
/* int indentBlock = GetLineIndentation(lineCurrent);
if (blockChange==1){
lineCurrent++;
int pos=SetLineIndentation(lineCurrent, indentBlock + indentSize);
} else if (blockChange==-1) {
indentBlock -= indentSize;
if (indentBlock < 0)
indentBlock = 0;
SetLineIndentation(lineCurrent, indentBlock);
lineCurrent++;
}
blockChange=0;
*/ }
if (!isspace(ch))
visibleChars++;
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_C_DEFAULT) {
if (iswordstart(ch)) {
styler.ColourTo(i-1, state);
state = SCE_C_IDENTIFIER;
} else if (ch == '@' && chNext == 'o') {
if ((styler.SafeGetCharAt(i+2) =='f') && (styler.SafeGetCharAt(i+3) == 'f')) {
styler.ColourTo(i-1, state);
state = SCE_C_COMMENT;
}
} else if (ch == '#') {
styler.ColourTo(i-1, state);
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
styler.ColourTo(i-1, state);
state = SCE_C_STRING;
} else if (ch == '\'') {
styler.ColourTo(i-1, state);
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_C_OPERATOR);
}
} else if (state == SCE_C_IDENTIFIER) {
if (!iswordchar(ch)) {
int levelChange = classifyWordBullant(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_C_DEFAULT;
chNext = styler.SafeGetCharAt(i + 1);
if (ch == '#') {
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
state = SCE_C_STRING;
} else if (ch == '\'') {
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i, SCE_C_OPERATOR);
}
if (endFoundThisLine == 0)
levelCurrent+=levelChange;
if (levelChange == -1)
endFoundThisLine=1;
}
} else if (state == SCE_C_COMMENT) {
if (ch == '@' && chNext == 'o') {
if (styler.SafeGetCharAt(i+2) == 'n') {
styler.ColourTo(i+2, state);
state = SCE_C_DEFAULT;
i+=2;
}
}
} else if (state == SCE_C_COMMENTLINE) {
if (ch == '\r' || ch == '\n') {
endFoundThisLine = 0;
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if (chNext == '\r' || chNext == '\n') {
endFoundThisLine = 0;
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
}
} else if (state == SCE_C_CHARACTER) {
if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
endFoundThisLine = 0;
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
} else if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\'') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
chPrev = ch;
}
styler.ColourTo(lengthDoc - 1, state);
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
if (fold) {
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
}
LexerModule lmBullant(SCLEX_BULLANT, ColouriseBullantDoc, "bullant");
<commit_msg>Upgraded keyword list descriptions from Brian Quinlan.<commit_after>// SciTE - Scintilla based Text Editor
// LexBullant.cxx - lexer for Bullant
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
char s[100];
for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
s[i] = static_cast<char>(tolower(styler[start + i]));
s[i + 1] = '\0';
}
int lev= 0;
char chAttr = SCE_C_IDENTIFIER;
if (isdigit(s[0]) || (s[0] == '.')){
chAttr = SCE_C_NUMBER;
}
else {
if (keywords.InList(s)) {
chAttr = SCE_C_WORD;
if (strcmp(s, "end") == 0)
lev = -1;
else if (strcmp(s, "method") == 0 ||
strcmp(s, "case") == 0 ||
strcmp(s, "class") == 0 ||
strcmp(s, "debug") == 0 ||
strcmp(s, "test") == 0 ||
strcmp(s, "if") == 0 ||
strcmp(s, "lock") == 0 ||
strcmp(s, "transaction") == 0 ||
strcmp(s, "trap") == 0 ||
strcmp(s, "until") == 0 ||
strcmp(s, "while") == 0)
lev = 1;
}
}
styler.ColourTo(end, chAttr);
return lev;
}
static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
bool fold = styler.GetPropertyInt("fold") != 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
int state = initStyle;
if (state == SCE_C_STRINGEOL) // Does not leak onto next line
state = SCE_C_DEFAULT;
char chPrev = ' ';
char chNext = styler[startPos];
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
styler.StartSegment(startPos);
int endFoundThisLine = 0;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
// Avoid triggering two times on Dos/Win
// End of line
endFoundThisLine = 0;
if (state == SCE_C_STRINGEOL) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
if (fold) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
levelPrev = levelCurrent;
}
visibleChars = 0;
/* int indentBlock = GetLineIndentation(lineCurrent);
if (blockChange==1){
lineCurrent++;
int pos=SetLineIndentation(lineCurrent, indentBlock + indentSize);
} else if (blockChange==-1) {
indentBlock -= indentSize;
if (indentBlock < 0)
indentBlock = 0;
SetLineIndentation(lineCurrent, indentBlock);
lineCurrent++;
}
blockChange=0;
*/ }
if (!isspace(ch))
visibleChars++;
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_C_DEFAULT) {
if (iswordstart(ch)) {
styler.ColourTo(i-1, state);
state = SCE_C_IDENTIFIER;
} else if (ch == '@' && chNext == 'o') {
if ((styler.SafeGetCharAt(i+2) =='f') && (styler.SafeGetCharAt(i+3) == 'f')) {
styler.ColourTo(i-1, state);
state = SCE_C_COMMENT;
}
} else if (ch == '#') {
styler.ColourTo(i-1, state);
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
styler.ColourTo(i-1, state);
state = SCE_C_STRING;
} else if (ch == '\'') {
styler.ColourTo(i-1, state);
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_C_OPERATOR);
}
} else if (state == SCE_C_IDENTIFIER) {
if (!iswordchar(ch)) {
int levelChange = classifyWordBullant(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_C_DEFAULT;
chNext = styler.SafeGetCharAt(i + 1);
if (ch == '#') {
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
state = SCE_C_STRING;
} else if (ch == '\'') {
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i, SCE_C_OPERATOR);
}
if (endFoundThisLine == 0)
levelCurrent+=levelChange;
if (levelChange == -1)
endFoundThisLine=1;
}
} else if (state == SCE_C_COMMENT) {
if (ch == '@' && chNext == 'o') {
if (styler.SafeGetCharAt(i+2) == 'n') {
styler.ColourTo(i+2, state);
state = SCE_C_DEFAULT;
i+=2;
}
}
} else if (state == SCE_C_COMMENTLINE) {
if (ch == '\r' || ch == '\n') {
endFoundThisLine = 0;
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if (chNext == '\r' || chNext == '\n') {
endFoundThisLine = 0;
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
}
} else if (state == SCE_C_CHARACTER) {
if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
endFoundThisLine = 0;
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
} else if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\'') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
chPrev = ch;
}
styler.ColourTo(lengthDoc - 1, state);
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
if (fold) {
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
}
static const char * const bullantWordListDesc[] = {
"Keywords",
0
};
LexerModule lmBullant(SCLEX_BULLANT, ColouriseBullantDoc, "bullant", 0, bullantWordListDesc);
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/framework/executor.h"
#include <memory>
#include "paddle/framework/scope.h"
#include "paddle/platform/device_context.h"
namespace paddle {
namespace framework {
class LinearListView;
class GraphView;
// Immutable view of a ProgramDesc organized for efficient execution.
class ProgramDescView {
public:
virtual ~ProgramDescView() {}
virtual void Initialize(const ProgramDesc*) = 0;
static ProgramDescView* Create(bool is_linear);
};
class LinearListView : public ProgramDescView {
public:
void Initialize(const ProgramDesc*) override;
};
class GraphView : public ProgramDescView {
public:
void Initialize(const ProgramDesc*) override;
};
ProgramDescView* ProgramDescView::Create(bool is_linear) {
if (is_linear) {
return new LinearListView();
} else {
return new GraphView();
}
}
void LinearListView::Initialize(const ProgramDesc*) {
// get a LinearView of ProgramDesc
}
void GraphView::Initialize(const ProgramDesc*) {
// get a GraphView of ProgramDesc
}
class ExecutorImpl : public Executor {
public:
ExecutorImpl(Scope* scope, const platform::DeviceContext* ctx,
const ProgramDesc* pdesc, bool is_linear)
: scope_(scope),
device_context_(ctx),
program_desc_(pdesc),
view_(ProgramDescView::Create(is_linear)) {}
virtual ~ExecutorImpl() {
if (view_) delete view_;
}
void Run() override;
void Initialize();
private:
Scope* scope_;
const platform::DeviceContext* device_context_;
const ProgramDesc* program_desc_;
ProgramDescView* view_;
};
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
platform::CPUDeviceContext* GetCPUDeviceContext() {
static std::unique_ptr<platform::CPUDeviceContext> g_cpu_device_context =
make_unique<platform::CPUDeviceContext>(platform::CPUPlace());
return g_cpu_device_context.get();
}
#ifndef PADDLE_ONLY_CPU
platform::CUDADeviceContext* GetCUDADeviceContext() {
static std::unique_ptr<platform::CUDADeviceContext> g_cuda_device_context =
make_unique<platform::CUDADeviceContext>(platform::GPUPlace(0));
return g_cuda_device_context.get();
}
#endif
framework::Scope* GetScope() {
static std::unique_ptr<framework::Scope> g_scope =
make_unique<framework::Scope>();
return g_scope.get();
}
Executor* NewLocalExecutor(const platform::Place& place,
const ProgramDesc& pdesc, bool is_linear) {
platform::DeviceContext* device_context = nullptr;
if (platform::is_cpu_place(place)) {
device_context = GetCPUDeviceContext();
} else if (platform::is_gpu_place(place)) {
#ifndef PADDLE_ONLY_CPU
device_context = GetCUDADeviceContext();
}
#else
PADDLE_THROW("'GPUPlace' is not supported in CPU only device.");
}
#endif
return new ExecutorImpl(GetScope(), device_context, &pdesc, is_linear);
}
void ExecutorImpl::Run() {
// operators running
scope_->NewVar();
device_context_->Wait();
}
void ExecutorImpl::Initialize() {
// Initialize the ProgramDescView
view_->Initialize(program_desc_);
}
} // namespace framework
} // namespace paddle
<commit_msg>pass place to GetCUDADeviceContext<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/framework/executor.h"
#include <memory>
#include "paddle/framework/scope.h"
#include "paddle/platform/device_context.h"
namespace paddle {
namespace framework {
class LinearListView;
class GraphView;
// Immutable view of a ProgramDesc organized for efficient execution.
class ProgramDescView {
public:
virtual ~ProgramDescView() {}
virtual void Initialize(const ProgramDesc*) = 0;
static ProgramDescView* Create(bool is_linear);
};
class LinearListView : public ProgramDescView {
public:
void Initialize(const ProgramDesc*) override;
};
class GraphView : public ProgramDescView {
public:
void Initialize(const ProgramDesc*) override;
};
ProgramDescView* ProgramDescView::Create(bool is_linear) {
if (is_linear) {
return new LinearListView();
} else {
return new GraphView();
}
}
void LinearListView::Initialize(const ProgramDesc*) {
// get a LinearView of ProgramDesc
}
void GraphView::Initialize(const ProgramDesc*) {
// get a GraphView of ProgramDesc
}
class ExecutorImpl : public Executor {
public:
ExecutorImpl(Scope* scope, const platform::DeviceContext* ctx,
const ProgramDesc* pdesc, bool is_linear)
: scope_(scope),
device_context_(ctx),
program_desc_(pdesc),
view_(ProgramDescView::Create(is_linear)) {}
virtual ~ExecutorImpl() {
if (view_) delete view_;
}
void Run() override;
void Initialize();
private:
Scope* scope_;
const platform::DeviceContext* device_context_;
const ProgramDesc* program_desc_;
ProgramDescView* view_;
};
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
platform::CPUDeviceContext* GetCPUDeviceContext(platform::CPUPlace& place) {
static std::unique_ptr<platform::CPUDeviceContext> g_cpu_device_context =
make_unique<platform::CPUDeviceContext>(place);
return g_cpu_device_context.get();
}
#ifndef PADDLE_ONLY_CPU
platform::CUDADeviceContext* GetCUDADeviceContext(platform::GPUPlace& place) {
static std::unique_ptr<platform::CUDADeviceContext> g_cuda_device_context =
make_unique<platform::CUDADeviceContext>(place);
return g_cuda_device_context.get();
}
#endif
framework::Scope* GetScope() {
static std::unique_ptr<framework::Scope> g_scope =
make_unique<framework::Scope>();
return g_scope.get();
}
Executor* NewLocalExecutor(const platform::Place& place,
const ProgramDesc& pdesc, bool is_linear) {
platform::DeviceContext* device_context = nullptr;
if (platform::is_cpu_place(place)) {
auto cpu_place = boost::get<platform::CPUPlace>(place);
device_context = GetCPUDeviceContext(cpu_place);
} else if (platform::is_gpu_place(place)) {
#ifndef PADDLE_ONLY_CPU
auto gpu_place = boost::get<platform::GPUPlace>(place);
device_context = GetCUDADeviceContext(gpu_place);
}
#else
PADDLE_THROW("'GPUPlace' is not supported in CPU only device.");
}
#endif
return new ExecutorImpl(GetScope(), device_context, &pdesc, is_linear);
}
void ExecutorImpl::Run() {
// operators running
scope_->NewVar();
device_context_->Wait();
}
void ExecutorImpl::Initialize() {
// Initialize the ProgramDescView
view_->Initialize(program_desc_);
}
} // namespace framework
} // namespace paddle
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkGDCMImageIO.h"
#include <list>
#include <fstream>
int main(int ac, char* av[])
{
if(ac < 5)
{
std::cerr << "Usage: " << av[0] << " DicomImage OutputDicomImage OutputImage RescalDicomImage\n";
return EXIT_FAILURE;
}
typedef short InputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( av[1] );
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer gdcmImageIO = ImageIOType::New();
reader->SetImageIO( gdcmImageIO );
try
{
reader->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file reader " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
// Rewrite the image in DICOM format
//
typedef itk::ImageFileWriter< InputImageType > Writer1Type;
Writer1Type::Pointer writer1 = Writer1Type::New();
writer1->SetFileName( av[2] );
writer1->SetInput( reader->GetOutput() );
writer1->SetImageIO( gdcmImageIO );
try
{
writer1->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
// Rescale intensities and rewrite the image in another format
//
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
InputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< WriteImageType > Writer2Type;
Writer2Type::Pointer writer2 = Writer2Type::New();
writer2->SetFileName( av[3] );
rescaler->SetInput( reader->GetOutput() );
writer2->SetInput( rescaler->GetOutput() );
try
{
writer2->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
// Rewrite the image in DICOM format but using less bits per pixel
//
typedef itk::ImageFileWriter< WriteImageType > Writer3Type;
Writer3Type::Pointer writer3 = Writer3Type::New();
writer3->SetFileName( av[4] );
writer3->SetInput( rescaler->GetOutput() );
writer3->UseInputMetaDataDictionaryOff ();
writer3->SetImageIO( gdcmImageIO );
try
{
writer3->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
gdcmImageIO->Print(std::cout);
return EXIT_SUCCESS;
}
<commit_msg>ENH: more code coverage by exercising get methods<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkGDCMImageIO.h"
#include <list>
#include <fstream>
int main(int ac, char* av[])
{
if(ac < 5)
{
std::cerr << "Usage: " << av[0] << " DicomImage OutputDicomImage OutputImage RescalDicomImage\n";
return EXIT_FAILURE;
}
typedef short InputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer gdcmImageIO = ImageIOType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( av[1] );
reader->SetImageIO( gdcmImageIO );
try
{
reader->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file reader " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
// Exercise the get methods
std::cout << "InternalComponentType: "
<< gdcmImageIO->GetInternalComponentType() << std::endl;
std::cout << "RescaleSlope: "
<< gdcmImageIO->GetRescaleSlope() << std::endl;
std::cout << "RescaleIntercept: "
<< gdcmImageIO->GetRescaleIntercept() << std::endl;
std::cout << "UIDPrefix: "
<< gdcmImageIO->GetUIDPrefix() << std::endl;
std::cout << "StudyInstanceUID: "
<< gdcmImageIO->GetStudyInstanceUID() << std::endl;
std::cout << "SeriesInstanceUID: "
<< gdcmImageIO->GetSeriesInstanceUID() << std::endl;
std::cout << "FrameOfReferenceInstanceUID: "
<< gdcmImageIO->GetFrameOfReferenceInstanceUID() << std::endl;
std::cout << "KeepOriginalUID: "
<< gdcmImageIO->GetKeepOriginalUID() << std::endl;
std::cout << "LoadSequences: "
<< gdcmImageIO->GetLoadSequences() << std::endl;
std::cout << "LoadPrivateTags: "
<< gdcmImageIO->GetLoadPrivateTags() << std::endl;
std::cout << "CompressionType: "
<< gdcmImageIO->GetCompressionType() << std::endl;
// Rewrite the image in DICOM format
//
typedef itk::ImageFileWriter< InputImageType > Writer1Type;
Writer1Type::Pointer writer1 = Writer1Type::New();
writer1->SetFileName( av[2] );
writer1->SetInput( reader->GetOutput() );
writer1->SetImageIO( gdcmImageIO );
try
{
writer1->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
// Rescale intensities and rewrite the image in another format
//
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
InputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
rescaler->SetInput( reader->GetOutput() );
typedef itk::ImageFileWriter< WriteImageType > Writer2Type;
Writer2Type::Pointer writer2 = Writer2Type::New();
writer2->SetFileName( av[3] );
writer2->SetInput( rescaler->GetOutput() );
try
{
writer2->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
// Rewrite the image in DICOM format but using less bits per pixel
//
typedef itk::ImageFileWriter< WriteImageType > Writer3Type;
Writer3Type::Pointer writer3 = Writer3Type::New();
writer3->SetFileName( av[4] );
writer3->SetInput( rescaler->GetOutput() );
writer3->UseInputMetaDataDictionaryOff ();
writer3->SetImageIO( gdcmImageIO );
try
{
writer3->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
gdcmImageIO->Print( std::cout );
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkGDCMImageIO.h"
#include <list>
#include <fstream>
int main(int ac, char* av[])
{
if(ac < 5)
{
std::cerr << "Usage: " << av[0] << " DicomImage OutputDicomImage OutputImage RescalDicomImage\n";
return EXIT_FAILURE;
}
typedef short InputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( av[1] );
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer gdcmImageIO = ImageIOType::New();
reader->SetImageIO( gdcmImageIO );
try
{
reader->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file reader " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
// Rewrite the image in DICOM format
//
typedef itk::ImageFileWriter< InputImageType > Writer1Type;
Writer1Type::Pointer writer1 = Writer1Type::New();
writer1->SetFileName( av[2] );
writer1->SetInput( reader->GetOutput() );
writer1->SetImageIO( gdcmImageIO );
try
{
writer1->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
// Rescale intensities and rewrite the image in another format
//
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
InputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< WriteImageType > Writer2Type;
Writer2Type::Pointer writer2 = Writer2Type::New();
writer2->SetFileName( av[3] );
rescaler->SetInput( reader->GetOutput() );
writer2->SetInput( rescaler->GetOutput() );
try
{
writer2->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
// Rewrite the image in DICOM format but using less bits per pixel
//
typedef itk::ImageFileWriter< WriteImageType > Writer3Type;
Writer3Type::Pointer writer3 = Writer3Type::New();
writer3->SetFileName( av[4] );
writer3->SetInput( rescaler->GetOutput() );
itk::MetaDataDictionary &d = gdcmImageIO->GetMetaDataDictionary();
writer3->UseInputMetaDataDictionaryOff ();
writer3->SetImageIO( gdcmImageIO );
try
{
writer3->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>COMP: unused variable warning.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkGDCMImageIO.h"
#include <list>
#include <fstream>
int main(int ac, char* av[])
{
if(ac < 5)
{
std::cerr << "Usage: " << av[0] << " DicomImage OutputDicomImage OutputImage RescalDicomImage\n";
return EXIT_FAILURE;
}
typedef short InputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( av[1] );
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer gdcmImageIO = ImageIOType::New();
reader->SetImageIO( gdcmImageIO );
try
{
reader->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file reader " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
// Rewrite the image in DICOM format
//
typedef itk::ImageFileWriter< InputImageType > Writer1Type;
Writer1Type::Pointer writer1 = Writer1Type::New();
writer1->SetFileName( av[2] );
writer1->SetInput( reader->GetOutput() );
writer1->SetImageIO( gdcmImageIO );
try
{
writer1->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
// Rescale intensities and rewrite the image in another format
//
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
InputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< WriteImageType > Writer2Type;
Writer2Type::Pointer writer2 = Writer2Type::New();
writer2->SetFileName( av[3] );
rescaler->SetInput( reader->GetOutput() );
writer2->SetInput( rescaler->GetOutput() );
try
{
writer2->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
// Rewrite the image in DICOM format but using less bits per pixel
//
typedef itk::ImageFileWriter< WriteImageType > Writer3Type;
Writer3Type::Pointer writer3 = Writer3Type::New();
writer3->SetFileName( av[4] );
writer3->SetInput( rescaler->GetOutput() );
writer3->UseInputMetaDataDictionaryOff ();
writer3->SetImageIO( gdcmImageIO );
try
{
writer3->Update();
}
catch (itk::ExceptionObject & e)
{
std::cerr << "exception in file writer " << std::endl;
std::cerr << e.GetDescription() << std::endl;
std::cerr << e.GetLocation() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Points.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Points.hh"
#include "FPoints.hh"
#include "IdList.hh"
vlPoints::vlPoints()
{
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = 0.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
}
void vlPoints::GetPoint(int id, float x[3])
{
float *xp = this->GetPoint(id);
for (int i=0; i<3; i++) x[i] = xp[i];
}
// Description:
// Given a list of pt ids, return an array of point coordinates.
void vlPoints::GetPoints(vlIdList& ptId, vlFloatPoints& fp)
{
for (int i=0; i<ptId.GetNumberOfIds(); i++)
{
fp.InsertPoint(i,this->GetPoint(ptId.GetId(i)));
}
}
// Description:
// Determine (xmin,xmax, ymin,ymax, zmin,zmax) bounds of points.
void vlPoints::ComputeBounds()
{
int i, j;
float *x;
if ( this->GetMTime() > this->ComputeTime )
{
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = LARGE_FLOAT;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -LARGE_FLOAT;
for (i=0; i<this->GetNumberOfPoints(); i++)
{
x = this->GetPoint(i);
for (j=0; j<3; j++)
{
if ( x[j] < this->Bounds[2*j] ) this->Bounds[2*j] = x[j];
if ( x[j] > this->Bounds[2*j+1] ) this->Bounds[2*j+1] = x[j];
}
}
this->ComputeTime.Modified();
}
}
// Description:
// Return the bounds of the points.
float *vlPoints::GetBounds()
{
this->ComputeBounds();
return this->Bounds;
}
void vlPoints::PrintSelf(ostream& os, vlIndent indent)
{
float *bounds;
vlRefCount::PrintSelf(os,indent);
os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
bounds = this->GetBounds();
os << indent << "Bounds: \n";
os << indent << " Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n";
os << indent << " Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n";
os << indent << " Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n";
}
<commit_msg>ERR: Removed extraneous includes.<commit_after>/*=========================================================================
Program: Visualization Library
Module: Points.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Points.hh"
vlPoints::vlPoints()
{
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = 0.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
}
void vlPoints::GetPoint(int id, float x[3])
{
float *xp = this->GetPoint(id);
for (int i=0; i<3; i++) x[i] = xp[i];
}
// Description:
// Given a list of pt ids, return an array of point coordinates.
void vlPoints::GetPoints(vlIdList& ptId, vlFloatPoints& fp)
{
for (int i=0; i<ptId.GetNumberOfIds(); i++)
{
fp.InsertPoint(i,this->GetPoint(ptId.GetId(i)));
}
}
// Description:
// Determine (xmin,xmax, ymin,ymax, zmin,zmax) bounds of points.
void vlPoints::ComputeBounds()
{
int i, j;
float *x;
if ( this->GetMTime() > this->ComputeTime )
{
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = LARGE_FLOAT;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -LARGE_FLOAT;
for (i=0; i<this->GetNumberOfPoints(); i++)
{
x = this->GetPoint(i);
for (j=0; j<3; j++)
{
if ( x[j] < this->Bounds[2*j] ) this->Bounds[2*j] = x[j];
if ( x[j] > this->Bounds[2*j+1] ) this->Bounds[2*j+1] = x[j];
}
}
this->ComputeTime.Modified();
}
}
// Description:
// Return the bounds of the points.
float *vlPoints::GetBounds()
{
this->ComputeBounds();
return this->Bounds;
}
void vlPoints::PrintSelf(ostream& os, vlIndent indent)
{
float *bounds;
vlRefCount::PrintSelf(os,indent);
os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
bounds = this->GetBounds();
os << indent << "Bounds: \n";
os << indent << " Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n";
os << indent << " Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n";
os << indent << " Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n";
}
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include <cmath>
#include "QGCGeo.h"
// These defines are private
#define M_DEG_TO_RAD (M_PI / 180.0)
#define M_RAD_TO_DEG (180.0 / M_PI)
#define CONSTANTS_ONE_G 9.80665f /* m/s^2 */
#define CONSTANTS_AIR_DENSITY_SEA_LEVEL_15C 1.225f /* kg/m^3 */
#define CONSTANTS_AIR_GAS_CONST 287.1f /* J/(kg * K) */
#define CONSTANTS_ABSOLUTE_NULL_CELSIUS -273.15f /* °C */
#define CONSTANTS_RADIUS_OF_EARTH 6371000 /* meters (m) */
static const float epsilon = std::numeric_limits<double>::epsilon();
void convertGeoToEnu(QGeoCoordinate coord, QGeoCoordinate origin, double* x, double* y, double* z) {
double lat_rad = coord.latitude() * M_DEG_TO_RAD;
double lon_rad = coord.longitude() * M_DEG_TO_RAD;
double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD;
double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD;
double sin_lat = sin(lat_rad);
double cos_lat = cos(lat_rad);
double cos_d_lon = cos(lon_rad - ref_lon_rad);
double ref_sin_lat = sin(ref_lat_rad);
double ref_cos_lat = cos(ref_lat_rad);
double c = acos(ref_sin_lat * sin_lat + ref_cos_lat * cos_lat * cos_d_lon);
double k = (fabs(c) < epsilon) ? 1.0 : (c / sin(c));
*x = k * (ref_cos_lat * sin_lat - ref_sin_lat * cos_lat * cos_d_lon) * CONSTANTS_RADIUS_OF_EARTH;
*y = k * cos_lat * sin(lon_rad - ref_lon_rad) * CONSTANTS_RADIUS_OF_EARTH;
*z = coord.altitude() - origin.altitude();
}
void convertEnuToGeo(double x, double y, double z, QGeoCoordinate origin, QGeoCoordinate *coord) {
double x_rad = x / CONSTANTS_RADIUS_OF_EARTH;
double y_rad = y / CONSTANTS_RADIUS_OF_EARTH;
double c = sqrtf(x_rad * x_rad + y_rad * y_rad);
double sin_c = sin(c);
double cos_c = cos(c);
double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD;
double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD;
double ref_sin_lat = sin(ref_lat_rad);
double ref_cos_lat = cos(ref_lat_rad);
double lat_rad;
double lon_rad;
if (fabs(c) > epsilon) {
lat_rad = asin(cos_c * ref_sin_lat + (x_rad * sin_c * ref_cos_lat) / c);
lon_rad = (ref_lon_rad + atan2(y_rad * sin_c, c * ref_cos_lat * cos_c - x_rad * ref_sin_lat * sin_c));
} else {
lat_rad = ref_lat_rad;
lon_rad = ref_lon_rad;
}
coord->setLatitude(lat_rad * M_RAD_TO_DEG);
coord->setLongitude(lon_rad * M_RAD_TO_DEG);
coord->setAltitude(z + origin.altitude());
}
<commit_msg>Added <limits> include.<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include <cmath>
#include <limits>
#include "QGCGeo.h"
// These defines are private
#define M_DEG_TO_RAD (M_PI / 180.0)
#define M_RAD_TO_DEG (180.0 / M_PI)
#define CONSTANTS_ONE_G 9.80665f /* m/s^2 */
#define CONSTANTS_AIR_DENSITY_SEA_LEVEL_15C 1.225f /* kg/m^3 */
#define CONSTANTS_AIR_GAS_CONST 287.1f /* J/(kg * K) */
#define CONSTANTS_ABSOLUTE_NULL_CELSIUS -273.15f /* °C */
#define CONSTANTS_RADIUS_OF_EARTH 6371000 /* meters (m) */
static const float epsilon = std::numeric_limits<double>::epsilon();
void convertGeoToEnu(QGeoCoordinate coord, QGeoCoordinate origin, double* x, double* y, double* z) {
double lat_rad = coord.latitude() * M_DEG_TO_RAD;
double lon_rad = coord.longitude() * M_DEG_TO_RAD;
double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD;
double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD;
double sin_lat = sin(lat_rad);
double cos_lat = cos(lat_rad);
double cos_d_lon = cos(lon_rad - ref_lon_rad);
double ref_sin_lat = sin(ref_lat_rad);
double ref_cos_lat = cos(ref_lat_rad);
double c = acos(ref_sin_lat * sin_lat + ref_cos_lat * cos_lat * cos_d_lon);
double k = (fabs(c) < epsilon) ? 1.0 : (c / sin(c));
*x = k * (ref_cos_lat * sin_lat - ref_sin_lat * cos_lat * cos_d_lon) * CONSTANTS_RADIUS_OF_EARTH;
*y = k * cos_lat * sin(lon_rad - ref_lon_rad) * CONSTANTS_RADIUS_OF_EARTH;
*z = coord.altitude() - origin.altitude();
}
void convertEnuToGeo(double x, double y, double z, QGeoCoordinate origin, QGeoCoordinate *coord) {
double x_rad = x / CONSTANTS_RADIUS_OF_EARTH;
double y_rad = y / CONSTANTS_RADIUS_OF_EARTH;
double c = sqrtf(x_rad * x_rad + y_rad * y_rad);
double sin_c = sin(c);
double cos_c = cos(c);
double ref_lon_rad = origin.longitude() * M_DEG_TO_RAD;
double ref_lat_rad = origin.latitude() * M_DEG_TO_RAD;
double ref_sin_lat = sin(ref_lat_rad);
double ref_cos_lat = cos(ref_lat_rad);
double lat_rad;
double lon_rad;
if (fabs(c) > epsilon) {
lat_rad = asin(cos_c * ref_sin_lat + (x_rad * sin_c * ref_cos_lat) / c);
lon_rad = (ref_lon_rad + atan2(y_rad * sin_c, c * ref_cos_lat * cos_c - x_rad * ref_sin_lat * sin_c));
} else {
lat_rad = ref_lat_rad;
lon_rad = ref_lon_rad;
}
coord->setLatitude(lat_rad * M_RAD_TO_DEG);
coord->setLongitude(lon_rad * M_RAD_TO_DEG);
coord->setAltitude(z + origin.altitude());
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkAffineDataInteractor3D.h"
#include "mitkDispatcher.h"
#include "mitkInteractionConst.h" // TODO: refactor file
#include "mitkInteractionPositionEvent.h"
#include "mitkInternalEvent.h"
#include "mitkMouseMoveEvent.h"
#include "mitkRenderingManager.h"
#include "mitkRotationOperation.h"
#include "mitkSurface.h"
#include <mitkPointOperation.h>
#include <vtkCamera.h>
#include <vtkDataArray.h>
#include <vtkInteractorStyle.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkRenderWindowInteractor.h>
mitk::AffineDataInteractor3D::AffineDataInteractor3D()
{
m_OriginalGeometry = Geometry3D::New();
// Initialize vector arithmetic
m_ObjectNormal[0] = 0.0;
m_ObjectNormal[1] = 0.0;
m_ObjectNormal[2] = 1.0;
}
mitk::AffineDataInteractor3D::~AffineDataInteractor3D()
{
}
void mitk::AffineDataInteractor3D::ConnectActionsAndFunctions()
{
CONNECT_CONDITION("isOverObject", CheckOverObject);
CONNECT_FUNCTION("selectObject",SelectObject);
CONNECT_FUNCTION("deselectObject",DeselectObject);
CONNECT_FUNCTION("initTranslate",InitTranslate);
CONNECT_FUNCTION("initRotate",InitRotate);
CONNECT_FUNCTION("translateObject",TranslateObject);
CONNECT_FUNCTION("rotateObject",RotateObject);
}
/*
* Check whether the DataNode contains a pointset, if not create one and add it.
*/
void mitk::AffineDataInteractor3D::DataNodeChanged()
{
//if (GetDataNode().IsNotNull())
//{
// // find proper place for this command!
// // maybe when DN is created ?
// GetDataNode()->SetBoolProperty("show contour", true);
// PointSet* points = dynamic_cast<PointSet*>(GetDataNode()->GetData());
// if (points == NULL)
// {
// m_PointSet = PointSet::New();
// GetDataNode()->SetData(m_PointSet);
// }
// else
// {
// m_PointSet = points;
// }
// // load config file parameter: maximal number of points
// mitk::PropertyList::Pointer properties = GetAttributes();
// std::string strNumber;
// if (properties->GetStringProperty("MaxPoints", strNumber))
// {
// m_MaxNumberOfPoints = atoi(strNumber.c_str());
// }
//}
}
bool mitk::AffineDataInteractor3D::CheckOverObject(const InteractionEvent* interactionEvent)
{
////Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
////Re-enable VTK interactor (may have been disabled previously)
const InteractionPositionEvent* positionEvent = dynamic_cast<const InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
if(interactionEvent->GetSender()->PickObject( m_CurrentPickedDisplayPoint, m_CurrentPickedPoint ) == this->GetDataNode().GetPointer())
{
return true;
}
return false;
}
bool mitk::AffineDataInteractor3D::SelectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 0.0, 0.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe dependend on distance from picked point
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), 0.0 );
return true;
}
bool mitk::AffineDataInteractor3D::DeselectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 1.0, 1.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe as inactive
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), -1.0 );
return true;
}
bool mitk::AffineDataInteractor3D::InitTranslate(StateMachineAction*, InteractionEvent* interactionEvent)
{
////Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
//// Disable VTK interactor until MITK interaction has been completed
// if ( renderWindowInteractor != NULL )
// renderWindowInteractor->Disable();
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
m_InitialPickedPoint = m_CurrentPickedPoint;
m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Make deep copy of current Geometry3D of the plane
this->GetDataNode()->GetData()->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
m_OriginalGeometry = static_cast< Geometry3D * >(this->GetDataNode()->GetData()->GetGeometry( timeStep )->Clone().GetPointer() );
return true;
}
bool mitk::AffineDataInteractor3D::InitRotate(StateMachineAction*, InteractionEvent* interactionEvent)
{
////Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
//// Disable VTK interactor until MITK interaction has been completed
// if ( renderWindowInteractor != NULL )
// renderWindowInteractor->Disable();
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
m_InitialPickedPoint = m_CurrentPickedPoint;
m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Make deep copy of current Geometry3D of the plane
this->GetDataNode()->GetData()->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
m_OriginalGeometry = static_cast< Geometry3D * >(this->GetDataNode()->GetData()->GetGeometry( timeStep )->Clone().GetPointer() );
return true;
}
bool mitk::AffineDataInteractor3D::TranslateObject (StateMachineAction*, InteractionEvent* interactionEvent)
{
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
Vector3D interactionMove;
interactionMove[0] = m_CurrentPickedPoint[0] - m_InitialPickedPoint[0];
interactionMove[1] = m_CurrentPickedPoint[1] - m_InitialPickedPoint[1];
interactionMove[2] = m_CurrentPickedPoint[2] - m_InitialPickedPoint[2];
Point3D origin = m_OriginalGeometry->GetOrigin();
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// If data is an mitk::Surface, extract it
Surface::Pointer surface = dynamic_cast< Surface* >(this->GetDataNode()->GetData());
vtkPolyData* polyData = NULL;
if (surface.IsNotNull())
{
polyData = surface->GetVtkPolyData( timeStep );
// Extract surface normal from surface (if existent, otherwise use default)
vtkPointData* pointData = polyData->GetPointData();
if (pointData != NULL)
{
vtkDataArray* normal = polyData->GetPointData()->GetVectors( "planeNormal" );
if (normal != NULL)
{
m_ObjectNormal[0] = normal->GetComponent( 0, 0 );
m_ObjectNormal[1] = normal->GetComponent( 0, 1 );
m_ObjectNormal[2] = normal->GetComponent( 0, 2 );
}
}
}
Vector3D transformedObjectNormal;
this->GetDataNode()->GetData()->GetGeometry( timeStep )->IndexToWorld(
m_ObjectNormal, transformedObjectNormal );
this->GetDataNode()->GetData()->GetGeometry( timeStep )->SetOrigin(
origin + transformedObjectNormal * (interactionMove * transformedObjectNormal) );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
bool mitk::AffineDataInteractor3D::RotateObject (StateMachineAction*, InteractionEvent* interactionEvent)
{
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
vtkCamera* camera = NULL;
vtkRenderer *currentVtkRenderer = NULL;
if ((interactionEvent->GetSender()) != NULL)
{
vtkRenderWindow* renderWindow = interactionEvent->GetSender()->GetRenderWindow();
if ( renderWindow != NULL )
{
vtkRenderWindowInteractor* renderWindowInteractor = renderWindow->GetInteractor();
if ( renderWindowInteractor != NULL )
{
currentVtkRenderer = renderWindowInteractor->GetInteractorStyle()->GetCurrentRenderer();
if ( currentVtkRenderer != NULL )
camera = currentVtkRenderer->GetActiveCamera();
}
}
}
if ( camera )
{
vtkFloatingPointType vpn[3];
camera->GetViewPlaneNormal( vpn );
Vector3D viewPlaneNormal;
viewPlaneNormal[0] = vpn[0];
viewPlaneNormal[1] = vpn[1];
viewPlaneNormal[2] = vpn[2];
Vector3D interactionMove;
interactionMove[0] = m_CurrentPickedPoint[0] - m_InitialPickedPoint[0];
interactionMove[1] = m_CurrentPickedPoint[1] - m_InitialPickedPoint[1];
interactionMove[2] = m_CurrentPickedPoint[2] - m_InitialPickedPoint[2];
if (interactionMove[0]==0 && interactionMove[1]==0 && interactionMove[2]==0)
return true;
Vector3D rotationAxis = itk::CrossProduct( viewPlaneNormal, interactionMove );
rotationAxis.Normalize();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
int *size = currentVtkRenderer->GetSize();
double l2 =
(m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) *
(m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) +
(m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]) *
(m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]);
double rotationAngle = 360.0 * sqrt(l2/(size[0]*size[0]+size[1]*size[1]));
// Use center of data bounding box as center of rotation
Point3D rotationCenter = m_OriginalGeometry->GetCenter();
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Reset current Geometry3D to original state (pre-interaction) and
// apply rotation
RotationOperation op( OpROTATE, rotationCenter, rotationAxis, rotationAngle );
Geometry3D::Pointer newGeometry = static_cast< Geometry3D * >(
m_OriginalGeometry->Clone().GetPointer() );
newGeometry->ExecuteOperation( &op );
mitk::TimeSlicedGeometry::Pointer timeSlicedGeometry = this->GetDataNode()->GetData()->GetTimeSlicedGeometry();
if (timeSlicedGeometry.IsNotNull())
{
timeSlicedGeometry->SetGeometry3D( newGeometry, timeStep );
}
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
else
return false;
}
bool mitk::AffineDataInteractor3D::ColorizeSurface(BaseRenderer::Pointer renderer, double scalar)
{
BaseData::Pointer data = this->GetDataNode()->GetData();
if(data.IsNull())
{
MITK_ERROR << "AffineInteractor3D: No data object present!";
return false;
}
// Get the timestep to also support 3D+t
int timeStep = 0;
if (renderer.IsNotNull())
timeStep = renderer->GetTimeStep(data);
// If data is an mitk::Surface, extract it
Surface::Pointer surface = dynamic_cast< Surface* >(data.GetPointer());
vtkPolyData* polyData = NULL;
if (surface.IsNotNull())
polyData = surface->GetVtkPolyData(timeStep);
if (polyData == NULL)
{
MITK_ERROR << "AffineInteractor3D: No poly data present!";
return false;
}
vtkPointData *pointData = polyData->GetPointData();
if (pointData == NULL)
{
MITK_ERROR << "AffineInteractor3D: No point data present!";
return false;
}
vtkDataArray *scalars = pointData->GetScalars();
if (scalars == NULL)
{
MITK_ERROR << "AffineInteractor3D: No scalars for point data present!";
return false;
}
for (unsigned int i = 0; i < pointData->GetNumberOfTuples(); ++i)
{
scalars->SetComponent(i, 0, scalar);
}
polyData->Modified();
pointData->Update();
return true;
}
<commit_msg>cleanup<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkAffineDataInteractor3D.h"
#include "mitkDispatcher.h"
#include "mitkInteractionConst.h" // TODO: refactor file
#include "mitkInteractionPositionEvent.h"
#include "mitkInternalEvent.h"
#include "mitkMouseMoveEvent.h"
#include "mitkRenderingManager.h"
#include "mitkRotationOperation.h"
#include "mitkSurface.h"
#include <mitkPointOperation.h>
#include <vtkCamera.h>
#include <vtkDataArray.h>
#include <vtkInteractorStyle.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkRenderWindowInteractor.h>
mitk::AffineDataInteractor3D::AffineDataInteractor3D()
{
m_OriginalGeometry = Geometry3D::New();
// Initialize vector arithmetic
m_ObjectNormal[0] = 0.0;
m_ObjectNormal[1] = 0.0;
m_ObjectNormal[2] = 1.0;
}
mitk::AffineDataInteractor3D::~AffineDataInteractor3D()
{
}
void mitk::AffineDataInteractor3D::ConnectActionsAndFunctions()
{
// **Conditions** that can be used in the state machine,
// to ensure that certain conditions are met, before
// actually executing an action
CONNECT_CONDITION("isOverObject", CheckOverObject);
// **Function** in the statmachine patterns also referred to as **Actions**
CONNECT_FUNCTION("selectObject",SelectObject);
CONNECT_FUNCTION("deselectObject",DeselectObject);
CONNECT_FUNCTION("initTranslate",InitTranslate);
CONNECT_FUNCTION("initRotate",InitRotate);
CONNECT_FUNCTION("translateObject",TranslateObject);
CONNECT_FUNCTION("rotateObject",RotateObject);
}
void mitk::AffineDataInteractor3D::DataNodeChanged()
{
}
bool mitk::AffineDataInteractor3D::CheckOverObject(const InteractionEvent* interactionEvent)
{
////Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
////Re-enable VTK interactor (may have been disabled previously)
const InteractionPositionEvent* positionEvent = dynamic_cast<const InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
if(interactionEvent->GetSender()->PickObject( m_CurrentPickedDisplayPoint, m_CurrentPickedPoint ) == this->GetDataNode().GetPointer())
{
return true;
}
return false;
}
bool mitk::AffineDataInteractor3D::SelectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 0.0, 0.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe dependend on distance from picked point
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), 0.0 );
return true;
}
bool mitk::AffineDataInteractor3D::DeselectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 1.0, 1.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe as inactive
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), -1.0 );
return true;
}
bool mitk::AffineDataInteractor3D::InitTranslate(StateMachineAction*, InteractionEvent* interactionEvent)
{
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
m_InitialPickedPoint = m_CurrentPickedPoint;
m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Make deep copy of current Geometry3D of the plane
this->GetDataNode()->GetData()->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
m_OriginalGeometry = static_cast< Geometry3D * >(this->GetDataNode()->GetData()->GetGeometry( timeStep )->Clone().GetPointer() );
return true;
}
bool mitk::AffineDataInteractor3D::InitRotate(StateMachineAction*, InteractionEvent* interactionEvent)
{
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
m_InitialPickedPoint = m_CurrentPickedPoint;
m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Make deep copy of current Geometry3D of the plane
this->GetDataNode()->GetData()->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
m_OriginalGeometry = static_cast< Geometry3D * >(this->GetDataNode()->GetData()->GetGeometry( timeStep )->Clone().GetPointer() );
return true;
}
bool mitk::AffineDataInteractor3D::TranslateObject (StateMachineAction*, InteractionEvent* interactionEvent)
{
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
Vector3D interactionMove;
interactionMove[0] = m_CurrentPickedPoint[0] - m_InitialPickedPoint[0];
interactionMove[1] = m_CurrentPickedPoint[1] - m_InitialPickedPoint[1];
interactionMove[2] = m_CurrentPickedPoint[2] - m_InitialPickedPoint[2];
Point3D origin = m_OriginalGeometry->GetOrigin();
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// If data is an mitk::Surface, extract it
Surface::Pointer surface = dynamic_cast< Surface* >(this->GetDataNode()->GetData());
vtkPolyData* polyData = NULL;
if (surface.IsNotNull())
{
polyData = surface->GetVtkPolyData( timeStep );
// Extract surface normal from surface (if existent, otherwise use default)
vtkPointData* pointData = polyData->GetPointData();
if (pointData != NULL)
{
vtkDataArray* normal = polyData->GetPointData()->GetVectors( "planeNormal" );
if (normal != NULL)
{
m_ObjectNormal[0] = normal->GetComponent( 0, 0 );
m_ObjectNormal[1] = normal->GetComponent( 0, 1 );
m_ObjectNormal[2] = normal->GetComponent( 0, 2 );
}
}
}
Vector3D transformedObjectNormal;
this->GetDataNode()->GetData()->GetGeometry( timeStep )->IndexToWorld(
m_ObjectNormal, transformedObjectNormal );
this->GetDataNode()->GetData()->GetGeometry( timeStep )->SetOrigin(
origin + transformedObjectNormal * (interactionMove * transformedObjectNormal) );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
bool mitk::AffineDataInteractor3D::RotateObject (StateMachineAction*, InteractionEvent* interactionEvent)
{
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
vtkCamera* camera = NULL;
vtkRenderer *currentVtkRenderer = NULL;
if ((interactionEvent->GetSender()) != NULL)
{
vtkRenderWindow* renderWindow = interactionEvent->GetSender()->GetRenderWindow();
if ( renderWindow != NULL )
{
vtkRenderWindowInteractor* renderWindowInteractor = renderWindow->GetInteractor();
if ( renderWindowInteractor != NULL )
{
currentVtkRenderer = renderWindowInteractor->GetInteractorStyle()->GetCurrentRenderer();
if ( currentVtkRenderer != NULL )
camera = currentVtkRenderer->GetActiveCamera();
}
}
}
if ( camera )
{
vtkFloatingPointType vpn[3];
camera->GetViewPlaneNormal( vpn );
Vector3D viewPlaneNormal;
viewPlaneNormal[0] = vpn[0];
viewPlaneNormal[1] = vpn[1];
viewPlaneNormal[2] = vpn[2];
Vector3D interactionMove;
interactionMove[0] = m_CurrentPickedPoint[0] - m_InitialPickedPoint[0];
interactionMove[1] = m_CurrentPickedPoint[1] - m_InitialPickedPoint[1];
interactionMove[2] = m_CurrentPickedPoint[2] - m_InitialPickedPoint[2];
if (interactionMove[0]==0 && interactionMove[1]==0 && interactionMove[2]==0)
return true;
Vector3D rotationAxis = itk::CrossProduct( viewPlaneNormal, interactionMove );
rotationAxis.Normalize();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
int *size = currentVtkRenderer->GetSize();
double l2 =
(m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) *
(m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) +
(m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]) *
(m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]);
double rotationAngle = 360.0 * sqrt(l2/(size[0]*size[0]+size[1]*size[1]));
// Use center of data bounding box as center of rotation
Point3D rotationCenter = m_OriginalGeometry->GetCenter();
int timeStep = 0;
if ((interactionEvent->GetSender()) != NULL)
timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Reset current Geometry3D to original state (pre-interaction) and
// apply rotation
RotationOperation op( OpROTATE, rotationCenter, rotationAxis, rotationAngle );
Geometry3D::Pointer newGeometry = static_cast< Geometry3D * >(
m_OriginalGeometry->Clone().GetPointer() );
newGeometry->ExecuteOperation( &op );
mitk::TimeSlicedGeometry::Pointer timeSlicedGeometry = this->GetDataNode()->GetData()->GetTimeSlicedGeometry();
if (timeSlicedGeometry.IsNotNull())
{
timeSlicedGeometry->SetGeometry3D( newGeometry, timeStep );
}
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
else
return false;
}
bool mitk::AffineDataInteractor3D::ColorizeSurface(BaseRenderer::Pointer renderer, double scalar)
{
BaseData::Pointer data = this->GetDataNode()->GetData();
if(data.IsNull())
{
MITK_ERROR << "AffineInteractor3D: No data object present!";
return false;
}
// Get the timestep to also support 3D+t
int timeStep = 0;
if (renderer.IsNotNull())
timeStep = renderer->GetTimeStep(data);
// If data is an mitk::Surface, extract it
Surface::Pointer surface = dynamic_cast< Surface* >(data.GetPointer());
vtkPolyData* polyData = NULL;
if (surface.IsNotNull())
polyData = surface->GetVtkPolyData(timeStep);
if (polyData == NULL)
{
MITK_ERROR << "AffineInteractor3D: No poly data present!";
return false;
}
vtkPointData *pointData = polyData->GetPointData();
if (pointData == NULL)
{
MITK_ERROR << "AffineInteractor3D: No point data present!";
return false;
}
vtkDataArray *scalars = pointData->GetScalars();
if (scalars == NULL)
{
MITK_ERROR << "AffineInteractor3D: No scalars for point data present!";
return false;
}
for (unsigned int i = 0; i < pointData->GetNumberOfTuples(); ++i)
{
scalars->SetComponent(i, 0, scalar);
}
polyData->Modified();
pointData->Update();
return true;
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkContourModelMapper2D.h>
#include <vtkPoints.h>
#include <vtkCellArray.h>
#include <vtkProperty.h>
#include <vtkPlane.h>
#include <vtkCutter.h>
#include <vtkStripper.h>
#include <vtkTubeFilter.h>
mitk::ContourModelMapper2D::ContourModelMapper2D()
{
}
mitk::ContourModelMapper2D::~ContourModelMapper2D()
{
}
const mitk::ContourModel* mitk::ContourModelMapper2D::GetInput( void )
{
//convient way to get the data from the dataNode
return static_cast< const mitk::ContourModel * >( this->GetData() );
}
vtkProp* mitk::ContourModelMapper2D::GetVtkProp(mitk::BaseRenderer* renderer)
{
//return the actor corresponding to the renderer
return m_LSH.GetLocalStorage(renderer)->m_Actor;
}
void mitk::ContourModelMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
if ( this->IsVisible(renderer)==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
}
}
void mitk::ContourModelMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
if ( this->IsVisible( renderer )==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
}
void mitk::ContourModelMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
if ( this->IsVisible(renderer)==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
}
}
void mitk::ContourModelMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
if(IsVisible(renderer)==false)
return;
if ( GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
}
}
void mitk::ContourModelMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
/*++ convert the contour to vtkPolyData and set it as input for our mapper ++*/
LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
mitk::ContourModel* inputContour = static_cast< mitk::ContourModel* >( this->GetData() );
localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour, renderer);
localStorage->m_Mapper->SetInput(localStorage->m_OutlinePolyData);
this->ApplyContourProperties(renderer);
}
void mitk::ContourModelMapper2D::Update(mitk::BaseRenderer* renderer)
{
if ( !this->IsVisible( renderer ) )
{
return;
}
//check if there is something to be rendered
mitk::ContourModel* data = static_cast< mitk::ContourModel*>( this->GetData() );
if ( data == NULL )
{
return;
}
// Calculate time step of the input data for the specified renderer (integer value)
this->CalculateTimeStep( renderer );
// Check if time step is valid
const TimeSlicedGeometry *dataTimeGeometry = data->GetTimeSlicedGeometry();
if ( ( dataTimeGeometry == NULL )
|| ( dataTimeGeometry->GetTimeSteps() == 0 )
|| ( !dataTimeGeometry->IsValidTime( this->GetTimestep() ) ) )
{
return;
}
const DataNode *node = this->GetDataNode();
data->UpdateOutputInformation();
LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
//check if something important has changed and we need to rerender
if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified?
|| (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified?
|| (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2DUpdateTime()) //was the geometry modified?
|| (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2D()->GetMTime())
|| (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
|| (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
{
this->GenerateDataForRenderer( renderer );
}
// since we have checked that nothing important has changed, we can set
// m_LastUpdateTime to the current time
localStorage->m_LastUpdateTime.Modified();
}
vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper2D::CreateVtkPolyDataFromContour(mitk::ContourModel* inputContour, mitk::BaseRenderer* renderer)
{
/* First of all convert the control points of the contourModel to vtk points
* and add lines in between them
*/
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); //the points to draw
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); //the lines to connect the points
//iterate over all control points
mitk::ContourModel::VertexIterator current = inputContour->IteratorBegin();
mitk::ContourModel::VertexIterator next = inputContour->IteratorBegin();
next++;
mitk::ContourModel::VertexIterator end = inputContour->IteratorEnd();
while(next != end)
{
mitk::ContourModel::VertexType* currentControlPoint = *current;
mitk::ContourModel::VertexType* nextControlPoint = *next;
vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]);
vtkIdType p2 = points->InsertNextPoint(nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]);
//add the line between both contorlPoints
lines->InsertNextCell(2);
lines->InsertCellPoint(p1);
lines->InsertCellPoint(p2);
current++;
next++;
}
/* If the contour is closed an additional line has to be created between the very first point
* and the last point
*/
if(inputContour->IsClosed())
{
//add a line from the last to the first control point
mitk::ContourModel::VertexType* firstControlPoint = *(inputContour->IteratorBegin());
mitk::ContourModel::VertexType* lastControlPoint = *(--(inputContour->IteratorEnd()));
vtkIdType p2 = points->InsertNextPoint(lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]);
vtkIdType p1 = points->InsertNextPoint(firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]);
//add the line between both contorlPoints
lines->InsertNextCell(2);
lines->InsertCellPoint(p1);
lines->InsertCellPoint(p2);
}
// Create a polydata to store everything in
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
// Add the points to the dataset
polyData->SetPoints(points);
// Add the lines to the dataset
polyData->SetLines(lines);
//check for the worldgeometry from the current render window
mitk::PlaneGeometry* currentWorldGeometry = dynamic_cast<mitk::PlaneGeometry*>( const_cast<mitk::Geometry2D*>(renderer->GetCurrentWorldGeometry2D()));
if (currentWorldGeometry)
{
//slice through the data to get a 2D representation of the (possible) 3D contour
//needed because currently there is no outher solution if the contour is within the plane
vtkSmartPointer<vtkTubeFilter> tubeFilter = vtkSmartPointer<vtkTubeFilter>::New();
tubeFilter->SetInput(polyData);
tubeFilter->SetRadius(0.01);
//origin and normal of vtkPlane
mitk::Point3D origin = currentWorldGeometry->GetOrigin();
mitk::Vector3D normal = currentWorldGeometry->GetNormal();
//the implicit function to slice through the polyData
vtkSmartPointer<vtkPlane> plane = vtkSmartPointer<vtkPlane>::New();
plane->SetOrigin(origin[0], origin[1], origin[2]);
plane->SetNormal(normal[0], normal[1], normal[2]);
//cuts through vtkPolyData with a given implicit function. In our case a plane
vtkSmartPointer<vtkCutter> cutter = vtkSmartPointer<vtkCutter>::New();
cutter->SetCutFunction(plane);
//cutter->SetInput(polyData);
cutter->SetInputConnection(tubeFilter->GetOutputPort());
vtkSmartPointer<vtkStripper> cutStrips = vtkStripper::New();
cutStrips->SetInputConnection(cutter->GetOutputPort());
cutStrips->Update();
//store the result in a new polyData
vtkSmartPointer<vtkPolyData> cutPolyData = vtkSmartPointer<vtkPolyData>::New();
cutPolyData= cutStrips->GetOutput();
return cutPolyData;
}
return polyData;
}
void mitk::ContourModelMapper2D::ApplyContourProperties(mitk::BaseRenderer* renderer)
{
LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
float binaryOutlineWidth(1.0);
if (this->GetDataNode()->GetFloatProperty( "contour width", binaryOutlineWidth, renderer ))
{
localStorage->m_Actor->GetProperty()->SetLineWidth(binaryOutlineWidth);
}
localStorage->m_Actor->GetProperty()->SetColor(0.9, 1.0, 0.1);
}
/*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/
mitk::ContourModelMapper2D::LocalStorage* mitk::ContourModelMapper2D::GetLocalStorage(mitk::BaseRenderer* renderer)
{
return m_LSH.GetLocalStorage(renderer);
}
mitk::ContourModelMapper2D::LocalStorage::LocalStorage()
{
m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
m_Actor = vtkSmartPointer<vtkActor>::New();
m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New();
//set the mapper for the actor
m_Actor->SetMapper(m_Mapper);
}
void mitk::ContourModelMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite );
node->AddProperty( "contour width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}<commit_msg>contour is correctly rendered in 2D window<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkContourModelMapper2D.h>
#include <vtkPoints.h>
#include <vtkCellArray.h>
#include <vtkProperty.h>
#include <vtkPlane.h>
#include <vtkCutter.h>
#include <vtkStripper.h>
#include <vtkTubeFilter.h>
mitk::ContourModelMapper2D::ContourModelMapper2D()
{
}
mitk::ContourModelMapper2D::~ContourModelMapper2D()
{
}
const mitk::ContourModel* mitk::ContourModelMapper2D::GetInput( void )
{
//convient way to get the data from the dataNode
return static_cast< const mitk::ContourModel * >( this->GetData() );
}
vtkProp* mitk::ContourModelMapper2D::GetVtkProp(mitk::BaseRenderer* renderer)
{
//return the actor corresponding to the renderer
return m_LSH.GetLocalStorage(renderer)->m_Actor;
}
void mitk::ContourModelMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
if ( this->IsVisible(renderer)==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
}
}
void mitk::ContourModelMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
if ( this->IsVisible( renderer )==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
}
void mitk::ContourModelMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
if ( this->IsVisible(renderer)==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
}
}
void mitk::ContourModelMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
if(IsVisible(renderer)==false)
return;
if ( GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
}
}
void mitk::ContourModelMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer )
{
/*++ convert the contour to vtkPolyData and set it as input for our mapper ++*/
LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
mitk::ContourModel* inputContour = static_cast< mitk::ContourModel* >( this->GetData() );
localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour, renderer);
localStorage->m_Mapper->SetInput(localStorage->m_OutlinePolyData);
this->ApplyContourProperties(renderer);
}
void mitk::ContourModelMapper2D::Update(mitk::BaseRenderer* renderer)
{
if ( !this->IsVisible( renderer ) )
{
return;
}
//check if there is something to be rendered
mitk::ContourModel* data = static_cast< mitk::ContourModel*>( this->GetData() );
if ( data == NULL )
{
return;
}
// Calculate time step of the input data for the specified renderer (integer value)
this->CalculateTimeStep( renderer );
// Check if time step is valid
const TimeSlicedGeometry *dataTimeGeometry = data->GetTimeSlicedGeometry();
if ( ( dataTimeGeometry == NULL )
|| ( dataTimeGeometry->GetTimeSteps() == 0 )
|| ( !dataTimeGeometry->IsValidTime( this->GetTimestep() ) ) )
{
return;
}
const DataNode *node = this->GetDataNode();
data->UpdateOutputInformation();
LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
//check if something important has changed and we need to rerender
if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified?
|| (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified?
|| (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2DUpdateTime()) //was the geometry modified?
|| (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2D()->GetMTime())
|| (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
|| (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
{
this->GenerateDataForRenderer( renderer );
}
// since we have checked that nothing important has changed, we can set
// m_LastUpdateTime to the current time
localStorage->m_LastUpdateTime.Modified();
}
vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper2D::CreateVtkPolyDataFromContour(mitk::ContourModel* inputContour, mitk::BaseRenderer* renderer)
{
/* First of all convert the control points of the contourModel to vtk points
* and add lines in between them
*/
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); //the points to draw
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); //the lines to connect the points
//iterate over all control points
mitk::ContourModel::VertexIterator current = inputContour->IteratorBegin();
mitk::ContourModel::VertexIterator next = inputContour->IteratorBegin();
next++;
mitk::ContourModel::VertexIterator end = inputContour->IteratorEnd();
while(next != end)
{
mitk::ContourModel::VertexType* currentControlPoint = *current;
mitk::ContourModel::VertexType* nextControlPoint = *next;
vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]);
vtkIdType p2 = points->InsertNextPoint(nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]);
//add the line between both contorlPoints
lines->InsertNextCell(2);
lines->InsertCellPoint(p1);
lines->InsertCellPoint(p2);
current++;
next++;
}
/* If the contour is closed an additional line has to be created between the very first point
* and the last point
*/
if(inputContour->IsClosed())
{
//add a line from the last to the first control point
mitk::ContourModel::VertexType* firstControlPoint = *(inputContour->IteratorBegin());
mitk::ContourModel::VertexType* lastControlPoint = *(--(inputContour->IteratorEnd()));
vtkIdType p2 = points->InsertNextPoint(lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]);
vtkIdType p1 = points->InsertNextPoint(firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]);
//add the line between both contorlPoints
lines->InsertNextCell(2);
lines->InsertCellPoint(p1);
lines->InsertCellPoint(p2);
}
// Create a polydata to store everything in
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
// Add the points to the dataset
polyData->SetPoints(points);
// Add the lines to the dataset
polyData->SetLines(lines);
//check for the worldgeometry from the current render window
mitk::PlaneGeometry* currentWorldGeometry = dynamic_cast<mitk::PlaneGeometry*>( const_cast<mitk::Geometry2D*>(renderer->GetCurrentWorldGeometry2D()));
if (currentWorldGeometry)
{
//slice through the data to get a 2D representation of the (possible) 3D contour
//needed because currently there is no outher solution if the contour is within the plane
vtkSmartPointer<vtkTubeFilter> tubeFilter = vtkSmartPointer<vtkTubeFilter>::New();
tubeFilter->SetInput(polyData);
tubeFilter->SetRadius(0.05);
//origin and normal of vtkPlane
mitk::Point3D origin = currentWorldGeometry->GetOrigin();
mitk::Vector3D normal = currentWorldGeometry->GetNormal();
//the implicit function to slice through the polyData
vtkSmartPointer<vtkPlane> plane = vtkSmartPointer<vtkPlane>::New();
plane->SetOrigin(origin[0], origin[1], origin[2]);
plane->SetNormal(normal[0], normal[1], normal[2]);
//cuts through vtkPolyData with a given implicit function. In our case a plane
vtkSmartPointer<vtkCutter> cutter = vtkSmartPointer<vtkCutter>::New();
cutter->SetCutFunction(plane);
//cutter->SetInput(polyData);
cutter->SetInputConnection(tubeFilter->GetOutputPort());
//we want the scalars of the input - so turn off generating the scalars within vtkCutter
cutter->GenerateCutScalarsOff();
cutter->Update();
//store the result in a new polyData
vtkSmartPointer<vtkPolyData> cutPolyData = vtkSmartPointer<vtkPolyData>::New();
cutPolyData= cutter->GetOutput();
return cutPolyData;
}
return polyData;
}
void mitk::ContourModelMapper2D::ApplyContourProperties(mitk::BaseRenderer* renderer)
{
LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
float binaryOutlineWidth(1.0);
if (this->GetDataNode()->GetFloatProperty( "contour width", binaryOutlineWidth, renderer ))
{
localStorage->m_Actor->GetProperty()->SetLineWidth(binaryOutlineWidth);
}
//make sure that directional lighting isn't used for our contour
localStorage->m_Actor->GetProperty()->SetAmbient(1.0);
localStorage->m_Actor->GetProperty()->SetDiffuse(0.0);
localStorage->m_Actor->GetProperty()->SetSpecular(0.0);
//set the color of the contour
localStorage->m_Actor->GetProperty()->SetColor(0.9, 1.0, 0.1);
}
/*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/
mitk::ContourModelMapper2D::LocalStorage* mitk::ContourModelMapper2D::GetLocalStorage(mitk::BaseRenderer* renderer)
{
return m_LSH.GetLocalStorage(renderer);
}
mitk::ContourModelMapper2D::LocalStorage::LocalStorage()
{
m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
m_Actor = vtkSmartPointer<vtkActor>::New();
m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New();
//set the mapper for the actor
m_Actor->SetMapper(m_Mapper);
}
void mitk::ContourModelMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite );
node->AddProperty( "contour width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** 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 [email protected].
**
**************************************************************************/
#include "projectwindow.h"
#include "doubletabwidget.h"
#include "project.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "session.h"
#include "projecttreewidget.h"
#include "iprojectproperties.h"
#include "targetsettingspanel.h"
#include "target.h"
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <utils/stylehelper.h>
#include <QApplication>
#include <QGridLayout>
#include <QLabel>
#include <QPainter>
#include <QStackedWidget>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
namespace {
const int ICON_SIZE(64);
const int ABOVE_HEADING_MARGIN(10);
const int ABOVE_CONTENTS_MARGIN(4);
const int BELOW_CONTENTS_MARGIN(16);
} // anonymous namespace
///
// OnePixelBlackLine
///
class OnePixelBlackLine : public QWidget
{
public:
OnePixelBlackLine(QWidget *parent)
: QWidget(parent)
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setMinimumHeight(1);
setMaximumHeight(1);
}
void paintEvent(QPaintEvent *e)
{
Q_UNUSED(e);
QPainter p(this);
QColor fillColor = Utils::StyleHelper::mergedColors(
palette().button().color(), Qt::black, 80);
p.fillRect(contentsRect(), fillColor);
}
};
class RootWidget : public QWidget
{
public:
RootWidget(QWidget *parent) : QWidget(parent) {
setFocusPolicy(Qt::NoFocus);
}
void paintEvent(QPaintEvent *);
};
void RootWidget::paintEvent(QPaintEvent *e)
{
QWidget::paintEvent(e);
QPainter painter(this);
QColor light = Utils::StyleHelper::mergedColors(
palette().button().color(), Qt::white, 30);
QColor dark = Utils::StyleHelper::mergedColors(
palette().button().color(), Qt::black, 85);
painter.setPen(light);
painter.drawLine(rect().topRight(), rect().bottomRight());
painter.setPen(dark);
painter.drawLine(rect().topRight() - QPoint(1,0), rect().bottomRight() - QPoint(1,0));
}
///
// PanelsWidget
///
PanelsWidget::PanelsWidget(QWidget *parent) :
QScrollArea(parent),
m_root(new RootWidget(this))
{
// We want a 900px wide widget with and the scrollbar at the
// side of the screen.
m_root->setFixedWidth(900);
m_root->setContentsMargins(0, 0, 40, 0);
QPalette pal = m_root->palette();
QColor background = Utils::StyleHelper::mergedColors(
palette().window().color(), Qt::white, 85);
pal.setColor(QPalette::All, QPalette::Window, background.darker(102));
setPalette(pal);
pal.setColor(QPalette::All, QPalette::Window, background);
m_root->setPalette(pal);
// The layout holding the individual panels:
m_layout = new QGridLayout(m_root);
m_layout->setColumnMinimumWidth(0, ICON_SIZE + 4);
m_layout->setSpacing(0);
setWidget(m_root);
setFrameStyle(QFrame::NoFrame);
setWidgetResizable(true);
setFocusPolicy(Qt::NoFocus);
}
PanelsWidget::~PanelsWidget()
{
qDeleteAll(m_panels);
}
/*
* Add a widget with heading information into the grid
* layout of the PanelsWidget.
*
* ...
* +--------+-------------------------------------------+ ABOVE_HEADING_MARGIN
* | icon | name |
* + +-------------------------------------------+
* | | line |
* +--------+-------------------------------------------+ ABOVE_CONTENTS_MARGIN
* | widget (with contentsmargins adjusted!) |
* +--------+-------------------------------------------+ BELOW_CONTENTS_MARGIN
*/
void PanelsWidget::addPropertiesPanel(PropertiesPanel *panel)
{
QTC_ASSERT(panel, return);
const int headerRow(m_layout->rowCount() - 1);
// icon:
if (!panel->icon().isNull()) {
QLabel *iconLabel = new QLabel(m_root);
iconLabel->setPixmap(panel->icon().pixmap(ICON_SIZE, ICON_SIZE));
iconLabel->setContentsMargins(0, ABOVE_HEADING_MARGIN, 0, 0);
m_layout->addWidget(iconLabel, headerRow, 0, 3, 1, Qt::AlignTop | Qt::AlignHCenter);
}
// name:
QLabel *nameLabel = new QLabel(m_root);
nameLabel->setText(panel->displayName());
QPalette palette = nameLabel->palette();
palette.setBrush(QPalette::All, QPalette::Foreground, QColor(0, 0, 0, 110));
nameLabel->setPalette(palette);
nameLabel->setContentsMargins(0, ABOVE_HEADING_MARGIN, 0, 0);
QFont f = nameLabel->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.6);
nameLabel->setFont(f);
m_layout->addWidget(nameLabel, headerRow, 1, 1, 1, Qt::AlignVCenter | Qt::AlignLeft);
// line:
const int lineRow(headerRow + 1);
QWidget *line = new OnePixelBlackLine(m_root);
m_layout->addWidget(line, lineRow, 1, 1, -1, Qt::AlignTop);
// add the widget:
const int widgetRow(lineRow + 1);
addPanelWidget(panel, widgetRow);
}
void PanelsWidget::addPanelWidget(PropertiesPanel *panel, int row)
{
QWidget *widget = panel->widget();
widget->setContentsMargins(Constants::PANEL_LEFT_MARGIN,
ABOVE_CONTENTS_MARGIN, 0,
BELOW_CONTENTS_MARGIN);
widget->setParent(m_root);
m_layout->addWidget(widget, row, 0, 1, 2);
m_panels.append(panel);
}
///
// ProjectWindow
///
ProjectWindow::ProjectWindow(QWidget *parent)
: QWidget(parent),
m_currentWidget(0),
m_previousTargetSubIndex(-1)
{
ProjectExplorer::SessionManager *session = ProjectExplorerPlugin::instance()->session();
// Setup overall layout:
QVBoxLayout *viewLayout = new QVBoxLayout(this);
viewLayout->setMargin(0);
viewLayout->setSpacing(0);
m_tabWidget = new DoubleTabWidget(this);
viewLayout->addWidget(m_tabWidget);
// Setup our container for the contents:
m_centralWidget = new QStackedWidget(this);
viewLayout->addWidget(m_centralWidget);
// connects:
connect(m_tabWidget, SIGNAL(currentIndexChanged(int,int)),
this, SLOT(showProperties(int,int)));
connect(session, SIGNAL(sessionLoaded(QString)), this, SLOT(restoreStatus()));
connect(session, SIGNAL(aboutToSaveSession()), this, SLOT(saveStatus()));
connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(registerProject(ProjectExplorer::Project*)));
connect(session, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
this, SLOT(deregisterProject(ProjectExplorer::Project*)));
connect(session, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(startupProjectChanged(ProjectExplorer::Project*)));
connect(session, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
this, SLOT(projectUpdated(ProjectExplorer::Project*)));
// Update properties to empty project for now:
showProperties(-1, -1);
}
ProjectWindow::~ProjectWindow()
{
}
void ProjectWindow::extensionsInitialized()
{
foreach (ITargetFactory *fac, ExtensionSystem::PluginManager::instance()->getObjects<ITargetFactory>())
connect(fac, SIGNAL(canCreateTargetIdsChanged()),
this, SLOT(targetFactoriesChanged()));
QList<IProjectPanelFactory *> list = ExtensionSystem::PluginManager::instance()->getObjects<IProjectPanelFactory>();
qSort(list.begin(), list.end(), &IPanelFactory::prioritySort);
}
void ProjectWindow::aboutToShutdown()
{
showProperties(-1, -1); // that's a bit stupid, but otherwise stuff is still
// connected to the session
disconnect(ProjectExplorerPlugin::instance()->session(), 0, this, 0);
}
void ProjectWindow::projectUpdated(Project *p)
{
// Called after a project was configured
int index = m_tabWidget->currentIndex();
deregisterProject(p);
registerProject(p);
m_tabWidget->setCurrentIndex(index);
}
void ProjectWindow::targetFactoriesChanged()
{
bool changed = false;
int index = m_tabWidget->currentIndex();
QList<Project *> projects = m_tabIndexToProject;
foreach (ProjectExplorer::Project *project, projects) {
if (m_usesTargetPage.value(project) != useTargetPage(project)) {
changed = true;
deregisterProject(project);
registerProject(project);
}
}
if (changed)
m_tabWidget->setCurrentIndex(index);
}
bool ProjectWindow::useTargetPage(ProjectExplorer::Project *project)
{
if (project->targets().isEmpty())
return false;
if (project->targets().size() > 1)
return true;
int count = 0;
foreach (ITargetFactory *fac, ExtensionSystem::PluginManager::instance()->getObjects<ITargetFactory>()) {
foreach (Core::Id targetId, fac->supportedTargetIds()) {
if (fac->canCreate(project, targetId))
++count;
if (count > 1)
return true;
}
}
return false;
}
void ProjectWindow::registerProject(ProjectExplorer::Project *project)
{
if (!project || m_tabIndexToProject.contains(project))
return;
// find index to insert:
int index = -1;
for (int i = 0; i <= m_tabIndexToProject.count(); ++i) {
if (i == m_tabIndexToProject.count() ||
m_tabIndexToProject.at(i)->displayName() > project->displayName()) {
index = i;
break;
}
}
QStringList subtabs;
bool usesTargetPage = useTargetPage(project);
m_usesTargetPage.insert(project, usesTargetPage);
if (!usesTargetPage){
// Show the target specific pages directly
if (project->activeTarget()) {
QList<ITargetPanelFactory *> factories =
ExtensionSystem::PluginManager::instance()->getObjects<ITargetPanelFactory>();
qSort(factories.begin(), factories.end(), &IPanelFactory::prioritySort);
foreach (ITargetPanelFactory *factory, factories)
if (factory->supports(project->activeTarget()))
subtabs << factory->displayName();
}
} else {
// Use the Targets page
subtabs << QCoreApplication::translate("TargetSettingsPanelFactory", "Targets");
}
// Add the project specific pages
QList<IProjectPanelFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IProjectPanelFactory>();
qSort(factories.begin(), factories.end(), &IPanelFactory::prioritySort);
foreach (IProjectPanelFactory *panelFactory, factories) {
if (panelFactory->supports(project))
subtabs << panelFactory->displayName();
}
m_tabIndexToProject.insert(index, project);
m_tabWidget->insertTab(index, project->displayName(), project->document()->fileName(), subtabs);
}
void ProjectWindow::deregisterProject(ProjectExplorer::Project *project)
{
int index = m_tabIndexToProject.indexOf(project);
if (index < 0)
return;
m_tabIndexToProject.removeAt(index);
m_tabWidget->removeTab(index);
}
void ProjectWindow::startupProjectChanged(ProjectExplorer::Project *p)
{
int index = m_tabIndexToProject.indexOf(p);
if (index != -1)
m_tabWidget->setCurrentIndex(index);
}
void ProjectWindow::showProperties(int index, int subIndex)
{
if (index < 0 || index >= m_tabIndexToProject.count()) {
removeCurrentWidget();
return;
}
Project *project = m_tabIndexToProject.at(index);
// Set up custom panels again:
int pos = 0;
IPanelFactory *fac = 0;
// remember previous sub index state of target settings page
if (TargetSettingsPanelWidget *previousPanelWidget
= qobject_cast<TargetSettingsPanelWidget*>(m_currentWidget)) {
m_previousTargetSubIndex = previousPanelWidget->currentSubIndex();
}
if (m_usesTargetPage.value(project)) {
if (subIndex == 0) {
// Targets page
removeCurrentWidget();
TargetSettingsPanelWidget *panelWidget = new TargetSettingsPanelWidget(project);
if (m_previousTargetSubIndex >= 0)
panelWidget->setCurrentSubIndex(m_previousTargetSubIndex);
m_currentWidget = panelWidget;
m_centralWidget->addWidget(m_currentWidget);
m_centralWidget->setCurrentWidget(m_currentWidget);
}
++pos;
} else if (project->activeTarget()) {
// No Targets page, target specific pages are first in the list
QList<ITargetPanelFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<ITargetPanelFactory>();
qSort(factories.begin(), factories.end(), &ITargetPanelFactory::prioritySort);
foreach (ITargetPanelFactory *panelFactory, factories) {
if (panelFactory->supports(project->activeTarget())) {
if (subIndex == pos) {
fac = panelFactory;
break;
}
++pos;
}
}
}
if (!fac) {
QList<IProjectPanelFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IProjectPanelFactory>();
qSort(factories.begin(), factories.end(), &IPanelFactory::prioritySort);
foreach (IProjectPanelFactory *panelFactory, factories) {
if (panelFactory->supports(project)) {
if (subIndex == pos) {
fac = panelFactory;
break;
}
++pos;
}
}
}
if (fac) {
removeCurrentWidget();
PropertiesPanel *panel = 0;
if (ITargetPanelFactory *ipf = qobject_cast<ITargetPanelFactory *>(fac))
panel = ipf->createPanel(project->activeTarget());
else if (IProjectPanelFactory *ipf = qobject_cast<IProjectPanelFactory *>(fac))
panel = ipf->createPanel(project);
Q_ASSERT(panel);
PanelsWidget *panelsWidget = new PanelsWidget(m_centralWidget);
panelsWidget->addPropertiesPanel(panel);
m_currentWidget = panelsWidget;
m_centralWidget->addWidget(m_currentWidget);
m_centralWidget->setCurrentWidget(m_currentWidget);
}
ProjectExplorerPlugin::instance()->session()->setStartupProject(project);
}
void ProjectWindow::removeCurrentWidget()
{
if (m_currentWidget) {
m_centralWidget->removeWidget(m_currentWidget);
if (m_currentWidget) {
delete m_currentWidget;
m_currentWidget = 0;
}
}
}
<commit_msg>Remove connections to removed functions<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** 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 [email protected].
**
**************************************************************************/
#include "projectwindow.h"
#include "doubletabwidget.h"
#include "project.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "session.h"
#include "projecttreewidget.h"
#include "iprojectproperties.h"
#include "targetsettingspanel.h"
#include "target.h"
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <utils/stylehelper.h>
#include <QApplication>
#include <QGridLayout>
#include <QLabel>
#include <QPainter>
#include <QStackedWidget>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
namespace {
const int ICON_SIZE(64);
const int ABOVE_HEADING_MARGIN(10);
const int ABOVE_CONTENTS_MARGIN(4);
const int BELOW_CONTENTS_MARGIN(16);
} // anonymous namespace
///
// OnePixelBlackLine
///
class OnePixelBlackLine : public QWidget
{
public:
OnePixelBlackLine(QWidget *parent)
: QWidget(parent)
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setMinimumHeight(1);
setMaximumHeight(1);
}
void paintEvent(QPaintEvent *e)
{
Q_UNUSED(e);
QPainter p(this);
QColor fillColor = Utils::StyleHelper::mergedColors(
palette().button().color(), Qt::black, 80);
p.fillRect(contentsRect(), fillColor);
}
};
class RootWidget : public QWidget
{
public:
RootWidget(QWidget *parent) : QWidget(parent) {
setFocusPolicy(Qt::NoFocus);
}
void paintEvent(QPaintEvent *);
};
void RootWidget::paintEvent(QPaintEvent *e)
{
QWidget::paintEvent(e);
QPainter painter(this);
QColor light = Utils::StyleHelper::mergedColors(
palette().button().color(), Qt::white, 30);
QColor dark = Utils::StyleHelper::mergedColors(
palette().button().color(), Qt::black, 85);
painter.setPen(light);
painter.drawLine(rect().topRight(), rect().bottomRight());
painter.setPen(dark);
painter.drawLine(rect().topRight() - QPoint(1,0), rect().bottomRight() - QPoint(1,0));
}
///
// PanelsWidget
///
PanelsWidget::PanelsWidget(QWidget *parent) :
QScrollArea(parent),
m_root(new RootWidget(this))
{
// We want a 900px wide widget with and the scrollbar at the
// side of the screen.
m_root->setFixedWidth(900);
m_root->setContentsMargins(0, 0, 40, 0);
QPalette pal = m_root->palette();
QColor background = Utils::StyleHelper::mergedColors(
palette().window().color(), Qt::white, 85);
pal.setColor(QPalette::All, QPalette::Window, background.darker(102));
setPalette(pal);
pal.setColor(QPalette::All, QPalette::Window, background);
m_root->setPalette(pal);
// The layout holding the individual panels:
m_layout = new QGridLayout(m_root);
m_layout->setColumnMinimumWidth(0, ICON_SIZE + 4);
m_layout->setSpacing(0);
setWidget(m_root);
setFrameStyle(QFrame::NoFrame);
setWidgetResizable(true);
setFocusPolicy(Qt::NoFocus);
}
PanelsWidget::~PanelsWidget()
{
qDeleteAll(m_panels);
}
/*
* Add a widget with heading information into the grid
* layout of the PanelsWidget.
*
* ...
* +--------+-------------------------------------------+ ABOVE_HEADING_MARGIN
* | icon | name |
* + +-------------------------------------------+
* | | line |
* +--------+-------------------------------------------+ ABOVE_CONTENTS_MARGIN
* | widget (with contentsmargins adjusted!) |
* +--------+-------------------------------------------+ BELOW_CONTENTS_MARGIN
*/
void PanelsWidget::addPropertiesPanel(PropertiesPanel *panel)
{
QTC_ASSERT(panel, return);
const int headerRow(m_layout->rowCount() - 1);
// icon:
if (!panel->icon().isNull()) {
QLabel *iconLabel = new QLabel(m_root);
iconLabel->setPixmap(panel->icon().pixmap(ICON_SIZE, ICON_SIZE));
iconLabel->setContentsMargins(0, ABOVE_HEADING_MARGIN, 0, 0);
m_layout->addWidget(iconLabel, headerRow, 0, 3, 1, Qt::AlignTop | Qt::AlignHCenter);
}
// name:
QLabel *nameLabel = new QLabel(m_root);
nameLabel->setText(panel->displayName());
QPalette palette = nameLabel->palette();
palette.setBrush(QPalette::All, QPalette::Foreground, QColor(0, 0, 0, 110));
nameLabel->setPalette(palette);
nameLabel->setContentsMargins(0, ABOVE_HEADING_MARGIN, 0, 0);
QFont f = nameLabel->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.6);
nameLabel->setFont(f);
m_layout->addWidget(nameLabel, headerRow, 1, 1, 1, Qt::AlignVCenter | Qt::AlignLeft);
// line:
const int lineRow(headerRow + 1);
QWidget *line = new OnePixelBlackLine(m_root);
m_layout->addWidget(line, lineRow, 1, 1, -1, Qt::AlignTop);
// add the widget:
const int widgetRow(lineRow + 1);
addPanelWidget(panel, widgetRow);
}
void PanelsWidget::addPanelWidget(PropertiesPanel *panel, int row)
{
QWidget *widget = panel->widget();
widget->setContentsMargins(Constants::PANEL_LEFT_MARGIN,
ABOVE_CONTENTS_MARGIN, 0,
BELOW_CONTENTS_MARGIN);
widget->setParent(m_root);
m_layout->addWidget(widget, row, 0, 1, 2);
m_panels.append(panel);
}
///
// ProjectWindow
///
ProjectWindow::ProjectWindow(QWidget *parent)
: QWidget(parent),
m_currentWidget(0),
m_previousTargetSubIndex(-1)
{
ProjectExplorer::SessionManager *session = ProjectExplorerPlugin::instance()->session();
// Setup overall layout:
QVBoxLayout *viewLayout = new QVBoxLayout(this);
viewLayout->setMargin(0);
viewLayout->setSpacing(0);
m_tabWidget = new DoubleTabWidget(this);
viewLayout->addWidget(m_tabWidget);
// Setup our container for the contents:
m_centralWidget = new QStackedWidget(this);
viewLayout->addWidget(m_centralWidget);
// connects:
connect(m_tabWidget, SIGNAL(currentIndexChanged(int,int)),
this, SLOT(showProperties(int,int)));
connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(registerProject(ProjectExplorer::Project*)));
connect(session, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
this, SLOT(deregisterProject(ProjectExplorer::Project*)));
connect(session, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(startupProjectChanged(ProjectExplorer::Project*)));
connect(session, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
this, SLOT(projectUpdated(ProjectExplorer::Project*)));
// Update properties to empty project for now:
showProperties(-1, -1);
}
ProjectWindow::~ProjectWindow()
{
}
void ProjectWindow::extensionsInitialized()
{
foreach (ITargetFactory *fac, ExtensionSystem::PluginManager::instance()->getObjects<ITargetFactory>())
connect(fac, SIGNAL(canCreateTargetIdsChanged()),
this, SLOT(targetFactoriesChanged()));
QList<IProjectPanelFactory *> list = ExtensionSystem::PluginManager::instance()->getObjects<IProjectPanelFactory>();
qSort(list.begin(), list.end(), &IPanelFactory::prioritySort);
}
void ProjectWindow::aboutToShutdown()
{
showProperties(-1, -1); // that's a bit stupid, but otherwise stuff is still
// connected to the session
disconnect(ProjectExplorerPlugin::instance()->session(), 0, this, 0);
}
void ProjectWindow::projectUpdated(Project *p)
{
// Called after a project was configured
int index = m_tabWidget->currentIndex();
deregisterProject(p);
registerProject(p);
m_tabWidget->setCurrentIndex(index);
}
void ProjectWindow::targetFactoriesChanged()
{
bool changed = false;
int index = m_tabWidget->currentIndex();
QList<Project *> projects = m_tabIndexToProject;
foreach (ProjectExplorer::Project *project, projects) {
if (m_usesTargetPage.value(project) != useTargetPage(project)) {
changed = true;
deregisterProject(project);
registerProject(project);
}
}
if (changed)
m_tabWidget->setCurrentIndex(index);
}
bool ProjectWindow::useTargetPage(ProjectExplorer::Project *project)
{
if (project->targets().isEmpty())
return false;
if (project->targets().size() > 1)
return true;
int count = 0;
foreach (ITargetFactory *fac, ExtensionSystem::PluginManager::instance()->getObjects<ITargetFactory>()) {
foreach (Core::Id targetId, fac->supportedTargetIds()) {
if (fac->canCreate(project, targetId))
++count;
if (count > 1)
return true;
}
}
return false;
}
void ProjectWindow::registerProject(ProjectExplorer::Project *project)
{
if (!project || m_tabIndexToProject.contains(project))
return;
// find index to insert:
int index = -1;
for (int i = 0; i <= m_tabIndexToProject.count(); ++i) {
if (i == m_tabIndexToProject.count() ||
m_tabIndexToProject.at(i)->displayName() > project->displayName()) {
index = i;
break;
}
}
QStringList subtabs;
bool usesTargetPage = useTargetPage(project);
m_usesTargetPage.insert(project, usesTargetPage);
if (!usesTargetPage){
// Show the target specific pages directly
if (project->activeTarget()) {
QList<ITargetPanelFactory *> factories =
ExtensionSystem::PluginManager::instance()->getObjects<ITargetPanelFactory>();
qSort(factories.begin(), factories.end(), &IPanelFactory::prioritySort);
foreach (ITargetPanelFactory *factory, factories)
if (factory->supports(project->activeTarget()))
subtabs << factory->displayName();
}
} else {
// Use the Targets page
subtabs << QCoreApplication::translate("TargetSettingsPanelFactory", "Targets");
}
// Add the project specific pages
QList<IProjectPanelFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IProjectPanelFactory>();
qSort(factories.begin(), factories.end(), &IPanelFactory::prioritySort);
foreach (IProjectPanelFactory *panelFactory, factories) {
if (panelFactory->supports(project))
subtabs << panelFactory->displayName();
}
m_tabIndexToProject.insert(index, project);
m_tabWidget->insertTab(index, project->displayName(), project->document()->fileName(), subtabs);
}
void ProjectWindow::deregisterProject(ProjectExplorer::Project *project)
{
int index = m_tabIndexToProject.indexOf(project);
if (index < 0)
return;
m_tabIndexToProject.removeAt(index);
m_tabWidget->removeTab(index);
}
void ProjectWindow::startupProjectChanged(ProjectExplorer::Project *p)
{
int index = m_tabIndexToProject.indexOf(p);
if (index != -1)
m_tabWidget->setCurrentIndex(index);
}
void ProjectWindow::showProperties(int index, int subIndex)
{
if (index < 0 || index >= m_tabIndexToProject.count()) {
removeCurrentWidget();
return;
}
Project *project = m_tabIndexToProject.at(index);
// Set up custom panels again:
int pos = 0;
IPanelFactory *fac = 0;
// remember previous sub index state of target settings page
if (TargetSettingsPanelWidget *previousPanelWidget
= qobject_cast<TargetSettingsPanelWidget*>(m_currentWidget)) {
m_previousTargetSubIndex = previousPanelWidget->currentSubIndex();
}
if (m_usesTargetPage.value(project)) {
if (subIndex == 0) {
// Targets page
removeCurrentWidget();
TargetSettingsPanelWidget *panelWidget = new TargetSettingsPanelWidget(project);
if (m_previousTargetSubIndex >= 0)
panelWidget->setCurrentSubIndex(m_previousTargetSubIndex);
m_currentWidget = panelWidget;
m_centralWidget->addWidget(m_currentWidget);
m_centralWidget->setCurrentWidget(m_currentWidget);
}
++pos;
} else if (project->activeTarget()) {
// No Targets page, target specific pages are first in the list
QList<ITargetPanelFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<ITargetPanelFactory>();
qSort(factories.begin(), factories.end(), &ITargetPanelFactory::prioritySort);
foreach (ITargetPanelFactory *panelFactory, factories) {
if (panelFactory->supports(project->activeTarget())) {
if (subIndex == pos) {
fac = panelFactory;
break;
}
++pos;
}
}
}
if (!fac) {
QList<IProjectPanelFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IProjectPanelFactory>();
qSort(factories.begin(), factories.end(), &IPanelFactory::prioritySort);
foreach (IProjectPanelFactory *panelFactory, factories) {
if (panelFactory->supports(project)) {
if (subIndex == pos) {
fac = panelFactory;
break;
}
++pos;
}
}
}
if (fac) {
removeCurrentWidget();
PropertiesPanel *panel = 0;
if (ITargetPanelFactory *ipf = qobject_cast<ITargetPanelFactory *>(fac))
panel = ipf->createPanel(project->activeTarget());
else if (IProjectPanelFactory *ipf = qobject_cast<IProjectPanelFactory *>(fac))
panel = ipf->createPanel(project);
Q_ASSERT(panel);
PanelsWidget *panelsWidget = new PanelsWidget(m_centralWidget);
panelsWidget->addPropertiesPanel(panel);
m_currentWidget = panelsWidget;
m_centralWidget->addWidget(m_currentWidget);
m_centralWidget->setCurrentWidget(m_currentWidget);
}
ProjectExplorerPlugin::instance()->session()->setStartupProject(project);
}
void ProjectWindow::removeCurrentWidget()
{
if (m_currentWidget) {
m_centralWidget->removeWidget(m_currentWidget);
if (m_currentWidget) {
delete m_currentWidget;
m_currentWidget = 0;
}
}
}
<|endoftext|> |
<commit_before>#include "AbstractCameraQueue.hpp"
#include <ros/console.h>
void AbstractCameraQueue::enqueue(std::vector<CameraData> data)
{
for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) {
enqueue(*it);
}
}
void AbstractCameraQueue::enqueue(CameraData data)
{
enqueueInternal(data);
if (getSize() > 15) {
ROS_WARN("Camera queue running full. Quadcopter id: %d", data.quadcopterId);
}
}
std::vector<CameraData> AbstractCameraQueue::toVector(CameraData data)
{
std::vector<CameraData> result;
result.push_back(data);
return result;
}<commit_msg>More info of camera queue is running full.<commit_after>#include "AbstractCameraQueue.hpp"
#include <ros/console.h>
void AbstractCameraQueue::enqueue(std::vector<CameraData> data)
{
for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) {
enqueue(*it);
}
}
void AbstractCameraQueue::enqueue(CameraData data)
{
enqueueInternal(data);
if (getSize() > 25) {
ROS_WARN("Camera queue running full. Quadcopter id: %d. Entries: %ld", data.quadcopterId, getSize());
}
}
std::vector<CameraData> AbstractCameraQueue::toVector(CameraData data)
{
std::vector<CameraData> result;
result.push_back(data);
return result;
}<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "Addition.h"
class AdditionTest : public ::testing::Test
{
virtual void SetUp() {}
virtual void TearDown() {}
};
TEST_F(AdditionTest, twoValues)
{
const int x = 2;
const int y = 3;
Addition addition;
EXPECT_EQ(5, addition.twoValues(x, y));
EXPECT_EQ(10, addition.twoValues(5, 6));
}
<commit_msg>Fixed failing test.<commit_after>#include <gtest/gtest.h>
#include "Addition.h"
class AdditionTest : public ::testing::Test
{
virtual void SetUp() {}
virtual void TearDown() {}
};
TEST_F(AdditionTest, twoValues)
{
const int x = 2;
const int y = 3;
Addition addition;
EXPECT_EQ(5, addition.twoValues(x, y));
EXPECT_EQ(10, addition.twoValues(5, 5));
}
<|endoftext|> |
<commit_before>#include "code_generator.h"
#include <unordered_map>
using namespace std;
struct code_generation_context
{
code_generation_context();
~code_generation_context();
unordered_map<string, instruction_sequence> functions;
unordered_map<string, label_instruction*> function_labels;
unordered_map<string, int> variables;
label_instruction* epilog_label;
int tempUsed;
int expressionTarget;
};
class code_generator_impl
{
public:
code_generator_impl();
~code_generator_impl();
instruction_sequence generate_code(program_node* program);
private:
instruction_sequence generate_code(program_node* program, code_generation_context* context);
instruction_sequence generate_code(function_node* function, code_generation_context* context);
instruction_sequence generate_code(statement_node* statement, code_generation_context* context);
instruction_sequence generate_code(if_statement_node* if_statement, code_generation_context* context);
instruction_sequence generate_code(return_statement_node* return_statement, code_generation_context* context);
instruction_sequence generate_code(call_statement_node* call_statement, code_generation_context* context);
instruction_sequence generate_code(expression_node* expression_statement, code_generation_context* context);
instruction_sequence generate_code(literal_node* literal, code_generation_context* context);
instruction_sequence generate_code(identifier_node* variable, code_generation_context* context);
instruction_sequence generate_code(call_node* call, code_generation_context* context);
instruction_sequence generate_code(plus_node* plus, code_generation_context* context);
instruction_sequence generate_code(minus_node* minus, code_generation_context* context);
instruction_sequence generate_code(condition_node* condition, code_generation_context* context);
};
void concatenate(instruction* prev, instruction* next)
{
prev->next = next;
next->prev = prev;
}
void concatenate(instruction_sequence prev, instruction* next)
{
prev.tail->next = next;
next->prev = prev.tail;
}
void concatenate(instruction* prev, instruction_sequence next)
{
prev->next = next.head;
next.head->prev = prev;
}
void concatenate(instruction_sequence prev, instruction_sequence next)
{
prev.tail->next = next.head;
next.head->prev = prev.tail;
}
code_generator::code_generator()
{
this->impl = new code_generator_impl();
}
code_generator::~code_generator()
{
delete this->impl;
}
instruction_sequence code_generator::generate_code(program_node* program)
{
return this->impl->generate_code(program);
}
code_generator_impl::code_generator_impl()
{
}
code_generator_impl::~code_generator_impl()
{
}
instruction_sequence code_generator_impl::generate_code(program_node* program)
{
code_generation_context context;
return this->generate_code(program, &context);
}
instruction_sequence code_generator_impl::generate_code(program_node* program, code_generation_context* context)
{
instruction_sequence result;
function_node* function = program->function;
while (function != nullptr)
{
label_instruction* label = new label_instruction();
context->function_labels.insert(make_pair(function->function_name, label));
}
function = program->function;
while (function != nullptr)
{
instruction_sequence function_body = this->generate_code(function, context);
context->functions.insert(make_pair(function->function_name, function_body));
function = function->next_function;
}
// TODO: Layout and linking
return result;
}
instruction_sequence code_generator_impl::generate_code(function_node* function, code_generation_context* context)
{
instruction_sequence result;
label_instruction* epilog_label = new label_instruction();
context->epilog_label = epilog_label;
context->tempUsed = 0;
if (function->argument_name != nullptr)
{
/* The stack pointer is pointing at empty, before it is the return address, before it is the argument! */
context->variables.insert(make_pair(function->argument_name, -2));
}
instruction_sequence statement_body = generate_code(function->statement, context);
// TODO: Generate prolog and epilog
return result;
}
instruction_sequence code_generator_impl::generate_code(statement_node* statement, code_generation_context* context)
{
switch (statement->get_statement_node_type())
{
case if_statement:
return this->generate_code((if_statement_node*)statement, context);
case return_statement:
return this->generate_code((return_statement_node*)statement, context);
case call_statement:
return this->generate_code((call_statement_node*)statement, context);
default:
instruction_sequence result;
return result;
}
}
instruction_sequence code_generator_impl::generate_code(if_statement_node* if_statement, code_generation_context* context)
{
instruction_sequence result;
int condition_target = ++context->tempUsed;
instruction_sequence condition_code = this->generate_code(if_statement->condition, context);
label_instruction* false_label = new label_instruction();
label_instruction* complete_label = new label_instruction();
// condition code
// load r3, condition_target
// beqz r3, false_label
// true code
// b complete
// false_label
// false code
// complete_label
load_instruction* load_condition = new load_instruction();
load_condition->destination_register = 3;
load_condition->location = condition_target;
branch_on_zero_instruction* branch_to_false = new branch_on_zero_instruction();
branch_to_false->operand = 3;
branch_to_false->branchTo = false_label;
instruction_sequence true_code = this->generate_code(if_statement->true_statement, context);
branch_instruction* branch_to_complete = new branch_instruction();
branch_to_complete->branchTo = complete_label;
instruction_sequence false_code = this->generate_code(if_statement->false_statement, context);
result.head = condition_code.head;
concatenate(condition_code, load_condition);
concatenate(load_condition, branch_to_false);
concatenate(branch_to_false, true_code);
concatenate(true_code, branch_to_complete);
concatenate(branch_to_complete, false_label);
concatenate(false_label, false_code);
concatenate(false_code, complete_label);
result.tail = complete_label;
return result;
}
instruction_sequence code_generator_impl::generate_code(return_statement_node* return_statement, code_generation_context* context)
{
instruction_sequence result;
int value_target = ++context->tempUsed;
context->expressionTarget = value_target;
instruction_sequence value_code = this->generate_code(return_statement->value, context);
// load r2, expression_target
load_instruction* load_value = new load_instruction();
load_value->destination_register = 2;
load_value->location = value_target;
// jump epilog
branch_instruction* branch_to_epilog = new branch_instruction();
branch_to_epilog->branchTo = context->epilog_label;
result.head = value_code.head;
concatenate(value_code, load_value);
concatenate(load_value, branch_to_epilog);
result.tail = branch_to_epilog;
return result;
}
instruction_sequence code_generator_impl::generate_code(call_statement_node* call_statement, code_generation_context* context)
{
instruction_sequence result;
return result;
}
instruction_sequence code_generator_impl::generate_code(expression_node* expression, code_generation_context* context)
{
switch (expression->get_expression_node_type())
{
case literal:
return this->generate_code((literal_node*)expression, context);
case variable:
return this->generate_code((identifier_node*)expression, context);
case call:
return this->generate_code((call_node*)expression, context);
case plus_node_type:
return this->generate_code((plus_node*)expression, context);
case minus_node_type:
return this->generate_code((minus_node*)expression, context);
default:
instruction_sequence result;
return result;
}
}
instruction_sequence code_generator_impl::generate_code(literal_node* literal, code_generation_context* context)
{
instruction_sequence result;
load_immediate_instruction* load_literal = new load_immediate_instruction();
load_literal->destination_register = 4;
load_literal->value = literal->value;
store_instruction* store = new store_instruction();
store->location = context->expressionTarget;
store->source_register = 4;
result.head = load_literal;
concatenate(load_literal, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(identifier_node* variable, code_generation_context* context)
{
instruction_sequence result;
return result;
}
instruction_sequence code_generator_impl::generate_code(call_node* call, code_generation_context* context)
{
instruction_sequence result;
int expressionTarget = context->expressionTarget;
int argumentTarget = ++context->tempUsed;
context->expressionTarget = argumentTarget;
instruction_sequence argument_code = this->generate_code(call->argument, context);
load_instruction* load_argument = new load_instruction();
load_argument->location = argumentTarget;
load_argument->destination_register = 1;
call_instruction* call_op = new call_instruction();
call_op->target = context->function_labels[call->function_name];
store_instruction* store = new store_instruction();
store->source_register = 2;
store->location = expressionTarget;
result.head = argument_code.head;
concatenate(argument_code, load_argument);
concatenate(load_argument, call_op);
concatenate(call_op, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(plus_node* plus, code_generation_context* context)
{
instruction_sequence result;
int expressionTarget = context->expressionTarget;
int left_target = ++context->tempUsed;
int right_target = ++context->tempUsed;
context->expressionTarget = left_target;
instruction_sequence left_code = this->generate_code(plus->left, context);
context->expressionTarget = right_target;
instruction_sequence right_code = this->generate_code(plus->left, context);
load_instruction* load_left = new load_instruction();
load_left->destination_register = 3;
load_left->location = left_target;
load_instruction* load_right = new load_instruction();
load_right->destination_register = 4;
load_right->location = right_target;
plus_instruction* plus_op = new plus_instruction();
plus_op->destination_register = 2;
plus_op->operand1 = 3;
plus_op->operand2 = 4;
store_instruction* store = new store_instruction();
store->source_register = 2;
store->location = expressionTarget;
result.head = left_code.head;
concatenate(left_code, right_code);
concatenate(right_code, load_left);
concatenate(load_left, load_right);
concatenate(load_right, plus_op);
concatenate(plus_op, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(minus_node* minus, code_generation_context* context)
{
instruction_sequence result;
int expressionTarget = context->expressionTarget;
int left_target = ++context->tempUsed;
int right_target = ++context->tempUsed;
context->expressionTarget = left_target;
instruction_sequence left_code = this->generate_code(minus->left, context);
context->expressionTarget = right_target;
instruction_sequence right_code = this->generate_code(minus->left, context);
load_instruction* load_left = new load_instruction();
load_left->destination_register = 3;
load_left->location = left_target;
load_instruction* load_right = new load_instruction();
load_right->destination_register = 4;
load_right->location = right_target;
minus_instruction* minus_op = new minus_instruction();
minus_op->destination_register = 2;
minus_op->operand1 = 3;
minus_op->operand2 = 4;
store_instruction* store = new store_instruction();
store->source_register = 2;
store->location = expressionTarget;
result.head = left_code.head;
concatenate(left_code, right_code);
concatenate(right_code, load_left);
concatenate(load_left, load_right);
concatenate(load_right, minus_op);
concatenate(minus_op, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(condition_node* condition, code_generation_context* context)
{
instruction_sequence result;
int variable_location = context->variables[condition->variable_name];
int literal = condition->value;
// load r3, variable_location
load_instruction* load_variable = new load_instruction();
load_variable->destination_register = 3;
load_variable->location = variable_location;
// loadimm r4, literal
load_immediate_instruction* load_literal = new load_immediate_instruction();
load_literal->destination_register = 4;
load_literal->value = literal;
// cmp r2, r3, r4
compare_instruction* compare = new compare_instruction();
compare->destination_register = 2;
compare->operand1 = 3;
compare->operand2 = 4;
// store target, r2
store_instruction* store = new store_instruction();
store->location = context->expressionTarget;
store->source_register = 2;
result.head = load_variable;
concatenate(load_variable, load_literal);
concatenate(load_literal, compare);
concatenate(compare, store);
result.tail = store;
return result;
}
code_generation_context::code_generation_context()
{
this->epilog_label = nullptr;
this->tempUsed = 0;
}
code_generation_context::~code_generation_context()
{
if (this->epilog_label != nullptr)
{
delete this->epilog_label;
}
}
<commit_msg>Fix a simple bug in CodeGenerator<commit_after>#include "code_generator.h"
#include <unordered_map>
using namespace std;
struct code_generation_context
{
code_generation_context();
~code_generation_context();
unordered_map<string, instruction_sequence> functions;
unordered_map<string, label_instruction*> function_labels;
unordered_map<string, int> variables;
label_instruction* epilog_label;
int tempUsed;
int expressionTarget;
};
class code_generator_impl
{
public:
code_generator_impl();
~code_generator_impl();
instruction_sequence generate_code(program_node* program);
private:
instruction_sequence generate_code(program_node* program, code_generation_context* context);
instruction_sequence generate_code(function_node* function, code_generation_context* context);
instruction_sequence generate_code(statement_node* statement, code_generation_context* context);
instruction_sequence generate_code(if_statement_node* if_statement, code_generation_context* context);
instruction_sequence generate_code(return_statement_node* return_statement, code_generation_context* context);
instruction_sequence generate_code(call_statement_node* call_statement, code_generation_context* context);
instruction_sequence generate_code(expression_node* expression_statement, code_generation_context* context);
instruction_sequence generate_code(literal_node* literal, code_generation_context* context);
instruction_sequence generate_code(identifier_node* variable, code_generation_context* context);
instruction_sequence generate_code(call_node* call, code_generation_context* context);
instruction_sequence generate_code(plus_node* plus, code_generation_context* context);
instruction_sequence generate_code(minus_node* minus, code_generation_context* context);
instruction_sequence generate_code(condition_node* condition, code_generation_context* context);
};
void concatenate(instruction* prev, instruction* next)
{
prev->next = next;
next->prev = prev;
}
void concatenate(instruction_sequence prev, instruction* next)
{
prev.tail->next = next;
next->prev = prev.tail;
}
void concatenate(instruction* prev, instruction_sequence next)
{
prev->next = next.head;
next.head->prev = prev;
}
void concatenate(instruction_sequence prev, instruction_sequence next)
{
prev.tail->next = next.head;
next.head->prev = prev.tail;
}
code_generator::code_generator()
{
this->impl = new code_generator_impl();
}
code_generator::~code_generator()
{
delete this->impl;
}
instruction_sequence code_generator::generate_code(program_node* program)
{
return this->impl->generate_code(program);
}
code_generator_impl::code_generator_impl()
{
}
code_generator_impl::~code_generator_impl()
{
}
instruction_sequence code_generator_impl::generate_code(program_node* program)
{
code_generation_context context;
return this->generate_code(program, &context);
}
instruction_sequence code_generator_impl::generate_code(program_node* program, code_generation_context* context)
{
instruction_sequence result;
function_node* function = program->function;
while (function != nullptr)
{
label_instruction* label = new label_instruction();
context->function_labels.insert(make_pair(function->function_name, label));
function = function->next_function;
}
function = program->function;
while (function != nullptr)
{
instruction_sequence function_body = this->generate_code(function, context);
context->functions.insert(make_pair(function->function_name, function_body));
function = function->next_function;
}
// TODO: Layout and linking
return result;
}
instruction_sequence code_generator_impl::generate_code(function_node* function, code_generation_context* context)
{
instruction_sequence result;
label_instruction* epilog_label = new label_instruction();
context->epilog_label = epilog_label;
context->tempUsed = 0;
if (function->argument_name != nullptr)
{
/* The stack pointer is pointing at empty, before it is the return address, before it is the argument! */
context->variables.insert(make_pair(function->argument_name, -2));
}
instruction_sequence statement_body = generate_code(function->statement, context);
// TODO: Generate prolog and epilog
return result;
}
instruction_sequence code_generator_impl::generate_code(statement_node* statement, code_generation_context* context)
{
switch (statement->get_statement_node_type())
{
case if_statement:
return this->generate_code((if_statement_node*)statement, context);
case return_statement:
return this->generate_code((return_statement_node*)statement, context);
case call_statement:
return this->generate_code((call_statement_node*)statement, context);
default:
instruction_sequence result;
return result;
}
}
instruction_sequence code_generator_impl::generate_code(if_statement_node* if_statement, code_generation_context* context)
{
instruction_sequence result;
int condition_target = ++context->tempUsed;
instruction_sequence condition_code = this->generate_code(if_statement->condition, context);
label_instruction* false_label = new label_instruction();
label_instruction* complete_label = new label_instruction();
// condition code
// load r3, condition_target
// beqz r3, false_label
// true code
// b complete
// false_label
// false code
// complete_label
load_instruction* load_condition = new load_instruction();
load_condition->destination_register = 3;
load_condition->location = condition_target;
branch_on_zero_instruction* branch_to_false = new branch_on_zero_instruction();
branch_to_false->operand = 3;
branch_to_false->branchTo = false_label;
instruction_sequence true_code = this->generate_code(if_statement->true_statement, context);
branch_instruction* branch_to_complete = new branch_instruction();
branch_to_complete->branchTo = complete_label;
instruction_sequence false_code = this->generate_code(if_statement->false_statement, context);
result.head = condition_code.head;
concatenate(condition_code, load_condition);
concatenate(load_condition, branch_to_false);
concatenate(branch_to_false, true_code);
concatenate(true_code, branch_to_complete);
concatenate(branch_to_complete, false_label);
concatenate(false_label, false_code);
concatenate(false_code, complete_label);
result.tail = complete_label;
return result;
}
instruction_sequence code_generator_impl::generate_code(return_statement_node* return_statement, code_generation_context* context)
{
instruction_sequence result;
int value_target = ++context->tempUsed;
context->expressionTarget = value_target;
instruction_sequence value_code = this->generate_code(return_statement->value, context);
// load r2, expression_target
load_instruction* load_value = new load_instruction();
load_value->destination_register = 2;
load_value->location = value_target;
// jump epilog
branch_instruction* branch_to_epilog = new branch_instruction();
branch_to_epilog->branchTo = context->epilog_label;
result.head = value_code.head;
concatenate(value_code, load_value);
concatenate(load_value, branch_to_epilog);
result.tail = branch_to_epilog;
return result;
}
instruction_sequence code_generator_impl::generate_code(call_statement_node* call_statement, code_generation_context* context)
{
instruction_sequence result;
return result;
}
instruction_sequence code_generator_impl::generate_code(expression_node* expression, code_generation_context* context)
{
switch (expression->get_expression_node_type())
{
case literal:
return this->generate_code((literal_node*)expression, context);
case variable:
return this->generate_code((identifier_node*)expression, context);
case call:
return this->generate_code((call_node*)expression, context);
case plus_node_type:
return this->generate_code((plus_node*)expression, context);
case minus_node_type:
return this->generate_code((minus_node*)expression, context);
default:
instruction_sequence result;
return result;
}
}
instruction_sequence code_generator_impl::generate_code(literal_node* literal, code_generation_context* context)
{
instruction_sequence result;
load_immediate_instruction* load_literal = new load_immediate_instruction();
load_literal->destination_register = 4;
load_literal->value = literal->value;
store_instruction* store = new store_instruction();
store->location = context->expressionTarget;
store->source_register = 4;
result.head = load_literal;
concatenate(load_literal, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(identifier_node* variable, code_generation_context* context)
{
instruction_sequence result;
return result;
}
instruction_sequence code_generator_impl::generate_code(call_node* call, code_generation_context* context)
{
instruction_sequence result;
int expressionTarget = context->expressionTarget;
int argumentTarget = ++context->tempUsed;
context->expressionTarget = argumentTarget;
instruction_sequence argument_code = this->generate_code(call->argument, context);
load_instruction* load_argument = new load_instruction();
load_argument->location = argumentTarget;
load_argument->destination_register = 1;
call_instruction* call_op = new call_instruction();
call_op->target = context->function_labels[call->function_name];
store_instruction* store = new store_instruction();
store->source_register = 2;
store->location = expressionTarget;
result.head = argument_code.head;
concatenate(argument_code, load_argument);
concatenate(load_argument, call_op);
concatenate(call_op, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(plus_node* plus, code_generation_context* context)
{
instruction_sequence result;
int expressionTarget = context->expressionTarget;
int left_target = ++context->tempUsed;
int right_target = ++context->tempUsed;
context->expressionTarget = left_target;
instruction_sequence left_code = this->generate_code(plus->left, context);
context->expressionTarget = right_target;
instruction_sequence right_code = this->generate_code(plus->left, context);
load_instruction* load_left = new load_instruction();
load_left->destination_register = 3;
load_left->location = left_target;
load_instruction* load_right = new load_instruction();
load_right->destination_register = 4;
load_right->location = right_target;
plus_instruction* plus_op = new plus_instruction();
plus_op->destination_register = 2;
plus_op->operand1 = 3;
plus_op->operand2 = 4;
store_instruction* store = new store_instruction();
store->source_register = 2;
store->location = expressionTarget;
result.head = left_code.head;
concatenate(left_code, right_code);
concatenate(right_code, load_left);
concatenate(load_left, load_right);
concatenate(load_right, plus_op);
concatenate(plus_op, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(minus_node* minus, code_generation_context* context)
{
instruction_sequence result;
int expressionTarget = context->expressionTarget;
int left_target = ++context->tempUsed;
int right_target = ++context->tempUsed;
context->expressionTarget = left_target;
instruction_sequence left_code = this->generate_code(minus->left, context);
context->expressionTarget = right_target;
instruction_sequence right_code = this->generate_code(minus->left, context);
load_instruction* load_left = new load_instruction();
load_left->destination_register = 3;
load_left->location = left_target;
load_instruction* load_right = new load_instruction();
load_right->destination_register = 4;
load_right->location = right_target;
minus_instruction* minus_op = new minus_instruction();
minus_op->destination_register = 2;
minus_op->operand1 = 3;
minus_op->operand2 = 4;
store_instruction* store = new store_instruction();
store->source_register = 2;
store->location = expressionTarget;
result.head = left_code.head;
concatenate(left_code, right_code);
concatenate(right_code, load_left);
concatenate(load_left, load_right);
concatenate(load_right, minus_op);
concatenate(minus_op, store);
result.tail = store;
return result;
}
instruction_sequence code_generator_impl::generate_code(condition_node* condition, code_generation_context* context)
{
instruction_sequence result;
int variable_location = context->variables[condition->variable_name];
int literal = condition->value;
// load r3, variable_location
load_instruction* load_variable = new load_instruction();
load_variable->destination_register = 3;
load_variable->location = variable_location;
// loadimm r4, literal
load_immediate_instruction* load_literal = new load_immediate_instruction();
load_literal->destination_register = 4;
load_literal->value = literal;
// cmp r2, r3, r4
compare_instruction* compare = new compare_instruction();
compare->destination_register = 2;
compare->operand1 = 3;
compare->operand2 = 4;
// store target, r2
store_instruction* store = new store_instruction();
store->location = context->expressionTarget;
store->source_register = 2;
result.head = load_variable;
concatenate(load_variable, load_literal);
concatenate(load_literal, compare);
concatenate(compare, store);
result.tail = store;
return result;
}
code_generation_context::code_generation_context()
{
this->epilog_label = nullptr;
this->tempUsed = 0;
}
code_generation_context::~code_generation_context()
{
if (this->epilog_label != nullptr)
{
delete this->epilog_label;
}
}
<|endoftext|> |
<commit_before>// Screen.hh for fluxbox
// Copyright (c) 2001 Henrik Kinnunen ([email protected])
//
// Screen.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef _SCREEN_HH_
#define _SCREEN_HH_
#include <X11/Xlib.h>
#include <X11/Xresource.h>
#ifdef TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else // !TIME_WITH_SYS_TIME
# ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
# else // !HAVE_SYS_TIME_H
# include <time.h>
# endif // HAVE_SYS_TIME_H
#endif // TIME_WITH_SYS_TIME
#include <stdio.h>
#include "Theme.hh"
// forward declaration
class BScreen;
#ifndef _BASEDISPLAY_HH_
#include "BaseDisplay.hh"
#endif
#ifndef _CONFIGMENU_HH_
#include "Configmenu.hh"
#endif
#ifndef _ICON_HH_
#include "Icon.hh"
#endif
#ifndef _LINKEDLIST_HH_
#include "LinkedList.hh"
#endif
#ifndef _NETIZEN_HH_
#include "Netizen.hh"
#endif
#ifndef _ROOTMENU_HH_
#include "Rootmenu.hh"
#endif
#ifndef _TIMER_HH_
#include "Timer.hh"
#endif
#ifndef _WORKSPACE_HH_
#include "Workspace.hh"
#endif
#ifndef _WORKSPACEMENU_HH_
#include "Workspacemenu.hh"
#endif
#ifndef _FLUXBOX_HH_
#include "fluxbox.hh"
#endif
#ifdef SLIT
# include "Slit.hh"
#endif // SLIT
class BScreen : public ScreenInfo {
public:
BScreen(Fluxbox *, int);
~BScreen(void);
inline const Bool &isToolbarOnTop(void) const
{ return resource.toolbar_on_top; }
inline const Bool &doToolbarAutoHide(void) const
{ return resource.toolbar_auto_hide; }
inline const Bool &isSloppyFocus(void) const
{ return resource.sloppy_focus; }
inline const Bool &isSemiSloppyFocus(void) const
{ return resource.semi_sloppy_focus; }
inline const Bool &isRootColormapInstalled(void) const
{ return root_colormap_installed; }
inline const Bool &isScreenManaged(void) const { return managed; }
inline const Bool &isTabRotateVertical(void) const
{ return resource.tab_rotate_vertical; }
inline const Bool &isSloppyWindowGrouping(void) const
{ return resource.sloppy_window_grouping; }
inline const Bool &doAutoRaise(void) const { return resource.auto_raise; }
inline const Bool &doImageDither(void) const
{ return resource.image_dither; }
inline const Bool &doOrderedDither(void) const
{ return resource.ordered_dither; }
inline const Bool &doOpaqueMove(void) const { return resource.opaque_move; }
inline const Bool &doFullMax(void) const { return resource.full_max; }
inline const Bool &doFocusNew(void) const { return resource.focus_new; }
inline const Bool &doFocusLast(void) const { return resource.focus_last; }
inline const GC &getOpGC() const { return theme->getOpGC(); }
inline const BColor *getBorderColor(void) { return &theme->getBorderColor(); }
inline BImageControl *getImageControl(void) { return image_control; }
inline Rootmenu *getRootmenu(void) { return rootmenu; }
#ifdef SLIT
inline const Bool &isSlitOnTop(void) const { return resource.slit_on_top; }
inline const Bool &doSlitAutoHide(void) const
{ return resource.slit_auto_hide; }
inline Slit *getSlit(void) { return slit; }
inline const int &getSlitPlacement(void) const
{ return resource.slit_placement; }
inline const int &getSlitDirection(void) const
{ return resource.slit_direction; }
inline void saveSlitPlacement(int p) { resource.slit_placement = p; }
inline void saveSlitDirection(int d) { resource.slit_direction = d; }
inline void saveSlitOnTop(Bool t) { resource.slit_on_top = t; }
inline void saveSlitAutoHide(Bool t) { resource.slit_auto_hide = t; }
#endif // SLIT
inline Toolbar *getToolbar(void) { return toolbar; }
inline Workspace *getWorkspace(int w) { return workspacesList->find(w); }
inline Workspace *getCurrentWorkspace(void) { return current_workspace; }
inline Workspacemenu *getWorkspacemenu(void) { return workspacemenu; }
inline const unsigned int getHandleWidth(void) const
{ return theme->getHandleWidth(); }
inline const unsigned int getBevelWidth(void) const
{ return theme->getBevelWidth(); }
inline const unsigned int getFrameWidth(void) const
{ return theme->getFrameWidth(); }
inline const unsigned int getBorderWidth(void) const
{ return theme->getBorderWidth(); }
inline const unsigned int getBorderWidth2x(void) const
{ return theme->getBorderWidth()*2; }
inline const int getCurrentWorkspaceID()
{ return current_workspace->getWorkspaceID(); }
inline const int getCount(void) { return workspacesList->count(); }
inline const int getIconCount(void) { return iconList->count(); }
inline LinkedList<FluxboxWindow> *getIconList(void) { return iconList; }
inline const int &getNumberOfWorkspaces(void) const
{ return resource.workspaces; }
inline const int &getToolbarPlacement(void) const
{ return resource.toolbar_placement; }
inline const int &getToolbarWidthPercent(void) const
{ return resource.toolbar_width_percent; }
inline const int &getPlacementPolicy(void) const
{ return resource.placement_policy; }
inline const int &getEdgeSnapThreshold(void) const
{ return resource.edge_snap_threshold; }
inline const int &getRowPlacementDirection(void) const
{ return resource.row_direction; }
inline const int &getColPlacementDirection(void) const
{ return resource.col_direction; }
inline const unsigned int &getTabWidth(void) const
{ return resource.tab_width; }
inline const unsigned int &getTabHeight(void) const
{ return resource.tab_height; }
inline const int getTabPlacement(void)
{ return resource.tab_placement; }
inline const int getTabAlignment(void)
{ return resource.tab_alignment; }
inline void setRootColormapInstalled(Bool r) { root_colormap_installed = r; }
inline void saveSloppyFocus(Bool s) { resource.sloppy_focus = s; }
inline void saveSemiSloppyFocus(Bool s) { resource.semi_sloppy_focus = s; }
inline void saveAutoRaise(Bool a) { resource.auto_raise = a; }
inline void saveWorkspaces(int w) { resource.workspaces = w; }
inline void saveToolbarOnTop(Bool r) { resource.toolbar_on_top = r; }
inline void saveToolbarAutoHide(Bool r) { resource.toolbar_auto_hide = r; }
inline void saveToolbarWidthPercent(int w)
{ resource.toolbar_width_percent = w; }
inline void saveToolbarPlacement(int p) { resource.toolbar_placement = p; }
inline void savePlacementPolicy(int p) { resource.placement_policy = p; }
inline void saveRowPlacementDirection(int d) { resource.row_direction = d; }
inline void saveColPlacementDirection(int d) { resource.col_direction = d; }
inline void saveEdgeSnapThreshold(int t)
{ resource.edge_snap_threshold = t; }
inline void saveImageDither(Bool d) { resource.image_dither = d; }
inline void saveOpaqueMove(Bool o) { resource.opaque_move = o; }
inline void saveFullMax(Bool f) { resource.full_max = f; }
inline void saveFocusNew(Bool f) { resource.focus_new = f; }
inline void saveFocusLast(Bool f) { resource.focus_last = f; }
inline void saveTabWidth(unsigned int w) { resource.tab_width = w; }
inline void saveTabHeight(unsigned int h) { resource.tab_height = h; }
inline void saveTabPlacement(unsigned int p) { resource.tab_placement = p; }
inline void saveTabAlignment(unsigned int a) { resource.tab_alignment = a; }
inline void saveTabRotateVertical(Bool r)
{ resource.tab_rotate_vertical = r; }
inline void saveSloppyWindowGrouping(Bool s)
{ resource.sloppy_window_grouping = s; }
inline void iconUpdate(void) { iconmenu->update(); }
inline Iconmenu *getIconmenu(void) { return iconmenu; }
#ifdef HAVE_STRFTIME
inline char *getStrftimeFormat(void) { return resource.strftime_format; }
void saveStrftimeFormat(char *);
#else // !HAVE_STRFTIME
inline int getDateFormat(void) { return resource.date_format; }
inline void saveDateFormat(int f) { resource.date_format = f; }
inline Bool isClock24Hour(void) { return resource.clock24hour; }
inline void saveClock24Hour(Bool c) { resource.clock24hour = c; }
#endif // HAVE_STRFTIME
inline Theme::WindowStyle *getWindowStyle(void) { return &theme->getWindowStyle(); }
inline Theme::MenuStyle *getMenuStyle(void) { return &theme->getMenuStyle(); }
inline Theme::ToolbarStyle *getToolbarStyle(void) { return &theme->getToolbarStyle(); }
FluxboxWindow *getIcon(int);
int addWorkspace(void);
int removeLastWorkspace(void);
//scroll workspaces
void nextWorkspace();
void prevWorkspace();
void removeWorkspaceNames(void);
void updateWorkspaceNamesAtom(void);
void addWorkspaceName(char *);
void addNetizen(Netizen *);
void removeNetizen(Window);
void addIcon(FluxboxWindow *);
void removeIcon(FluxboxWindow *);
void getNameOfWorkspace(int, char **);
void changeWorkspaceID(int);
void raiseWindows(Window *, int);
void reassociateWindow(FluxboxWindow *, int, Bool);
void prevFocus(void);
void nextFocus(void);
void raiseFocus(void);
void reconfigure(void);
void rereadMenu(void);
void shutdown(void);
void showPosition(int, int);
void showGeometry(unsigned int, unsigned int);
void hideGeometry(void);
void updateNetizenCurrentWorkspace(void);
void updateNetizenWorkspaceCount(void);
void updateNetizenWindowFocus(void);
void updateNetizenWindowAdd(Window, unsigned long);
void updateNetizenWindowDel(Window);
void updateNetizenConfigNotify(XEvent *);
void updateNetizenWindowRaise(Window);
void updateNetizenWindowLower(Window);
enum { RowSmartPlacement = 1, ColSmartPlacement, CascadePlacement, LeftRight,
RightLeft, TopBottom, BottomTop };
enum { LeftJustify = 1, RightJustify, CenterJustify };
enum { RoundBullet = 1, TriangleBullet, SquareBullet, NoBullet };
enum { Restart = 1, RestartOther, Exit, Shutdown, Execute, Reconfigure,
WindowShade, WindowIconify, WindowMaximize, WindowClose, WindowRaise,
WindowLower, WindowStick, WindowKill, SetStyle, WindowTab};
private:
Theme *theme;
Bool root_colormap_installed, managed, geom_visible;
GC opGC;
Pixmap geom_pixmap;
Window geom_window;
Fluxbox *fluxbox;
BImageControl *image_control;
Configmenu *configmenu;
Iconmenu *iconmenu;
Rootmenu *rootmenu;
LinkedList<Rootmenu> *rootmenuList;
LinkedList<Netizen> *netizenList;
LinkedList<FluxboxWindow> *iconList;
#ifdef SLIT
Slit *slit;
#endif // SLIT
Toolbar *toolbar;
Workspace *current_workspace;
Workspacemenu *workspacemenu;
unsigned int geom_w, geom_h;
unsigned long event_mask;
LinkedList<char> *workspaceNames;
LinkedList<Workspace> *workspacesList;
struct resource {
Bool toolbar_on_top, toolbar_auto_hide, sloppy_focus, auto_raise,
auto_edge_balance, image_dither, ordered_dither, opaque_move, full_max,
focus_new, focus_last, tab_rotate_vertical, semi_sloppy_focus,
sloppy_window_grouping;
int workspaces, toolbar_placement, toolbar_width_percent, placement_policy,
edge_snap_threshold, row_direction, col_direction;
unsigned int tab_placement, tab_alignment, tab_width, tab_height;
#ifdef SLIT
Bool slit_on_top, slit_auto_hide;
int slit_placement, slit_direction;
#endif // SLIT
#ifdef HAVE_STRFTIME
char *strftime_format;
#else // !HAVE_STRFTIME
Bool clock24hour;
int date_format;
#endif // HAVE_STRFTIME
} resource;
protected:
Bool parseMenuFile(FILE *, Rootmenu *);
bool readDatabaseTexture(char *, char *, BTexture *, unsigned long);
bool readDatabaseColor(char *, char *, BColor *, unsigned long);
void readDatabaseFontSet(char *, char *, XFontSet *);
XFontSet createFontSet(char *);
void readDatabaseFont(char *, char *, XFontStruct **);
void InitMenu(void);
};
#endif // _SCREEN_HH_
<commit_msg>Added maximize over slit resource<commit_after>// Screen.hh for fluxbox
// Copyright (c) 2001 Henrik Kinnunen ([email protected])
//
// Screen.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef _SCREEN_HH_
#define _SCREEN_HH_
#include <X11/Xlib.h>
#include <X11/Xresource.h>
#ifdef TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else // !TIME_WITH_SYS_TIME
# ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
# else // !HAVE_SYS_TIME_H
# include <time.h>
# endif // HAVE_SYS_TIME_H
#endif // TIME_WITH_SYS_TIME
#include <stdio.h>
#include "Theme.hh"
// forward declaration
class BScreen;
#ifndef _BASEDISPLAY_HH_
#include "BaseDisplay.hh"
#endif
#ifndef _CONFIGMENU_HH_
#include "Configmenu.hh"
#endif
#ifndef _ICON_HH_
#include "Icon.hh"
#endif
#ifndef _LINKEDLIST_HH_
#include "LinkedList.hh"
#endif
#ifndef _NETIZEN_HH_
#include "Netizen.hh"
#endif
#ifndef _ROOTMENU_HH_
#include "Rootmenu.hh"
#endif
#ifndef _TIMER_HH_
#include "Timer.hh"
#endif
#ifndef _WORKSPACE_HH_
#include "Workspace.hh"
#endif
#ifndef _WORKSPACEMENU_HH_
#include "Workspacemenu.hh"
#endif
#ifndef _FLUXBOX_HH_
#include "fluxbox.hh"
#endif
#ifdef SLIT
# include "Slit.hh"
#endif // SLIT
class BScreen : public ScreenInfo {
public:
BScreen(Fluxbox *, int);
~BScreen(void);
inline const Bool &isToolbarOnTop(void) const
{ return resource.toolbar_on_top; }
inline const Bool &doToolbarAutoHide(void) const
{ return resource.toolbar_auto_hide; }
inline const Bool &isSloppyFocus(void) const
{ return resource.sloppy_focus; }
inline const Bool &isSemiSloppyFocus(void) const
{ return resource.semi_sloppy_focus; }
inline const Bool &isRootColormapInstalled(void) const
{ return root_colormap_installed; }
inline const Bool &isScreenManaged(void) const { return managed; }
inline const Bool &isTabRotateVertical(void) const
{ return resource.tab_rotate_vertical; }
inline const Bool &isSloppyWindowGrouping(void) const
{ return resource.sloppy_window_grouping; }
inline const Bool &doAutoRaise(void) const { return resource.auto_raise; }
inline const Bool &doImageDither(void) const
{ return resource.image_dither; }
inline const Bool &doOrderedDither(void) const
{ return resource.ordered_dither; }
inline const Bool &doMaxOverSlit(void) const { return resource.max_over_slit; }
inline const Bool &doOpaqueMove(void) const { return resource.opaque_move; }
inline const Bool &doFullMax(void) const { return resource.full_max; }
inline const Bool &doFocusNew(void) const { return resource.focus_new; }
inline const Bool &doFocusLast(void) const { return resource.focus_last; }
inline const GC &getOpGC() const { return theme->getOpGC(); }
inline const BColor *getBorderColor(void) { return &theme->getBorderColor(); }
inline BImageControl *getImageControl(void) { return image_control; }
inline Rootmenu *getRootmenu(void) { return rootmenu; }
#ifdef SLIT
inline const Bool &isSlitOnTop(void) const { return resource.slit_on_top; }
inline const Bool &doSlitAutoHide(void) const
{ return resource.slit_auto_hide; }
inline Slit *getSlit(void) { return slit; }
inline const int &getSlitPlacement(void) const
{ return resource.slit_placement; }
inline const int &getSlitDirection(void) const
{ return resource.slit_direction; }
inline void saveSlitPlacement(int p) { resource.slit_placement = p; }
inline void saveSlitDirection(int d) { resource.slit_direction = d; }
inline void saveSlitOnTop(Bool t) { resource.slit_on_top = t; }
inline void saveSlitAutoHide(Bool t) { resource.slit_auto_hide = t; }
#endif // SLIT
inline Toolbar *getToolbar(void) { return toolbar; }
inline Workspace *getWorkspace(int w) { return workspacesList->find(w); }
inline Workspace *getCurrentWorkspace(void) { return current_workspace; }
inline Workspacemenu *getWorkspacemenu(void) { return workspacemenu; }
inline const unsigned int getHandleWidth(void) const
{ return theme->getHandleWidth(); }
inline const unsigned int getBevelWidth(void) const
{ return theme->getBevelWidth(); }
inline const unsigned int getFrameWidth(void) const
{ return theme->getFrameWidth(); }
inline const unsigned int getBorderWidth(void) const
{ return theme->getBorderWidth(); }
inline const unsigned int getBorderWidth2x(void) const
{ return theme->getBorderWidth()*2; }
inline const int getCurrentWorkspaceID()
{ return current_workspace->getWorkspaceID(); }
inline const int getCount(void) { return workspacesList->count(); }
inline const int getIconCount(void) { return iconList->count(); }
inline LinkedList<FluxboxWindow> *getIconList(void) { return iconList; }
inline const int &getNumberOfWorkspaces(void) const
{ return resource.workspaces; }
inline const int &getToolbarPlacement(void) const
{ return resource.toolbar_placement; }
inline const int &getToolbarWidthPercent(void) const
{ return resource.toolbar_width_percent; }
inline const int &getPlacementPolicy(void) const
{ return resource.placement_policy; }
inline const int &getEdgeSnapThreshold(void) const
{ return resource.edge_snap_threshold; }
inline const int &getRowPlacementDirection(void) const
{ return resource.row_direction; }
inline const int &getColPlacementDirection(void) const
{ return resource.col_direction; }
inline const unsigned int &getTabWidth(void) const
{ return resource.tab_width; }
inline const unsigned int &getTabHeight(void) const
{ return resource.tab_height; }
inline const int getTabPlacement(void)
{ return resource.tab_placement; }
inline const int getTabAlignment(void)
{ return resource.tab_alignment; }
inline void setRootColormapInstalled(Bool r) { root_colormap_installed = r; }
inline void saveSloppyFocus(Bool s) { resource.sloppy_focus = s; }
inline void saveSemiSloppyFocus(Bool s) { resource.semi_sloppy_focus = s; }
inline void saveAutoRaise(Bool a) { resource.auto_raise = a; }
inline void saveWorkspaces(int w) { resource.workspaces = w; }
inline void saveToolbarOnTop(Bool r) { resource.toolbar_on_top = r; }
inline void saveToolbarAutoHide(Bool r) { resource.toolbar_auto_hide = r; }
inline void saveToolbarWidthPercent(int w)
{ resource.toolbar_width_percent = w; }
inline void saveToolbarPlacement(int p) { resource.toolbar_placement = p; }
inline void savePlacementPolicy(int p) { resource.placement_policy = p; }
inline void saveRowPlacementDirection(int d) { resource.row_direction = d; }
inline void saveColPlacementDirection(int d) { resource.col_direction = d; }
inline void saveEdgeSnapThreshold(int t)
{ resource.edge_snap_threshold = t; }
inline void saveImageDither(Bool d) { resource.image_dither = d; }
inline void saveMaxOverSlit(Bool m) { resource.max_over_slit = m; }
inline void saveOpaqueMove(Bool o) { resource.opaque_move = o; }
inline void saveFullMax(Bool f) { resource.full_max = f; }
inline void saveFocusNew(Bool f) { resource.focus_new = f; }
inline void saveFocusLast(Bool f) { resource.focus_last = f; }
inline void saveTabWidth(unsigned int w) { resource.tab_width = w; }
inline void saveTabHeight(unsigned int h) { resource.tab_height = h; }
inline void saveTabPlacement(unsigned int p) { resource.tab_placement = p; }
inline void saveTabAlignment(unsigned int a) { resource.tab_alignment = a; }
inline void saveTabRotateVertical(Bool r)
{ resource.tab_rotate_vertical = r; }
inline void saveSloppyWindowGrouping(Bool s)
{ resource.sloppy_window_grouping = s; }
inline void iconUpdate(void) { iconmenu->update(); }
inline Iconmenu *getIconmenu(void) { return iconmenu; }
#ifdef HAVE_STRFTIME
inline char *getStrftimeFormat(void) { return resource.strftime_format; }
void saveStrftimeFormat(char *);
#else // !HAVE_STRFTIME
inline int getDateFormat(void) { return resource.date_format; }
inline void saveDateFormat(int f) { resource.date_format = f; }
inline Bool isClock24Hour(void) { return resource.clock24hour; }
inline void saveClock24Hour(Bool c) { resource.clock24hour = c; }
#endif // HAVE_STRFTIME
inline Theme::WindowStyle *getWindowStyle(void) { return &theme->getWindowStyle(); }
inline Theme::MenuStyle *getMenuStyle(void) { return &theme->getMenuStyle(); }
inline Theme::ToolbarStyle *getToolbarStyle(void) { return &theme->getToolbarStyle(); }
FluxboxWindow *getIcon(int);
int addWorkspace(void);
int removeLastWorkspace(void);
//scroll workspaces
void nextWorkspace();
void prevWorkspace();
void removeWorkspaceNames(void);
void updateWorkspaceNamesAtom(void);
void addWorkspaceName(char *);
void addNetizen(Netizen *);
void removeNetizen(Window);
void addIcon(FluxboxWindow *);
void removeIcon(FluxboxWindow *);
void getNameOfWorkspace(int, char **);
void changeWorkspaceID(int);
void raiseWindows(Window *, int);
void reassociateWindow(FluxboxWindow *, int, Bool);
void prevFocus(void);
void nextFocus(void);
void raiseFocus(void);
void reconfigure(void);
void rereadMenu(void);
void shutdown(void);
void showPosition(int, int);
void showGeometry(unsigned int, unsigned int);
void hideGeometry(void);
void updateNetizenCurrentWorkspace(void);
void updateNetizenWorkspaceCount(void);
void updateNetizenWindowFocus(void);
void updateNetizenWindowAdd(Window, unsigned long);
void updateNetizenWindowDel(Window);
void updateNetizenConfigNotify(XEvent *);
void updateNetizenWindowRaise(Window);
void updateNetizenWindowLower(Window);
enum { RowSmartPlacement = 1, ColSmartPlacement, CascadePlacement, LeftRight,
RightLeft, TopBottom, BottomTop };
enum { LeftJustify = 1, RightJustify, CenterJustify };
enum { RoundBullet = 1, TriangleBullet, SquareBullet, NoBullet };
enum { Restart = 1, RestartOther, Exit, Shutdown, Execute, Reconfigure,
WindowShade, WindowIconify, WindowMaximize, WindowClose, WindowRaise,
WindowLower, WindowStick, WindowKill, SetStyle, WindowTab};
private:
Theme *theme;
Bool root_colormap_installed, managed, geom_visible;
GC opGC;
Pixmap geom_pixmap;
Window geom_window;
Fluxbox *fluxbox;
BImageControl *image_control;
Configmenu *configmenu;
Iconmenu *iconmenu;
Rootmenu *rootmenu;
LinkedList<Rootmenu> *rootmenuList;
LinkedList<Netizen> *netizenList;
LinkedList<FluxboxWindow> *iconList;
#ifdef SLIT
Slit *slit;
#endif // SLIT
Toolbar *toolbar;
Workspace *current_workspace;
Workspacemenu *workspacemenu;
unsigned int geom_w, geom_h;
unsigned long event_mask;
LinkedList<char> *workspaceNames;
LinkedList<Workspace> *workspacesList;
struct resource {
Bool toolbar_on_top, toolbar_auto_hide, sloppy_focus, auto_raise,
auto_edge_balance, image_dither, ordered_dither, opaque_move, full_max,
focus_new, focus_last, max_over_slit, tab_rotate_vertical, semi_sloppy_focus,
sloppy_window_grouping;
int workspaces, toolbar_placement, toolbar_width_percent, placement_policy,
edge_snap_threshold, row_direction, col_direction;
unsigned int tab_placement, tab_alignment, tab_width, tab_height;
#ifdef SLIT
Bool slit_on_top, slit_auto_hide;
int slit_placement, slit_direction;
#endif // SLIT
#ifdef HAVE_STRFTIME
char *strftime_format;
#else // !HAVE_STRFTIME
Bool clock24hour;
int date_format;
#endif // HAVE_STRFTIME
} resource;
protected:
Bool parseMenuFile(FILE *, Rootmenu *);
bool readDatabaseTexture(char *, char *, BTexture *, unsigned long);
bool readDatabaseColor(char *, char *, BColor *, unsigned long);
void readDatabaseFontSet(char *, char *, XFontSet *);
XFontSet createFontSet(char *);
void readDatabaseFont(char *, char *, XFontStruct **);
void InitMenu(void);
};
#endif // _SCREEN_HH_
<|endoftext|> |
<commit_before>// Copyright 2019 Netherlands eScience Center and Netherlands Institute for Radio Astronomy (ASTRON)
//
// 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 <ReadData.hpp>
#include <ArgumentList.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <gtest/gtest.h>
std::string fileName;
int main(int argc, char * argv[])
{
testing::InitGoogleTest(&argc, argv);
isa::utils::ArgumentList arguments(argc, argv);
try
{
fileName = arguments.getSwitchArgument<std::string>("-zapped_channels_file");
}
catch ( isa::utils::EmptyCommandLine & err )
{
std::cerr << "Required command line parameters:" << std::endl;
std::cerr << "\t-zapped_channels_file <string>" << std::endl;
}
return RUN_ALL_TESTS();
}
TEST(ZappedChannels, FileError)
{
AstroData::Observation observation;
std::vector<unsigned int> channels;
std::string wrongFileName = "zappred_channels.conf";
ASSERT_THROW(AstroData::readZappedChannels(observation, wrongFileName, channels), AstroData::FileError);
}
TEST(ZappedChannels, MatchingChannels)
{
AstroData::Observation observation;
std::vector<unsigned int> channels;
observation.setFrequencyRange(1, 1024, 0.0f, 0.0f);
channels.resize(observation.getNrChannels());
AstroData::readZappedChannels(observation, fileName, channels);
EXPECT_EQ(channels.at(4), 1);
EXPECT_EQ(channels.at(39), 1);
EXPECT_EQ(channels.at(7), 1);
EXPECT_EQ(channels.at(19), 1);
EXPECT_EQ(channels.at(1023), 1);
EXPECT_EQ(channels.at(0), 1);
EXPECT_NE(channels.at(45), 1);
EXPECT_NE(channels.at(128), 1);
}
<commit_msg>Added empty lines.<commit_after>// Copyright 2019 Netherlands eScience Center and Netherlands Institute for Radio Astronomy (ASTRON)
//
// 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 <ReadData.hpp>
#include <ArgumentList.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <gtest/gtest.h>
std::string fileName;
int main(int argc, char * argv[])
{
testing::InitGoogleTest(&argc, argv);
isa::utils::ArgumentList arguments(argc, argv);
try
{
fileName = arguments.getSwitchArgument<std::string>("-zapped_channels_file");
}
catch ( isa::utils::EmptyCommandLine & err )
{
std::cerr << std::endl;
std::cerr << "Required command line parameters:" << std::endl;
std::cerr << "\t-zapped_channels_file <string>" << std::endl;
std::cerr << std::endl;
}
return RUN_ALL_TESTS();
}
TEST(ZappedChannels, FileError)
{
AstroData::Observation observation;
std::vector<unsigned int> channels;
std::string wrongFileName = "zappred_channels.conf";
ASSERT_THROW(AstroData::readZappedChannels(observation, wrongFileName, channels), AstroData::FileError);
}
TEST(ZappedChannels, MatchingChannels)
{
AstroData::Observation observation;
std::vector<unsigned int> channels;
observation.setFrequencyRange(1, 1024, 0.0f, 0.0f);
channels.resize(observation.getNrChannels());
AstroData::readZappedChannels(observation, fileName, channels);
EXPECT_EQ(channels.at(4), 1);
EXPECT_EQ(channels.at(39), 1);
EXPECT_EQ(channels.at(7), 1);
EXPECT_EQ(channels.at(19), 1);
EXPECT_EQ(channels.at(1023), 1);
EXPECT_EQ(channels.at(0), 1);
EXPECT_NE(channels.at(45), 1);
EXPECT_NE(channels.at(128), 1);
}
<|endoftext|> |
<commit_before>#include <QFileInfo>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/target.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
#include "OutputPane.h"
#include "OutputParser.h"
#include "PaneWidget.h"
#include "TestModel.h"
#include "ParseState.h"
#include "TestMark.h"
using namespace QtcGtest::Internal;
OutputPane::OutputPane(QObject *parent) :
IOutputPane(parent),
parser_ (new OutputParser),
model_ (new TestModel),
state_ (new ParseState),
widget_ (NULL),
totalsLabel_ (new QLabel),
disabledLabel_ (new QLabel),
togglePopupButton_ (new QToolButton),
togglePassedButton_ (new QToolButton)
{
totalsLabel_->setMargin(5);
togglePopupButton_->setCheckable (true);
togglePopupButton_->setChecked (true);
togglePopupButton_->setToolTip (tr ("Auto popup pane"));
togglePopupButton_->setIcon(QIcon(QLatin1String(":/images/popup.ico")));
togglePassedButton_->setCheckable (true);
togglePassedButton_->setChecked (true);
togglePassedButton_->setToolTip (tr ("Show passed tests"));
togglePassedButton_->setIcon(QIcon(QLatin1String(":/images/passed.ico")));
connect (model_.data (), &TestModel::newError, this, &OutputPane::addMark);
}
OutputPane::~OutputPane()
{
delete togglePassedButton_;
delete togglePopupButton_;
delete disabledLabel_;
delete totalsLabel_;
delete parser_;
delete state_;
}
QWidget *OutputPane::outputWidget(QWidget *parent)
{
Q_ASSERT (model_ != NULL);
widget_ = new PaneWidget (model_, parent); // Can be only 1?
connect (widget_.data (), SIGNAL (viewClicked (const QModelIndex&)),
this, SLOT (handleViewClicked (const QModelIndex&)));
connect (togglePassedButton_, SIGNAL (clicked (bool)),
widget_.data (), SLOT (showPassed (bool)));
return widget_.data ();
}
QList<QWidget *> OutputPane::toolBarWidgets() const
{
QList<QWidget*> widgets;
widgets << togglePopupButton_ << togglePassedButton_ << totalsLabel_ << disabledLabel_;
return widgets;
}
QString OutputPane::displayName() const
{
return tr ("Google Test");
}
int OutputPane::priorityInStatusBar() const
{
return 10;
}
void OutputPane::clearContents()
{
qDeleteAll (marks);
marks.clear ();
model_->clear ();
totalsLabel_->clear ();
disabledLabel_->clear ();
}
void OutputPane::visibilityChanged(bool visible)
{
}
void OutputPane::setFocus()
{
if (!widget_.isNull ())
{
widget_->setFocus ();
}
}
bool OutputPane::hasFocus() const
{
if (!widget_.isNull ())
{
return widget_->hasFocus ();
}
return false;
}
bool OutputPane::canFocus() const
{
return (!widget_.isNull ());
}
bool OutputPane::canNavigate() const
{
return true;
}
bool OutputPane::canNext() const
{
Q_ASSERT (model_ != NULL);
// Do not update value because Creator checks it BEFORE it can actually be updated.
return (model_->errorCount () > 0);
}
bool OutputPane::canPrevious() const
{
Q_ASSERT (model_ != NULL);
// Do not update value because Creator checks it BEFORE it can actually be updated.
return (model_->errorCount () > 0);
}
void OutputPane::goToNext()
{
Q_ASSERT (!widget_.isNull ());
QModelIndex currentIndex = widget_->testModelIndex (widget_->currentIndex ());
showError (model_->nextError (currentIndex));
}
void OutputPane::goToPrev()
{
Q_ASSERT (!widget_.isNull ());
QModelIndex currentIndex = widget_->testModelIndex (widget_->currentIndex ());
showError (model_->previousError (currentIndex));
}
void OutputPane::setCurrentIndex(const QModelIndex &index)
{
widget_->setCurrentIndex (widget_->proxyIndex(index));
}
void OutputPane::showError(const QModelIndex &errorIndex)
{
if (!errorIndex.isValid ())
{
return;
}
widget_->setCurrentIndex (widget_->proxyIndex(errorIndex));
int row = errorIndex.row ();
QString file = errorIndex.sibling (row, TestModel::ColumnFile).data ().toString ();
int line = errorIndex.sibling (row, TestModel::ColumnLine).data ().toInt ();
Core::EditorManager::openEditorAt (file, line);
}
void OutputPane::handleViewClicked(const QModelIndex &index)
{
Q_ASSERT (index.isValid());
QModelIndex sourceIndex = widget_->testModelIndex (index);
TestModel::Type type = model_->getType (sourceIndex);
if (type == TestModel::TypeDetailError)
{
showError (sourceIndex);
}
else if (type == TestModel::TypeDetail)
{
QModelIndex previousError = model_->previousError (sourceIndex);
if (previousError.isValid () && previousError.parent ().row () == sourceIndex.parent ().row ())
{
showError (model_->previousError (sourceIndex));
}
}
}
void OutputPane::addMark(const QModelIndex &index)
{
auto row = index.row ();
auto file = index.sibling (row, TestModel::ColumnFile).data ().toString ();
auto line = index.sibling (row, TestModel::ColumnLine).data ().toInt ();
marks << new TestMark (QPersistentModelIndex(index), file, line, *this);
}
void OutputPane::handleRunStart(ProjectExplorer::RunControl *control)
{
state_->reset ();
model_->clear ();
totalsLabel_->clear ();
disabledLabel_->clear ();
state_->projectFiles = control->project ()->files (ProjectExplorer::Project::SourceFiles);
connect (control, SIGNAL (appendMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )),
this, SLOT (parseMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )));
}
void OutputPane::handleRunFinish (ProjectExplorer::RunControl *control)
{
if (state_->isGoogleTestRun)
{
widget_->spanColumns ();
totalsLabel_->setText (tr ("Total: passed %1 of %2 (%3 ms).").arg (
state_->passedTotalCount).arg (
state_->passedTotalCount +
state_->failedTotalCount).arg (state_->totalTime));
disabledLabel_->setText(tr ("Disabled tests: %1.").arg (state_->disabledCount));
if (togglePopupButton_->isChecked())
{
popup (WithFocus);
}
}
disconnect (control, SIGNAL (appendMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )),
this, SLOT (parseMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )));
}
void OutputPane::parseMessage(ProjectExplorer::RunControl *control, const QString &msg, Utils::OutputFormat format)
{
Q_UNUSED (control);
if (!(format == Utils::StdOutFormat || format == Utils::StdOutFormatSameLine))
{
return;
}
QStringList lines = msg.split (QLatin1Char ('\n'));
foreach (const QString& line, lines)
{
if (line.trimmed ().isEmpty ())
{
continue;
}
if (!state_->isGoogleTestRun)
{
state_->isGoogleTestRun = parser_->isGoogleTestRun (line);
if (!state_->isGoogleTestRun) {
continue;
}
}
parser_->parseMessage (line, *model_, *state_);
}
}
<commit_msg>Check variables for existence.<commit_after>#include <QFileInfo>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/target.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
#include "OutputPane.h"
#include "OutputParser.h"
#include "PaneWidget.h"
#include "TestModel.h"
#include "ParseState.h"
#include "TestMark.h"
using namespace QtcGtest::Internal;
OutputPane::OutputPane(QObject *parent) :
IOutputPane(parent),
parser_ (new OutputParser),
model_ (new TestModel),
state_ (new ParseState),
widget_ (NULL),
totalsLabel_ (new QLabel),
disabledLabel_ (new QLabel),
togglePopupButton_ (new QToolButton),
togglePassedButton_ (new QToolButton)
{
totalsLabel_->setMargin(5);
togglePopupButton_->setCheckable (true);
togglePopupButton_->setChecked (true);
togglePopupButton_->setToolTip (tr ("Auto popup pane"));
togglePopupButton_->setIcon(QIcon(QLatin1String(":/images/popup.ico")));
togglePassedButton_->setCheckable (true);
togglePassedButton_->setChecked (true);
togglePassedButton_->setToolTip (tr ("Show passed tests"));
togglePassedButton_->setIcon(QIcon(QLatin1String(":/images/passed.ico")));
connect (model_.data (), &TestModel::newError, this, &OutputPane::addMark);
}
OutputPane::~OutputPane()
{
delete togglePassedButton_;
delete togglePopupButton_;
delete disabledLabel_;
delete totalsLabel_;
delete parser_;
delete state_;
}
QWidget *OutputPane::outputWidget(QWidget *parent)
{
Q_ASSERT (model_ != NULL);
widget_ = new PaneWidget (model_, parent); // Can be only 1?
connect (widget_.data (), SIGNAL (viewClicked (const QModelIndex&)),
this, SLOT (handleViewClicked (const QModelIndex&)));
connect (togglePassedButton_, SIGNAL (clicked (bool)),
widget_.data (), SLOT (showPassed (bool)));
return widget_.data ();
}
QList<QWidget *> OutputPane::toolBarWidgets() const
{
QList<QWidget*> widgets;
widgets << togglePopupButton_ << togglePassedButton_ << totalsLabel_ << disabledLabel_;
return widgets;
}
QString OutputPane::displayName() const
{
return tr ("Google Test");
}
int OutputPane::priorityInStatusBar() const
{
return 10;
}
void OutputPane::clearContents()
{
qDeleteAll (marks);
marks.clear ();
model_->clear ();
totalsLabel_->clear ();
disabledLabel_->clear ();
}
void OutputPane::visibilityChanged(bool visible)
{
}
void OutputPane::setFocus()
{
if (!widget_.isNull ())
{
widget_->setFocus ();
}
}
bool OutputPane::hasFocus() const
{
if (!widget_.isNull ())
{
return widget_->hasFocus ();
}
return false;
}
bool OutputPane::canFocus() const
{
return (!widget_.isNull ());
}
bool OutputPane::canNavigate() const
{
return true;
}
bool OutputPane::canNext() const
{
Q_ASSERT (model_ != NULL);
// Do not update value because Creator checks it BEFORE it can actually be updated.
return (model_->errorCount () > 0);
}
bool OutputPane::canPrevious() const
{
Q_ASSERT (model_ != NULL);
// Do not update value because Creator checks it BEFORE it can actually be updated.
return (model_->errorCount () > 0);
}
void OutputPane::goToNext()
{
Q_ASSERT (!widget_.isNull ());
QModelIndex currentIndex = widget_->testModelIndex (widget_->currentIndex ());
showError (model_->nextError (currentIndex));
}
void OutputPane::goToPrev()
{
Q_ASSERT (!widget_.isNull ());
QModelIndex currentIndex = widget_->testModelIndex (widget_->currentIndex ());
showError (model_->previousError (currentIndex));
}
void OutputPane::setCurrentIndex(const QModelIndex &index)
{
widget_->setCurrentIndex (widget_->proxyIndex(index));
}
void OutputPane::showError(const QModelIndex &errorIndex)
{
if (!errorIndex.isValid ())
{
return;
}
widget_->setCurrentIndex (widget_->proxyIndex(errorIndex));
int row = errorIndex.row ();
QString file = errorIndex.sibling (row, TestModel::ColumnFile).data ().toString ();
int line = errorIndex.sibling (row, TestModel::ColumnLine).data ().toInt ();
Core::EditorManager::openEditorAt (file, line);
}
void OutputPane::handleViewClicked(const QModelIndex &index)
{
Q_ASSERT (index.isValid());
QModelIndex sourceIndex = widget_->testModelIndex (index);
TestModel::Type type = model_->getType (sourceIndex);
if (type == TestModel::TypeDetailError)
{
showError (sourceIndex);
}
else if (type == TestModel::TypeDetail)
{
QModelIndex previousError = model_->previousError (sourceIndex);
if (previousError.isValid () && previousError.parent ().row () == sourceIndex.parent ().row ())
{
showError (model_->previousError (sourceIndex));
}
}
}
void OutputPane::addMark(const QModelIndex &index)
{
auto row = index.row ();
auto file = index.sibling (row, TestModel::ColumnFile).data ().toString ();
auto line = index.sibling (row, TestModel::ColumnLine).data ().toInt ();
marks << new TestMark (QPersistentModelIndex(index), file, line, *this);
}
void OutputPane::handleRunStart(ProjectExplorer::RunControl *control)
{
state_->reset ();
model_->clear ();
totalsLabel_->clear ();
disabledLabel_->clear ();
if (control && control->project ()) {
state_->projectFiles = control->project ()->files (ProjectExplorer::Project::SourceFiles);
}
connect (control, SIGNAL (appendMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )),
this, SLOT (parseMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )));
}
void OutputPane::handleRunFinish (ProjectExplorer::RunControl *control)
{
if (state_->isGoogleTestRun)
{
widget_->spanColumns ();
totalsLabel_->setText (tr ("Total: passed %1 of %2 (%3 ms).").arg (
state_->passedTotalCount).arg (
state_->passedTotalCount +
state_->failedTotalCount).arg (state_->totalTime));
disabledLabel_->setText(tr ("Disabled tests: %1.").arg (state_->disabledCount));
if (togglePopupButton_->isChecked())
{
popup (WithFocus);
}
}
disconnect (control, SIGNAL (appendMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )),
this, SLOT (parseMessage(ProjectExplorer::RunControl *, const QString &, Utils::OutputFormat )));
}
void OutputPane::parseMessage(ProjectExplorer::RunControl *control, const QString &msg, Utils::OutputFormat format)
{
Q_UNUSED (control);
if (!(format == Utils::StdOutFormat || format == Utils::StdOutFormatSameLine))
{
return;
}
QStringList lines = msg.split (QLatin1Char ('\n'));
foreach (const QString& line, lines)
{
if (line.trimmed ().isEmpty ())
{
continue;
}
if (!state_->isGoogleTestRun)
{
state_->isGoogleTestRun = parser_->isGoogleTestRun (line);
if (!state_->isGoogleTestRun) {
continue;
}
}
parser_->parseMessage (line, *model_, *state_);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ignoreZiZu_ja_JP.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2003-04-28 16:53:19 $
*
* 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): _______________________________________
*
*
************************************************************************/
// prevent internal compiler error with MSVC6SP3
#include <utility>
#define TRANSLITERATION_ZiZu_ja_JP
#include <transliteration_Ignore.hxx>
namespace com { namespace sun { namespace star { namespace i18n {
sal_Unicode
ignoreZiZu_ja_JP_translator (const sal_Unicode c)
{
switch (c) {
case 0x30C2: // KATAKANA LETTER DI
return 0x30B8; // KATAKANA LETTER ZI
case 0x3062: // HIRAGANA LETTER DI
return 0x3058; // HIRAGANA LETTER ZI
case 0x30C5: // KATAKANA LETTER DU
return 0x30BA; // KATAKANA LETTER ZU
case 0x3065: // HIRAGANA LETTER DU
return 0x305A; // HIRAGANA LETTER ZU
}
return c;
}
ignoreZiZu_ja_JP::ignoreZiZu_ja_JP()
{
func = ignoreZiZu_ja_JP_translator;
table = 0;
map = 0;
transliterationName = "ignoreZiZu_ja_JP";
implementationName = "com.sun.star.i18n.Transliteration.ignoreZiZu_ja_JP";
}
} } } }
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.190); FILE MERGED 2005/09/05 17:47:58 rt 1.6.190.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ignoreZiZu_ja_JP.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:32:27 $
*
* 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
*
************************************************************************/
// prevent internal compiler error with MSVC6SP3
#include <utility>
#define TRANSLITERATION_ZiZu_ja_JP
#include <transliteration_Ignore.hxx>
namespace com { namespace sun { namespace star { namespace i18n {
sal_Unicode
ignoreZiZu_ja_JP_translator (const sal_Unicode c)
{
switch (c) {
case 0x30C2: // KATAKANA LETTER DI
return 0x30B8; // KATAKANA LETTER ZI
case 0x3062: // HIRAGANA LETTER DI
return 0x3058; // HIRAGANA LETTER ZI
case 0x30C5: // KATAKANA LETTER DU
return 0x30BA; // KATAKANA LETTER ZU
case 0x3065: // HIRAGANA LETTER DU
return 0x305A; // HIRAGANA LETTER ZU
}
return c;
}
ignoreZiZu_ja_JP::ignoreZiZu_ja_JP()
{
func = ignoreZiZu_ja_JP_translator;
table = 0;
map = 0;
transliterationName = "ignoreZiZu_ja_JP";
implementationName = "com.sun.star.i18n.Transliteration.ignoreZiZu_ja_JP";
}
} } } }
<|endoftext|> |
<commit_before>#include <iostream>
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
bool dostring(lua_State* L, const char* str)
{
if (luaL_loadbuffer(L, str, std::strlen(str), str) || lua_pcall(L, 0, 0, 0))
{
const char* a = lua_tostring(L, -1);
std::cout << a << "\n";
lua_pop(L, 1);
return true;
}
return false;
}
#include <luabind/luabind.hpp>
#include <boost/any.hpp>
template<class T>
struct convert_any
{
static void convert(lua_State* L, const boost::any& a)
{
typename luabind::detail::default_policy::template generate_converter<T, luabind::detail::cpp_to_lua>::type conv;
conv.apply(L, *boost::any_cast<T>(&a));
}
};
std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converters;
template<class T>
void register_any_converter()
{
any_converters[&typeid(T)] = convert_any<T>::convert;
}
namespace luabind
{
namespace converters
{
yes_t is_user_defined(by_value<boost::any>);
yes_t is_user_defined(by_const_reference<boost::any>);
void convert_cpp_to_lua(lua_State* L, const boost::any& a)
{
typedef void(*conv_t)(lua_State* L, const boost::any&);
conv_t conv = any_converters[&a.type()];
conv(L, a);
}
}
}
boost::any f(bool b)
{
if (b) return "foobar";
else return "3.5f";
}
int main()
{
register_any_converter<int>();
register_any_converter<float>();
register_any_converter<const char*>();
register_any_converter<std::string>();
lua_State* L = lua_open();
lua_baselibopen(L);
using namespace luabind;
open(L);
module(L)
[
def("f", &f)
];
dostring(L, "print( f(true) )");
dostring(L, "print( f(false) )");
dostring(L, "function update(p) print(p) end");
boost::any param = std::string("foo");
luabind::call_function<void>(L, "update", param);
lua_close(L);
}
<commit_msg>fixed any_converter example<commit_after>#include <iostream>
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
bool dostring(lua_State* L, const char* str)
{
if (luaL_loadbuffer(L, str, std::strlen(str), str) || lua_pcall(L, 0, 0, 0))
{
const char* a = lua_tostring(L, -1);
std::cout << a << "\n";
lua_pop(L, 1);
return true;
}
return false;
}
#include <luabind/luabind.hpp>
#include <luabind/detail/convert_to_lua.hpp>
#include <boost/any.hpp>
template<class T>
struct convert_any
{
static void convert(lua_State* L, const boost::any& a)
{
luabind::detail::convert_to_lua(L, *boost::any_cast<T>(&a));
}
};
std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converters;
template<class T>
void register_any_converter()
{
any_converters[&typeid(T)] = convert_any<T>::convert;
}
namespace luabind
{
namespace converters
{
yes_t is_user_defined(by_value<boost::any>);
yes_t is_user_defined(by_const_reference<boost::any>);
void convert_cpp_to_lua(lua_State* L, const boost::any& a)
{
typedef void(*conv_t)(lua_State* L, const boost::any&);
conv_t conv = any_converters[&a.type()];
conv(L, a);
}
}
}
boost::any f(bool b)
{
if (b) return "foobar";
else return "3.5f";
}
int main()
{
register_any_converter<int>();
register_any_converter<float>();
register_any_converter<const char*>();
register_any_converter<std::string>();
lua_State* L = lua_open();
#if LUA_VERSION_NUM >= 501
luaL_openlibs(L);
#else
lua_baselibopen(L);
#endif
using namespace luabind;
open(L);
module(L)
[
def("f", &f)
];
dostring(L, "print( f(true) )");
dostring(L, "print( f(false) )");
dostring(L, "function update(p) print(p) end");
boost::any param = std::string("foo");
luabind::call_function<void>(L, "update", param);
lua_close(L);
}
<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "combine_masks_process.h"
#include <processes/helpers/image/format.h>
#include <processes/helpers/image/operators.h>
#include <processes/helpers/image/pixtypes.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <numeric>
#include <string>
/**
* \file combine_masks_process.cxx
*
* \brief Implementation of the mask combination process.
*/
namespace vistk
{
class combine_masks_process::priv
{
public:
priv();
~priv();
typedef port_t tag_t;
typedef std::vector<tag_t> tags_t;
binop_func_t const combine;
port_type_t const port_type;
tags_t tags;
static port_t const port_mask_prefix;
static port_t const port_mask;
};
process::port_t const combine_masks_process::priv::port_mask_prefix = process::port_t("mask/");
process::port_t const combine_masks_process::priv::port_mask = process::port_t("mask");
combine_masks_process
::combine_masks_process(config_t const& config)
: process(config)
, d(new priv)
{
ensure_inputs_are_valid(false);
port_flags_t required;
required.insert(flag_required);
declare_output_port(priv::port_mask, boost::make_shared<port_info>(
d->port_type,
required,
port_description_t("The combined mask.")));
}
combine_masks_process
::~combine_masks_process()
{
}
void
combine_masks_process
::_init()
{
if (!d->combine)
{
static std::string const reason = "A combine function for the "
"mask pixtype could not be found";
throw invalid_configuration_exception(name(), reason);
}
if (!d->tags.size())
{
static std::string const reason = "There must be at least one mask to combine";
throw invalid_configuration_exception(name(), reason);
}
process::_init();
}
void
combine_masks_process
::_step()
{
std::vector<datum_t> data;
datum_t dat;
BOOST_FOREACH (priv::tag_t const& tag, d->tags)
{
datum_t const idat = grab_datum_from_port(priv::port_mask_prefix + tag);
switch (idat->type())
{
case datum::data:
/// \todo Check image sizes.
data.push_back(dat);
break;
case datum::complete:
mark_process_as_complete();
break;
case datum::invalid:
case datum::error:
{
datum::error_t const err_string = datum::error_t("Error on input tag \'" + tag + "\'");
dat = datum::error_datum(err_string);
break;
}
case datum::empty:
default:
break;
}
data.push_back(idat);
}
if (!dat)
{
dat = std::accumulate(data.begin(), data.end(), datum_t(), d->combine);
}
push_datum_to_port(priv::port_mask, dat);
process::_step();
}
process::port_info_t
combine_masks_process
::_input_port_info(port_t const& port)
{
if (boost::starts_with(port, priv::port_mask_prefix))
{
priv::tag_t const tag = port.substr(priv::port_mask_prefix.size());
priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);
if (i == d->tags.end())
{
d->tags.push_back(tag);
port_flags_t required;
required.insert(flag_required);
declare_input_port(port, boost::make_shared<port_info>(
d->port_type,
required,
port_description_t("The \'" + tag + "\' mask.")));
}
}
return process::_input_port_info(port);
}
combine_masks_process::priv
::priv()
: combine(or_for_pixtype(pixtypes::pixtype_byte()))
, port_type(port_type_for_pixtype(pixtypes::pixtype_byte(), pixfmts::pixfmt_mask()))
{
}
combine_masks_process::priv
::~priv()
{
}
}
<commit_msg>Delay marking as complete<commit_after>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "combine_masks_process.h"
#include <processes/helpers/image/format.h>
#include <processes/helpers/image/operators.h>
#include <processes/helpers/image/pixtypes.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <numeric>
#include <string>
/**
* \file combine_masks_process.cxx
*
* \brief Implementation of the mask combination process.
*/
namespace vistk
{
class combine_masks_process::priv
{
public:
priv();
~priv();
typedef port_t tag_t;
typedef std::vector<tag_t> tags_t;
binop_func_t const combine;
port_type_t const port_type;
tags_t tags;
static port_t const port_mask_prefix;
static port_t const port_mask;
};
process::port_t const combine_masks_process::priv::port_mask_prefix = process::port_t("mask/");
process::port_t const combine_masks_process::priv::port_mask = process::port_t("mask");
combine_masks_process
::combine_masks_process(config_t const& config)
: process(config)
, d(new priv)
{
ensure_inputs_are_valid(false);
port_flags_t required;
required.insert(flag_required);
declare_output_port(priv::port_mask, boost::make_shared<port_info>(
d->port_type,
required,
port_description_t("The combined mask.")));
}
combine_masks_process
::~combine_masks_process()
{
}
void
combine_masks_process
::_init()
{
if (!d->combine)
{
static std::string const reason = "A combine function for the "
"mask pixtype could not be found";
throw invalid_configuration_exception(name(), reason);
}
if (!d->tags.size())
{
static std::string const reason = "There must be at least one mask to combine";
throw invalid_configuration_exception(name(), reason);
}
process::_init();
}
void
combine_masks_process
::_step()
{
std::vector<datum_t> data;
bool complete = false;
datum_t dat;
BOOST_FOREACH (priv::tag_t const& tag, d->tags)
{
datum_t const idat = grab_datum_from_port(priv::port_mask_prefix + tag);
switch (idat->type())
{
case datum::data:
/// \todo Check image sizes.
data.push_back(dat);
break;
case datum::complete:
complete = true;
break;
case datum::invalid:
case datum::error:
{
datum::error_t const err_string = datum::error_t("Error on input tag \'" + tag + "\'");
dat = datum::error_datum(err_string);
break;
}
case datum::empty:
default:
break;
}
data.push_back(idat);
}
if (complete)
{
mark_process_as_complete();
dat = datum::complete_datum();
}
if (!dat)
{
dat = std::accumulate(data.begin(), data.end(), datum_t(), d->combine);
}
push_datum_to_port(priv::port_mask, dat);
process::_step();
}
process::port_info_t
combine_masks_process
::_input_port_info(port_t const& port)
{
if (boost::starts_with(port, priv::port_mask_prefix))
{
priv::tag_t const tag = port.substr(priv::port_mask_prefix.size());
priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);
if (i == d->tags.end())
{
d->tags.push_back(tag);
port_flags_t required;
required.insert(flag_required);
declare_input_port(port, boost::make_shared<port_info>(
d->port_type,
required,
port_description_t("The \'" + tag + "\' mask.")));
}
}
return process::_input_port_info(port);
}
combine_masks_process::priv
::priv()
: combine(or_for_pixtype(pixtypes::pixtype_byte()))
, port_type(port_type_for_pixtype(pixtypes::pixtype_byte(), pixfmts::pixfmt_mask()))
{
}
combine_masks_process::priv
::~priv()
{
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: [email protected] *
* *
*******************************************************************************/
#define CGOGN_CORE_DLL_EXPORT
#define CGOGN_CORE_UTILS_LOGGER_OUTPUT_CPP_
#include <iostream>
#include <limits>
#include <cgogn/core/utils/logger_output.h>
#include <termcolor.hpp>
namespace cgogn
{
namespace logger
{
void NullOutput::process_entry(const LogEntry&)
{}
ConsoleOutput::ConsoleOutput() : LoggerOutput()
{}
void ConsoleOutput::process_entry(const LogEntry& e)
{
if (e)
{
std::ostream& o = (e.get_level() <= LogLevel::LogLevel_DEPRECATED) ? std::cout : std::cerr;
internal::add_color(o,e.get_level()) << termcolor::bold;
o << "[" << internal::loglevel_to_string(e.get_level()) << "]" << termcolor::reset;
if (!e.get_sender().empty())
{
o << '(' << termcolor::magenta << e.get_sender() << termcolor::reset << ')';
}
o << ": " << e.get_message_str();
if (e.get_level() >= LogLevel::LogLevel_DEBUG && !e.get_fileinfo().empty())
{
o << " (file " << termcolor::magenta;
o << e.get_fileinfo() << termcolor::reset << ')';
}
o << '.' << std::endl;
}
}
FileOutput::FileOutput(const std::string& filename) : LoggerOutput()
,filename_(filename)
{
out_.open(filename, std::ios_base::out | std::ios_base::trunc);
}
void FileOutput::process_entry(const LogEntry& e)
{
if (out_.good())
{
out_ << "[" << internal::loglevel_to_string(e.get_level()) << "]";
if (!e.get_sender().empty())
{
out_ << '(' << e.get_sender() << ')';
}
out_ << ": " << e.get_message_str();
if (!e.get_fileinfo().empty())
out_ << " (file " << e.get_fileinfo() << ')';
out_ << '.' << std::endl;
}
}
} // namespace logger
} // namespace cgogn
<commit_msg>removed the "." added automatically by the logger.<commit_after>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: [email protected] *
* *
*******************************************************************************/
#define CGOGN_CORE_DLL_EXPORT
#define CGOGN_CORE_UTILS_LOGGER_OUTPUT_CPP_
#include <iostream>
#include <limits>
#include <cgogn/core/utils/logger_output.h>
#include <termcolor.hpp>
namespace cgogn
{
namespace logger
{
void NullOutput::process_entry(const LogEntry&)
{}
ConsoleOutput::ConsoleOutput() : LoggerOutput()
{}
void ConsoleOutput::process_entry(const LogEntry& e)
{
if (e)
{
std::ostream& o = (e.get_level() <= LogLevel::LogLevel_DEPRECATED) ? std::cout : std::cerr;
internal::add_color(o,e.get_level()) << termcolor::bold;
o << "[" << internal::loglevel_to_string(e.get_level()) << "]" << termcolor::reset;
if (!e.get_sender().empty())
{
o << '(' << termcolor::magenta << e.get_sender() << termcolor::reset << ')';
}
o << ": " << e.get_message_str();
if (e.get_level() >= LogLevel::LogLevel_DEBUG && !e.get_fileinfo().empty())
{
o << " (file " << termcolor::magenta;
o << e.get_fileinfo() << termcolor::reset << ')';
}
o << std::endl;
}
}
FileOutput::FileOutput(const std::string& filename) : LoggerOutput()
,filename_(filename)
{
out_.open(filename, std::ios_base::out | std::ios_base::trunc);
}
void FileOutput::process_entry(const LogEntry& e)
{
if (out_.good())
{
out_ << "[" << internal::loglevel_to_string(e.get_level()) << "]";
if (!e.get_sender().empty())
{
out_ << '(' << e.get_sender() << ')';
}
out_ << ": " << e.get_message_str();
if (!e.get_fileinfo().empty())
out_ << " (file " << e.get_fileinfo() << ')';
out_ << std::endl;
}
}
} // namespace logger
} // namespace cgogn
<|endoftext|> |
<commit_before>/*!
@file
@author Albert Semenov
@date 09/2008
@module
*//*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_ResourceManager.h"
#include "MyGUI_LanguageManager.h"
#include "MyGUI_XmlDocument.h"
namespace MyGUI
{
const std::string XML_TYPE("Language");
MYGUI_INSTANCE_IMPLEMENT(LanguageManager);
void LanguageManager::initialise()
{
MYGUI_ASSERT(false == mIsInitialise, INSTANCE_TYPE_NAME << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << INSTANCE_TYPE_NAME);
ResourceManager::getInstance().registerLoadXmlDelegate(XML_TYPE) = newDelegate(this, &LanguageManager::_load);
mCurrentLanguage = mMapFile.end();
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully initialized");
mIsInitialise = true;
}
void LanguageManager::shutdown()
{
if (false == mIsInitialise) return;
MYGUI_LOG(Info, "* Shutdown: " << INSTANCE_TYPE_NAME);
ResourceManager::getInstance().unregisterLoadXmlDelegate(XML_TYPE);
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully shutdown");
mIsInitialise = false;
}
bool LanguageManager::load(const std::string & _file, const std::string & _group)
{
return ResourceManager::getInstance()._loadImplement(_file, _group, true, XML_TYPE, INSTANCE_TYPE_NAME);
}
void LanguageManager::_load(xml::ElementPtr _node, const std::string & _file, Version _version)
{
std::string def;
// берем детей и крутимся, основной цикл
xml::ElementEnumerator root = _node->getElementEnumerator();
while (root.next(XML_TYPE)) {
// парсим атрибуты
root->findAttribute("default", def);
// берем детей и крутимся
xml::ElementEnumerator info = root->getElementEnumerator();
while (info.next("Info")) {
// парсим атрибуты
std::string name(info->findAttribute("name"));
// доюавляем в карту пользователя
if (name.empty()) {
xml::ElementEnumerator source_info = info->getElementEnumerator();
while (source_info.next("Source")) {
loadLanguage(source_info->getContent(), ResourceManager::getInstance().getResourceGroup(), true);
};
}
// добавляем в карту языков
else {
MapListString::iterator lang = mMapFile.find(name);
if (lang == mMapFile.end()) {
lang = mMapFile.insert(std::make_pair(name, VectorString())).first;
}
xml::ElementEnumerator source_info = info->getElementEnumerator();
while (source_info.next("Source")) {
lang->second.push_back(source_info->getContent());
};
}
};
};
if ( ! def.empty()) setCurrentLanguage(def);
}
bool LanguageManager::setCurrentLanguage(const std::string & _name)
{
mCurrentLanguage = mMapFile.find(_name);
if (mCurrentLanguage == mMapFile.end()) {
MYGUI_LOG(Error, "Language '" << _name << "' is not found");
return false;
}
loadLanguage(mCurrentLanguage->second, ResourceManager::getInstance().getResourceGroup());
eventChangeLanguage(mCurrentLanguage->first);
return true;
}
void LanguageManager::loadLanguage(const VectorString & _list, const std::string & _group)
{
mMapLanguage.clear();
for (VectorString::const_iterator iter=_list.begin(); iter!=_list.end(); ++iter) {
loadLanguage(*iter, _group);
}
}
bool LanguageManager::loadLanguage(const std::string & _file, const std::string & _group, bool _user)
{
if (!_group.empty()) {
if (!helper::isFileExist(_file, _group)) {
MYGUI_LOG(Error, "file '" << _file << "' not found in group'" << _group << "'");
return false;
}
Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingletonPtr()->openResource(_file, _group);
// проверяем на сигнатуру utf8
uint32 sign = 0;
stream->read((void*)&sign, 3);
if (sign != 0x00BFBBEF) {
MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format");
return false;
}
_loadLanguage(stream, _user);
return true;
}
std::ifstream stream(_file.c_str());
if (false == stream.is_open()) {
MYGUI_LOG(Error, "error open file '" << _file << "'");
return false;
}
// проверяем на сигнатуру utf8
uint32 sign = 0;
stream.read((char*)&sign, 3);
if (sign != 0x00BFBBEF) {
MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format");
stream.close();
return false;
}
_loadLanguage(stream, _user);
stream.close();
return true;
}
void LanguageManager::_loadLanguage(std::ifstream & _stream, bool _user)
{
std::string read;
while (false == _stream.eof()) {
std::getline(_stream, read);
if (read.empty()) continue;
size_t pos = read.find_first_of(" \t");
if (_user) {
if (pos == std::string::npos) mUserMapLanguage[read] = "";
else mUserMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
else {
if (pos == std::string::npos) mMapLanguage[read] = "";
else mMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
};
}
void LanguageManager::_loadLanguage(const Ogre::DataStreamPtr& stream, bool _user)
{
std::string read;
while (false == stream->eof()) {
read = stream->getLine (false);
if (read.empty()) continue;
size_t pos = read.find_first_of(" \t");
if (_user) {
if (pos == std::string::npos) mUserMapLanguage[read] = "";
else mUserMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
else {
if (pos == std::string::npos) mMapLanguage[read] = "";
else mMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
};
}
Ogre::UTFString LanguageManager::replaceTags(const Ogre::UTFString & _line)
{
// вот хз, что быстрее, итераторы или математика указателей,
// для непонятно какого размера одного символа UTF8
Ogre::UTFString line(_line);
if (mMapLanguage.empty() && mUserMapLanguage.empty()) return _line;
Ogre::UTFString::iterator end = line.end();
for (Ogre::UTFString::iterator iter=line.begin(); iter!=end; ++iter) {
if (*iter == '#') {
++iter;
if (iter == end) {
return line;
}
else {
if (*iter != '{') continue;
Ogre::UTFString::iterator iter2 = iter;
++iter2;
while (true) {
if (iter2 == end) return line;
if (*iter2 == '}') {
size_t start = iter - line.begin();
size_t len = (iter2 - line.begin()) - start - 1;
const Ogre::UTFString & tag = line.substr(start + 1, len);
bool find = true;
MapLanguageString::iterator replace = mMapLanguage.find(tag);
if (replace == mMapLanguage.end()) {
replace = mUserMapLanguage.find(tag);
find = replace != mUserMapLanguage.end();
}
if (!find) {
iter = line.insert(iter, '#') + size_t(len + 2);
end = line.end();
break;
}
else {
iter = line.erase(iter - size_t(1), iter2 + size_t(1));
size_t pos = iter - line.begin();
line.insert(pos, replace->second);
iter = line.begin() + pos + replace->second.length();
end = line.end();
if (iter == end) return line;
break;
}
iter = iter2;
break;
}
++iter2;
};
}
}
}
return line;
}
Ogre::UTFString LanguageManager::getTag(const Ogre::UTFString & _tag)
{
MapLanguageString::iterator iter = mMapLanguage.find(_tag);
if (iter == mMapLanguage.end()) {
iter = mUserMapLanguage.find(_tag);
if (iter != mUserMapLanguage.end()) return iter->second;
return _tag;
}
return iter->second;
}
} // namespace MyGUI
<commit_msg>fix LanguageManager<commit_after>/*!
@file
@author Albert Semenov
@date 09/2008
@module
*//*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_ResourceManager.h"
#include "MyGUI_LanguageManager.h"
#include "MyGUI_XmlDocument.h"
namespace MyGUI
{
const std::string XML_TYPE("Language");
MYGUI_INSTANCE_IMPLEMENT(LanguageManager);
void LanguageManager::initialise()
{
MYGUI_ASSERT(false == mIsInitialise, INSTANCE_TYPE_NAME << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << INSTANCE_TYPE_NAME);
ResourceManager::getInstance().registerLoadXmlDelegate(XML_TYPE) = newDelegate(this, &LanguageManager::_load);
mCurrentLanguage = mMapFile.end();
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully initialized");
mIsInitialise = true;
}
void LanguageManager::shutdown()
{
if (false == mIsInitialise) return;
MYGUI_LOG(Info, "* Shutdown: " << INSTANCE_TYPE_NAME);
ResourceManager::getInstance().unregisterLoadXmlDelegate(XML_TYPE);
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully shutdown");
mIsInitialise = false;
}
bool LanguageManager::load(const std::string & _file, const std::string & _group)
{
return ResourceManager::getInstance()._loadImplement(_file, _group, true, XML_TYPE, INSTANCE_TYPE_NAME);
}
void LanguageManager::_load(xml::ElementPtr _node, const std::string & _file, Version _version)
{
std::string def;
// берем детей и крутимся, основной цикл
xml::ElementEnumerator root = _node->getElementEnumerator();
while (root.next(XML_TYPE)) {
// парсим атрибуты
root->findAttribute("default", def);
// берем детей и крутимся
xml::ElementEnumerator info = root->getElementEnumerator();
while (info.next("Info")) {
// парсим атрибуты
std::string name(info->findAttribute("name"));
// доюавляем в карту пользователя
if (name.empty()) {
xml::ElementEnumerator source_info = info->getElementEnumerator();
while (source_info.next("Source")) {
loadLanguage(source_info->getContent(), ResourceManager::getInstance().getResourceGroup(), true);
};
}
// добавляем в карту языков
else {
MapListString::iterator lang = mMapFile.find(name);
if (lang == mMapFile.end()) {
lang = mMapFile.insert(std::make_pair(name, VectorString())).first;
}
xml::ElementEnumerator source_info = info->getElementEnumerator();
while (source_info.next("Source")) {
lang->second.push_back(source_info->getContent());
};
}
};
};
if ( ! def.empty()) setCurrentLanguage(def);
}
bool LanguageManager::setCurrentLanguage(const std::string & _name)
{
mCurrentLanguage = mMapFile.find(_name);
if (mCurrentLanguage == mMapFile.end()) {
MYGUI_LOG(Error, "Language '" << _name << "' is not found");
return false;
}
loadLanguage(mCurrentLanguage->second, ResourceManager::getInstance().getResourceGroup());
eventChangeLanguage(mCurrentLanguage->first);
return true;
}
void LanguageManager::loadLanguage(const VectorString & _list, const std::string & _group)
{
mMapLanguage.clear();
for (VectorString::const_iterator iter=_list.begin(); iter!=_list.end(); ++iter) {
loadLanguage(*iter, _group);
}
}
bool LanguageManager::loadLanguage(const std::string & _file, const std::string & _group, bool _user)
{
if (!_group.empty()) {
if (!helper::isFileExist(_file, _group)) {
MYGUI_LOG(Error, "file '" << _file << "' not found in group'" << _group << "'");
return false;
}
Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingletonPtr()->openResource(_file, _group);
// проверяем на сигнатуру utf8
uint32 sign = 0;
stream->read((void*)&sign, 3);
if (sign != 0x00BFBBEF) {
MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format");
return false;
}
_loadLanguage(stream, _user);
return true;
}
std::ifstream stream(_file.c_str());
if (false == stream.is_open()) {
MYGUI_LOG(Error, "error open file '" << _file << "'");
return false;
}
// проверяем на сигнатуру utf8
uint32 sign = 0;
stream.read((char*)&sign, 3);
if (sign != 0x00BFBBEF) {
MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format");
stream.close();
return false;
}
_loadLanguage(stream, _user);
stream.close();
return true;
}
void LanguageManager::_loadLanguage(std::ifstream & _stream, bool _user)
{
std::string read;
while (false == _stream.eof()) {
std::getline(_stream, read);
if (read.empty()) continue;
size_t pos = read.find_first_of(" \t");
if (_user) {
if (pos == std::string::npos) mUserMapLanguage[read] = "";
else mUserMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
else {
if (pos == std::string::npos) mMapLanguage[read] = "";
else mMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
};
}
void LanguageManager::_loadLanguage(const Ogre::DataStreamPtr& stream, bool _user)
{
std::string read;
while (false == stream->eof()) {
read = stream->getLine (false);
if (read.empty()) continue;
size_t pos = read.find_first_of(" \t");
if (_user) {
if (pos == std::string::npos) mUserMapLanguage[read] = "";
else mUserMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
else {
if (pos == std::string::npos) mMapLanguage[read] = "";
else mMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
}
};
}
Ogre::UTFString LanguageManager::replaceTags(const Ogre::UTFString & _line)
{
// вот хз, что быстрее, итераторы или математика указателей,
// для непонятно какого размера одного символа UTF8
Ogre::UTFString line(_line);
if (mMapLanguage.empty() && mUserMapLanguage.empty()) return _line;
Ogre::UTFString::iterator end = line.end();
for (Ogre::UTFString::iterator iter=line.begin(); iter!=end; ) {
if (*iter == '#')
{
++iter;
if (iter == end)
{
return line;
}
else
{
if (*iter != '{')
{
++iter;
continue;
}
Ogre::UTFString::iterator iter2 = iter;
++iter2;
while (true)
{
if (iter2 == end) return line;
if (*iter2 == '}')
{
size_t start = iter - line.begin();
size_t len = (iter2 - line.begin()) - start - 1;
const Ogre::UTFString & tag = line.substr(start + 1, len);
bool find = true;
MapLanguageString::iterator replace = mMapLanguage.find(tag);
if (replace == mMapLanguage.end())
{
replace = mUserMapLanguage.find(tag);
find = replace != mUserMapLanguage.end();
}
if (!find)
{
iter = line.insert(iter, '#') + size_t(len + 2);
end = line.end();
break;
}
else
{
iter = line.erase(iter - size_t(1), iter2 + size_t(1));
size_t pos = iter - line.begin();
line.insert(pos, replace->second);
iter = line.begin() + pos + replace->second.length();
end = line.end();
if (iter == end) return line;
break;
}
iter = iter2;
break;
}
++iter2;
};
}
}
else
{
++iter;
}
}
return line;
}
Ogre::UTFString LanguageManager::getTag(const Ogre::UTFString & _tag)
{
MapLanguageString::iterator iter = mMapLanguage.find(_tag);
if (iter == mMapLanguage.end()) {
iter = mUserMapLanguage.find(_tag);
if (iter != mUserMapLanguage.end()) return iter->second;
return _tag;
}
return iter->second;
}
} // namespace MyGUI
<|endoftext|> |
<commit_before>/**
* @file sparse_coding_impl.hpp
* @author Nishant Mehta
*
* Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or
* l1+l2 (Elastic Net) regularization.
*/
#ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
#define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
// In case it hasn't already been included.
#include "sparse_coding.hpp"
namespace mlpack {
namespace sparse_coding {
template<typename DictionaryInitializer>
SparseCoding<DictionaryInitializer>::SparseCoding(const arma::mat& data,
const size_t atoms,
const double lambda1,
const double lambda2) :
atoms(atoms),
data(data),
codes(atoms, data.n_cols),
lambda1(lambda1),
lambda2(lambda2)
{
// Initialize the dictionary.
DictionaryInitializer::Initialize(data, atoms, dictionary);
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::Encode(const size_t maxIterations,
const double objTolerance,
const double newtonTolerance)
{
Timer::Start("sparse_coding");
double lastObjVal = DBL_MAX;
// Take the initial coding step, which has to happen before entering the main
// optimization loop.
Log::Info << "Initial Coding Step." << std::endl;
OptimizeCode();
arma::uvec adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
Log::Info << " Objective value: " << Objective() << "." << std::endl;
for (size_t t = 1; t != maxIterations; ++t)
{
// Print current iteration, and maximum number of iterations (if it isn't
// 0).
Log::Info << "Iteration " << t;
if (maxIterations != 0)
Log::Info << " of " << maxIterations;
Log::Info << "." << std::endl;
// First step: optimize the dictionary.
Log::Info << "Performing dictionary step... " << std::endl;
OptimizeDictionary(adjacencies, newtonTolerance);
Log::Info << " Objective value: " << Objective() << "." << std::endl;
// Second step: perform the coding.
Log::Info << "Performing coding step..." << std::endl;
OptimizeCode();
// Get the indices of all the nonzero elements in the codes.
adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
// Find the new objective value and improvement so we can check for
// convergence.
double curObjVal = Objective();
double improvement = lastObjVal - curObjVal;
Log::Info << " Objective value: " << curObjVal << " (improvement "
<< std::scientific << improvement << ")." << std::endl;
// Have we converged?
if (improvement < objTolerance)
{
Log::Info << "Converged within tolerance " << objTolerance << ".\n";
break;
}
lastObjVal = curObjVal;
}
Timer::Stop("sparse_coding");
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::OptimizeCode()
{
// When using the Cholesky version of LARS, this is correct even if
// lambda2 > 0.
arma::mat matGram = trans(dictionary) * dictionary;
for (size_t i = 0; i < data.n_cols; ++i)
{
// Report progress.
if ((i % 100) == 0)
Log::Debug << "Optimization at point " << i << "." << std::endl;
bool useCholesky = true;
regression::LARS lars(useCholesky, matGram, lambda1, lambda2);
// Create an alias of the code (using the same memory), and then LARS will
// place the result directly into that; then we will not need to have an
// extra copy.
arma::vec code = codes.unsafe_col(i);
lars.Regress(dictionary, data.unsafe_col(i), code, false);
}
}
// Dictionary step for optimization.
template<typename DictionaryInitializer>
double SparseCoding<DictionaryInitializer>::OptimizeDictionary(
const arma::uvec& adjacencies,
const double newtonTolerance)
{
// Count the number of atomic neighbors for each point x^i.
arma::uvec neighborCounts = arma::zeros<arma::uvec>(data.n_cols, 1);
if (adjacencies.n_elem > 0)
{
// This gets the column index. Intentional integer division.
size_t curPointInd = (size_t) (adjacencies(0) / atoms);
size_t nextColIndex = (curPointInd + 1) * atoms;
for (size_t l = 1; l < adjacencies.n_elem; ++l)
{
// If l no longer refers to an element in this column, advance the column
// number accordingly.
if (adjacencies(l) >= nextColIndex)
{
curPointInd = (size_t) (adjacencies(l) / atoms);
nextColIndex = (curPointInd + 1) * atoms;
}
++neighborCounts(curPointInd);
}
}
// Handle the case of inactive atoms (atoms not used in the given coding).
std::vector<size_t> inactiveAtoms;
for (size_t j = 0; j < atoms; ++j)
{
if (accu(codes.row(j) != 0) == 0)
inactiveAtoms.push_back(j);
}
const size_t nInactiveAtoms = inactiveAtoms.size();
const size_t nActiveAtoms = atoms - nInactiveAtoms;
// Efficient construction of Z restricted to active atoms.
arma::mat matActiveZ;
if (nInactiveAtoms > 0)
{
math::RemoveRows(codes, inactiveAtoms, matActiveZ);
}
if (nInactiveAtoms > 0)
{
Log::Warn << "There are " << nInactiveAtoms
<< " inactive atoms. They will be re-initialized randomly.\n";
}
Log::Debug << "Solving Dual via Newton's Method.\n";
// Solve using Newton's method in the dual - note that the final dot
// multiplication with inv(A) seems to be unavoidable. Although more
// expensive, the code written this way (we use solve()) should be more
// numerically stable than just using inv(A) for everything.
arma::vec dualVars = arma::zeros<arma::vec>(nActiveAtoms);
//vec dualVars = 1e-14 * ones<vec>(nActiveAtoms);
// Method used by feature sign code - fails miserably here. Perhaps the
// MATLAB optimizer fmincon does something clever?
//vec dualVars = 10.0 * randu(nActiveAtoms, 1);
//vec dualVars = diagvec(solve(dictionary, data * trans(codes))
// - codes * trans(codes));
//for (size_t i = 0; i < dualVars.n_elem; i++)
// if (dualVars(i) < 0)
// dualVars(i) = 0;
bool converged = false;
// If we have any inactive atoms, we must construct these differently.
arma::mat codesXT;
arma::mat codesZT;
if (inactiveAtoms.empty())
{
codesXT = codes * trans(data);
codesZT = codes * trans(codes);
}
else
{
codesXT = matActiveZ * trans(data);
codesZT = matActiveZ * trans(matActiveZ);
}
double normGradient;
double improvement;
for (size_t t = 1; !converged; ++t)
{
arma::mat A = codesZT + diagmat(dualVars);
arma::mat matAInvZXT = solve(A, codesXT);
arma::vec gradient = -arma::sum(arma::square(matAInvZXT), 1);
gradient += 1;
arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A));
arma::vec searchDirection = -solve(hessian, gradient);
//printf("%e\n", norm(searchDirection, 2));
// Armijo line search.
const double c = 1e-4;
double alpha = 1.0;
const double rho = 0.9;
double sufficientDecrease = c * dot(gradient, searchDirection);
while (true)
{
// Calculate objective.
double sumDualVars = sum(dualVars);
double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars);
double fNew = -(-trace(trans(codesXT) * solve(codesZT +
diagmat(dualVars + alpha * searchDirection), codesXT)) -
(sumDualVars + alpha * sum(searchDirection)));
if (fNew <= fOld + alpha * sufficientDecrease)
{
searchDirection = alpha * searchDirection;
improvement = fOld - fNew;
break;
}
alpha *= rho;
}
// Take step and print useful information.
dualVars += searchDirection;
normGradient = norm(gradient, 2);
Log::Debug << "Newton Method iteration " << t << ":" << std::endl;
Log::Debug << " Gradient norm: " << std::scientific << normGradient
<< "." << std::endl;
Log::Debug << " Improvement: " << std::scientific << improvement << ".\n";
if (improvement < newtonTolerance)
converged = true;
}
if (inactiveAtoms.empty())
{
// Directly update dictionary.
dictionary = trans(solve(codesZT + diagmat(dualVars), codesXT));
}
else
{
arma::mat activeDictionary = trans(solve(codesZT +
diagmat(dualVars), codesXT));
// Update all atoms.
size_t currentInactiveIndex = 0;
for (size_t i = 0; i < atoms; ++i)
{
if (inactiveAtoms[currentInactiveIndex] == i)
{
// This atom is inactive. Reinitialize it randomly.
dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)));
dictionary.col(i) /= norm(dictionary.col(i), 2);
// Increment inactive index counter.
++currentInactiveIndex;
}
else
{
// Update estimate.
dictionary.col(i) = activeDictionary.col(i - currentInactiveIndex);
}
}
}
//printf("final reconstruction error: %e\n", norm(data - dictionary * codes, "fro"));
return normGradient;
}
// Project each atom of the dictionary back into the unit ball (if necessary).
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::ProjectDictionary()
{
for (size_t j = 0; j < atoms; j++)
{
double atomNorm = norm(dictionary.col(j), 2);
if (atomNorm > 1)
{
Log::Info << "Norm of atom " << j << " exceeds 1 (" << std::scientific
<< atomNorm << "). Shrinking...\n";
dictionary.col(j) /= atomNorm;
}
}
}
// Compute the objective function.
template<typename DictionaryInitializer>
double SparseCoding<DictionaryInitializer>::Objective() const
{
double l11NormZ = sum(sum(abs(codes)));
double froNormResidual = norm(data - (dictionary * codes), "fro");
if (lambda2 > 0)
{
double froNormZ = norm(codes, "fro");
return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 *
std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ);
}
else // It can be simpler.
{
return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ;
}
}
template<typename DictionaryInitializer>
std::string SparseCoding<DictionaryInitializer>::ToString() const
{
std::ostringstream convert;
convert << "Sparse Coding [" << this << "]" << std::endl;
convert << " Data: " << data.n_rows << "x" ;
convert << data.n_cols << std::endl;
convert << " Atoms: " << atoms << std::endl;
convert << " Lambda 1: " << lambda1 << std::endl;
convert << " Lambda 2: " << lambda2 << std::endl;
return convert.str();
}
}; // namespace sparse_coding
}; // namespace mlpack
#endif
<commit_msg>Be explicit with calls to arma:: functions. Although gcc accepts this as-is, we don't have a guarantee that all compilers will.<commit_after>/**
* @file sparse_coding_impl.hpp
* @author Nishant Mehta
*
* Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or
* l1+l2 (Elastic Net) regularization.
*/
#ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
#define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
// In case it hasn't already been included.
#include "sparse_coding.hpp"
namespace mlpack {
namespace sparse_coding {
template<typename DictionaryInitializer>
SparseCoding<DictionaryInitializer>::SparseCoding(const arma::mat& data,
const size_t atoms,
const double lambda1,
const double lambda2) :
atoms(atoms),
data(data),
codes(atoms, data.n_cols),
lambda1(lambda1),
lambda2(lambda2)
{
// Initialize the dictionary.
DictionaryInitializer::Initialize(data, atoms, dictionary);
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::Encode(const size_t maxIterations,
const double objTolerance,
const double newtonTolerance)
{
Timer::Start("sparse_coding");
double lastObjVal = DBL_MAX;
// Take the initial coding step, which has to happen before entering the main
// optimization loop.
Log::Info << "Initial Coding Step." << std::endl;
OptimizeCode();
arma::uvec adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
Log::Info << " Objective value: " << Objective() << "." << std::endl;
for (size_t t = 1; t != maxIterations; ++t)
{
// Print current iteration, and maximum number of iterations (if it isn't
// 0).
Log::Info << "Iteration " << t;
if (maxIterations != 0)
Log::Info << " of " << maxIterations;
Log::Info << "." << std::endl;
// First step: optimize the dictionary.
Log::Info << "Performing dictionary step... " << std::endl;
OptimizeDictionary(adjacencies, newtonTolerance);
Log::Info << " Objective value: " << Objective() << "." << std::endl;
// Second step: perform the coding.
Log::Info << "Performing coding step..." << std::endl;
OptimizeCode();
// Get the indices of all the nonzero elements in the codes.
adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
// Find the new objective value and improvement so we can check for
// convergence.
double curObjVal = Objective();
double improvement = lastObjVal - curObjVal;
Log::Info << " Objective value: " << curObjVal << " (improvement "
<< std::scientific << improvement << ")." << std::endl;
// Have we converged?
if (improvement < objTolerance)
{
Log::Info << "Converged within tolerance " << objTolerance << ".\n";
break;
}
lastObjVal = curObjVal;
}
Timer::Stop("sparse_coding");
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::OptimizeCode()
{
// When using the Cholesky version of LARS, this is correct even if
// lambda2 > 0.
arma::mat matGram = trans(dictionary) * dictionary;
for (size_t i = 0; i < data.n_cols; ++i)
{
// Report progress.
if ((i % 100) == 0)
Log::Debug << "Optimization at point " << i << "." << std::endl;
bool useCholesky = true;
regression::LARS lars(useCholesky, matGram, lambda1, lambda2);
// Create an alias of the code (using the same memory), and then LARS will
// place the result directly into that; then we will not need to have an
// extra copy.
arma::vec code = codes.unsafe_col(i);
lars.Regress(dictionary, data.unsafe_col(i), code, false);
}
}
// Dictionary step for optimization.
template<typename DictionaryInitializer>
double SparseCoding<DictionaryInitializer>::OptimizeDictionary(
const arma::uvec& adjacencies,
const double newtonTolerance)
{
// Count the number of atomic neighbors for each point x^i.
arma::uvec neighborCounts = arma::zeros<arma::uvec>(data.n_cols, 1);
if (adjacencies.n_elem > 0)
{
// This gets the column index. Intentional integer division.
size_t curPointInd = (size_t) (adjacencies(0) / atoms);
size_t nextColIndex = (curPointInd + 1) * atoms;
for (size_t l = 1; l < adjacencies.n_elem; ++l)
{
// If l no longer refers to an element in this column, advance the column
// number accordingly.
if (adjacencies(l) >= nextColIndex)
{
curPointInd = (size_t) (adjacencies(l) / atoms);
nextColIndex = (curPointInd + 1) * atoms;
}
++neighborCounts(curPointInd);
}
}
// Handle the case of inactive atoms (atoms not used in the given coding).
std::vector<size_t> inactiveAtoms;
for (size_t j = 0; j < atoms; ++j)
{
if (arma::accu(codes.row(j) != 0) == 0)
inactiveAtoms.push_back(j);
}
const size_t nInactiveAtoms = inactiveAtoms.size();
const size_t nActiveAtoms = atoms - nInactiveAtoms;
// Efficient construction of Z restricted to active atoms.
arma::mat matActiveZ;
if (nInactiveAtoms > 0)
{
math::RemoveRows(codes, inactiveAtoms, matActiveZ);
}
if (nInactiveAtoms > 0)
{
Log::Warn << "There are " << nInactiveAtoms
<< " inactive atoms. They will be re-initialized randomly.\n";
}
Log::Debug << "Solving Dual via Newton's Method.\n";
// Solve using Newton's method in the dual - note that the final dot
// multiplication with inv(A) seems to be unavoidable. Although more
// expensive, the code written this way (we use solve()) should be more
// numerically stable than just using inv(A) for everything.
arma::vec dualVars = arma::zeros<arma::vec>(nActiveAtoms);
//vec dualVars = 1e-14 * ones<vec>(nActiveAtoms);
// Method used by feature sign code - fails miserably here. Perhaps the
// MATLAB optimizer fmincon does something clever?
//vec dualVars = 10.0 * randu(nActiveAtoms, 1);
//vec dualVars = diagvec(solve(dictionary, data * trans(codes))
// - codes * trans(codes));
//for (size_t i = 0; i < dualVars.n_elem; i++)
// if (dualVars(i) < 0)
// dualVars(i) = 0;
bool converged = false;
// If we have any inactive atoms, we must construct these differently.
arma::mat codesXT;
arma::mat codesZT;
if (inactiveAtoms.empty())
{
codesXT = codes * trans(data);
codesZT = codes * trans(codes);
}
else
{
codesXT = matActiveZ * trans(data);
codesZT = matActiveZ * trans(matActiveZ);
}
double normGradient;
double improvement;
for (size_t t = 1; !converged; ++t)
{
arma::mat A = codesZT + diagmat(dualVars);
arma::mat matAInvZXT = solve(A, codesXT);
arma::vec gradient = -arma::sum(arma::square(matAInvZXT), 1);
gradient += 1;
arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A));
arma::vec searchDirection = -solve(hessian, gradient);
//printf("%e\n", norm(searchDirection, 2));
// Armijo line search.
const double c = 1e-4;
double alpha = 1.0;
const double rho = 0.9;
double sufficientDecrease = c * dot(gradient, searchDirection);
while (true)
{
// Calculate objective.
double sumDualVars = arma::sum(dualVars);
double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars);
double fNew = -(-trace(trans(codesXT) * solve(codesZT +
diagmat(dualVars + alpha * searchDirection), codesXT)) -
(sumDualVars + alpha * arma::sum(searchDirection)));
if (fNew <= fOld + alpha * sufficientDecrease)
{
searchDirection = alpha * searchDirection;
improvement = fOld - fNew;
break;
}
alpha *= rho;
}
// Take step and print useful information.
dualVars += searchDirection;
normGradient = arma::norm(gradient, 2);
Log::Debug << "Newton Method iteration " << t << ":" << std::endl;
Log::Debug << " Gradient norm: " << std::scientific << normGradient
<< "." << std::endl;
Log::Debug << " Improvement: " << std::scientific << improvement << ".\n";
if (improvement < newtonTolerance)
converged = true;
}
if (inactiveAtoms.empty())
{
// Directly update dictionary.
dictionary = trans(solve(codesZT + diagmat(dualVars), codesXT));
}
else
{
arma::mat activeDictionary = trans(solve(codesZT +
diagmat(dualVars), codesXT));
// Update all atoms.
size_t currentInactiveIndex = 0;
for (size_t i = 0; i < atoms; ++i)
{
if (inactiveAtoms[currentInactiveIndex] == i)
{
// This atom is inactive. Reinitialize it randomly.
dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)));
dictionary.col(i) /= arma::norm(dictionary.col(i), 2);
// Increment inactive index counter.
++currentInactiveIndex;
}
else
{
// Update estimate.
dictionary.col(i) = activeDictionary.col(i - currentInactiveIndex);
}
}
}
//printf("final reconstruction error: %e\n", norm(data - dictionary * codes, "fro"));
return normGradient;
}
// Project each atom of the dictionary back into the unit ball (if necessary).
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::ProjectDictionary()
{
for (size_t j = 0; j < atoms; j++)
{
double atomNorm = arma::norm(dictionary.col(j), 2);
if (atomNorm > 1)
{
Log::Info << "Norm of atom " << j << " exceeds 1 (" << std::scientific
<< atomNorm << "). Shrinking...\n";
dictionary.col(j) /= atomNorm;
}
}
}
// Compute the objective function.
template<typename DictionaryInitializer>
double SparseCoding<DictionaryInitializer>::Objective() const
{
double l11NormZ = arma::sum(arma::sum(arma::abs(codes)));
double froNormResidual = arma::norm(data - (dictionary * codes), "fro");
if (lambda2 > 0)
{
double froNormZ = arma::norm(codes, "fro");
return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 *
std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ);
}
else // It can be simpler.
{
return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ;
}
}
template<typename DictionaryInitializer>
std::string SparseCoding<DictionaryInitializer>::ToString() const
{
std::ostringstream convert;
convert << "Sparse Coding [" << this << "]" << std::endl;
convert << " Data: " << data.n_rows << "x" ;
convert << data.n_cols << std::endl;
convert << " Atoms: " << atoms << std::endl;
convert << " Lambda 1: " << lambda1 << std::endl;
convert << " Lambda 2: " << lambda2 << std::endl;
return convert.str();
}
}; // namespace sparse_coding
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>#pragma once
#include "generator/feature_merger.hpp"
#include "generator/generate_info.hpp"
#include "indexer/scales.hpp"
#include "base/logging.hpp"
#include "defines.hpp"
/// Process FeatureBuilder1 for world map. Main functions:
/// - check for visibility in world map
/// - merge linear features
template <class FeatureOutT>
class WorldMapGenerator
{
class EmitterImpl : public FeatureEmitterIFace
{
FeatureOutT m_output;
public:
explicit EmitterImpl(feature::GenerateInfo const & info)
: m_output(info.GetTmpFileName(WORLD_FILE_NAME))
{
LOG(LINFO, ("Output World file:", info.GetTmpFileName(WORLD_FILE_NAME)));
}
/// This function is called after merging linear features.
virtual void operator() (FeatureBuilder1 const & fb)
{
// do additional check for suitable size of feature
if (NeedPushToWorld(fb) && scales::IsGoodForLevel(scales::GetUpperWorldScale(), fb.GetLimitRect()))
PushSure(fb);
}
bool NeedPushToWorld(FeatureBuilder1 const & fb) const
{
// GetMinFeatureDrawScale also checks suitable size for AREA features
return (scales::GetUpperWorldScale() >= fb.GetMinFeatureDrawScale());
}
void PushSure(FeatureBuilder1 const & fb) { m_output(fb); }
};
EmitterImpl m_worldBucket;
FeatureTypesProcessor m_typesCorrector;
FeatureMergeProcessor m_merger;
public:
template <class TInfo>
explicit WorldMapGenerator(TInfo const & info)
: m_worldBucket(info),
m_merger(POINT_COORD_BITS - (scales::GetUpperScale() - scales::GetUpperWorldScale()) / 2)
{
// Do not strip last types for given tags,
// for example, do not cut 'admin_level' in 'boundary-administrative-XXX'.
char const * arr1[][3] = {
{ "boundary", "administrative", "2" },
{ "boundary", "administrative", "3" },
{ "boundary", "administrative", "4" }
};
for (size_t i = 0; i < ARRAY_SIZE(arr1); ++i)
m_typesCorrector.SetDontNormalizeType(arr1[i]);
char const * arr2[] = { "boundary", "administrative", "4", "state" };
m_typesCorrector.SetDontNormalizeType(arr2);
/// @todo It's not obvious to integrate link->way conversion.
/// Review it in future.
/*
char const * arr3[][2] = {
{ "highway", "motorway_link" },
{ "highway", "primary_link" },
{ "highway", "secondary_link" },
{ "highway", "trunk_link" }
};
char const * arr4[][2] = {
{ "highway", "motorway" },
{ "highway", "primary" },
{ "highway", "secondary" },
{ "highway", "trunk" }
};
STATIS_ASSERT(ARRAY_SIZE(arr3) == ARRAY_SIZE(arr4));
for (size_t i = 0; i < ARRAY_SIZE(arr3); ++i)
m_typesCorrector.SetMappingTypes(arr3[i], arr4[i]);
*/
}
void operator()(FeatureBuilder1 fb)
{
if (m_worldBucket.NeedPushToWorld(fb))
{
if (fb.GetGeomType() == feature::GEOM_LINE)
{
MergedFeatureBuilder1 * p = m_typesCorrector(fb);
if (p)
m_merger(p);
}
else
{
if (feature::PreprocessForWorldMap(fb))
m_worldBucket.PushSure(fb);
}
}
}
void DoMerge()
{
m_merger.DoMerge(m_worldBucket);
}
};
template <class FeatureOutT>
class CountryMapGenerator
{
FeatureOutT m_bucket;
public:
template <class TInfo>
explicit CountryMapGenerator(TInfo const & info) : m_bucket(info) {}
void operator()(FeatureBuilder1 fb)
{
if (feature::PreprocessForCountryMap(fb))
m_bucket(fb);
}
FeatureOutT const & Parent() const { return m_bucket; }
};
<commit_msg>Check borders<commit_after>#pragma once
#include "generator/feature_merger.hpp"
#include "generator/generate_info.hpp"
#include "indexer/scales.hpp"
#include "base/logging.hpp"
#include "defines.hpp"
/// Process FeatureBuilder1 for world map. Main functions:
/// - check for visibility in world map
/// - merge linear features
template <class FeatureOutT>
class WorldMapGenerator
{
class EmitterImpl : public FeatureEmitterIFace
{
FeatureOutT m_output;
uint32_t m_boundaryType;
list<m2::RegionD> m_waterRegions;
public:
explicit EmitterImpl(feature::GenerateInfo const & info)
: m_output(info.GetTmpFileName(WORLD_FILE_NAME))
{
m_boundaryType = classif().GetTypeByPath({ "boundary", "administrative"});
LoadWatersRegionsDump(info.m_intermediateDir + WORLD_COASTS_FILE_NAME + ".rawdump");
LOG(LINFO, ("Output World file:", info.GetTmpFileName(WORLD_FILE_NAME)));
}
void LoadWatersRegionsDump(string const &dumpFileName)
{
LOG(LINFO, ("Load water polygons:", dumpFileName));
ifstream file;
file.exceptions(ifstream::badbit);
file.open(dumpFileName);
if (!file.is_open())
LOG(LCRITICAL, ("Can't open water polygons"));
size_t total = 0;
while (true)
{
uint64_t numGeometries = 0;
file.read(reinterpret_cast<char *>(&numGeometries), sizeof(numGeometries));
if (numGeometries == 0)
break;
++total;
vector<m2::PointD> points;
for (size_t i = 0; i < numGeometries; ++i)
{
uint64_t numPoints = 0;
file.read(reinterpret_cast<char *>(&numPoints), sizeof(numPoints));
points.resize(numPoints);
file.read(reinterpret_cast<char *>(points.data()), sizeof(m2::PointD) * numPoints);
m_waterRegions.push_back(m2::RegionD());
m_waterRegions.back().Assign(points.begin(), points.end());
}
}
LOG(LINFO, ("Load", total, "water polygons"));
}
/// This function is called after merging linear features.
virtual void operator() (FeatureBuilder1 const & fb)
{
// do additional check for suitable size of feature
if (NeedPushToWorld(fb) && scales::IsGoodForLevel(scales::GetUpperWorldScale(), fb.GetLimitRect()))
PushSure(fb);
}
bool IsWaterBoundaries(FeatureBuilder1 const & fb) const
{
if (fb.FindType(m_boundaryType, 2) == ftype::GetEmptyValue())
return false;
m2::PointD pts[3] = {{0, 0}, {0, 0}, {0, 0}};
size_t hits[3] = {0, 0, 0};
pts[0] = fb.GetGeometry().front().front();
pts[1] = *(fb.GetGeometry().front().begin() + fb.GetGeometry().front().size()/2);
pts[2] = fb.GetGeometry().front().back();
for (m2::RegionD const & region : m_waterRegions)
{
hits[0] += region.Contains(pts[0]) ? 1 : 0;
hits[1] += region.Contains(pts[1]) ? 1 : 0;
hits[2] += region.Contains(pts[2]) ? 1 : 0;
}
size_t state = (hits[0] & 0x01) + (hits[1] & 0x01) + (hits[2] & 0x01);
LOG(LINFO, ("hits:", hits, "Boundary state:", state, "Dump:", DebugPrint(fb)));
// whole border on land
if (state == 0)
return false;
// whole border on water
if (state == 3)
return true;
LOG(LINFO, ("Found partial boundary"));
return false;
}
bool NeedPushToWorld(FeatureBuilder1 const & fb) const
{
if (IsWaterBoundaries(fb))
{
LOG(LINFO, ("Skip boundary"));
return false;
}
// GetMinFeatureDrawScale also checks suitable size for AREA features
return (scales::GetUpperWorldScale() >= fb.GetMinFeatureDrawScale());
}
void PushSure(FeatureBuilder1 const & fb) { m_output(fb); }
};
EmitterImpl m_worldBucket;
FeatureTypesProcessor m_typesCorrector;
FeatureMergeProcessor m_merger;
public:
template <class TInfo>
explicit WorldMapGenerator(TInfo const & info)
: m_worldBucket(info),
m_merger(POINT_COORD_BITS - (scales::GetUpperScale() - scales::GetUpperWorldScale()) / 2)
{
// Do not strip last types for given tags,
// for example, do not cut 'admin_level' in 'boundary-administrative-XXX'.
char const * arr1[][3] = {
{ "boundary", "administrative", "2" },
{ "boundary", "administrative", "3" },
{ "boundary", "administrative", "4" }
};
for (size_t i = 0; i < ARRAY_SIZE(arr1); ++i)
m_typesCorrector.SetDontNormalizeType(arr1[i]);
char const * arr2[] = { "boundary", "administrative", "4", "state" };
m_typesCorrector.SetDontNormalizeType(arr2);
/// @todo It's not obvious to integrate link->way conversion.
/// Review it in future.
/*
char const * arr3[][2] = {
{ "highway", "motorway_link" },
{ "highway", "primary_link" },
{ "highway", "secondary_link" },
{ "highway", "trunk_link" }
};
char const * arr4[][2] = {
{ "highway", "motorway" },
{ "highway", "primary" },
{ "highway", "secondary" },
{ "highway", "trunk" }
};
STATIS_ASSERT(ARRAY_SIZE(arr3) == ARRAY_SIZE(arr4));
for (size_t i = 0; i < ARRAY_SIZE(arr3); ++i)
m_typesCorrector.SetMappingTypes(arr3[i], arr4[i]);
*/
}
void operator()(FeatureBuilder1 fb)
{
if (m_worldBucket.NeedPushToWorld(fb))
{
if (fb.GetGeomType() == feature::GEOM_LINE)
{
MergedFeatureBuilder1 * p = m_typesCorrector(fb);
if (p)
m_merger(p);
}
else
{
if (feature::PreprocessForWorldMap(fb))
m_worldBucket.PushSure(fb);
}
}
}
void DoMerge()
{
m_merger.DoMerge(m_worldBucket);
}
};
template <class FeatureOutT>
class CountryMapGenerator
{
FeatureOutT m_bucket;
public:
template <class TInfo>
explicit CountryMapGenerator(TInfo const & info) : m_bucket(info) {}
void operator()(FeatureBuilder1 fb)
{
if (feature::PreprocessForCountryMap(fb))
m_bucket(fb);
}
FeatureOutT const & Parent() const { return m_bucket; }
};
<|endoftext|> |
<commit_before>/**
* @file
* @brief Implementation of ROOT data file reader module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "ROOTObjectReaderModule.hpp"
#include <climits>
#include <string>
#include <utility>
#include <TBranch.h>
#include <TKey.h>
#include <TObjArray.h>
#include <TTree.h>
#include "core/messenger/Messenger.hpp"
#include "core/utils/log.h"
#include "core/utils/type.h"
#include "objects/Object.hpp"
#include "objects/objects.h"
#include "core/utils/type.h"
using namespace allpix;
ROOTObjectReaderModule::ROOTObjectReaderModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr)
: Module(config), messenger_(messenger), geo_mgr_(geo_mgr) {}
/**
* @note Objects cannot be stored in smart pointers due to internal ROOT logic
*/
ROOTObjectReaderModule::~ROOTObjectReaderModule() {
for(auto message_inf : message_info_array_) {
delete message_inf.objects;
}
}
/**
* Adds lambda function map to convert a vector of generic objects to a templated message containing this particular type of
* object from its typeid.
*/
template <typename T> static void add_creator(ROOTObjectReaderModule::MessageCreatorMap& map) {
map[typeid(T)] = [&](std::vector<Object*> objects, std::shared_ptr<Detector> detector = nullptr) {
std::vector<T> data;
for(auto& object : objects) {
data.emplace_back(std::move(*static_cast<T*>(object)));
}
if(detector == nullptr) {
return std::make_shared<Message<T>>(data);
}
return std::make_shared<Message<T>>(data, detector);
};
}
/**
* Uses SFINAE trick to call the add_creator function for all template arguments of a container class. Used to add creators
* for every object in a tuple of objects.
*/
template <template <typename...> class T, typename... Args>
static void gen_creator_map_from_tag(ROOTObjectReaderModule::MessageCreatorMap& map, type_tag<T<Args...>>) {
std::initializer_list<int> value{(add_creator<Args>(map), 0)...};
(void)value;
}
/**
* Wrapper function to make the SFINAE trick in \ref gen_creator_map_from_tag work.
*/
template <typename T> static ROOTObjectReaderModule::MessageCreatorMap gen_creator_map() {
ROOTObjectReaderModule::MessageCreatorMap ret_map;
gen_creator_map_from_tag(ret_map, type_tag<T>());
return ret_map;
}
void ROOTObjectReaderModule::init() {
// Read include and exclude list
if(config_.has("include") && config_.has("exclude")) {
throw InvalidCombinationError(
config_, {"exclude", "include"}, "include and exclude parameter are mutually exclusive");
} else if(config_.has("include")) {
auto inc_arr = config_.getArray<std::string>("include");
include_.insert(inc_arr.begin(), inc_arr.end());
} else if(config_.has("exclude")) {
auto exc_arr = config_.getArray<std::string>("exclude");
exclude_.insert(exc_arr.begin(), exc_arr.end());
}
// Initialize the call map from the tuple of available objects
message_creator_map_ = gen_creator_map<allpix::OBJECTS>();
// Open the file with the objects
input_file_ = std::make_unique<TFile>(config_.getPath("file_name", true).c_str());
// Read all the trees in the file
TList* keys = input_file_->GetListOfKeys();
std::set<std::string> tree_names;
for(auto&& object : *keys) {
auto& key = dynamic_cast<TKey&>(*object);
if(std::string(key.GetClassName()) == "TTree") {
auto tree = static_cast<TTree*>(key.ReadObjectAny(nullptr));
// Check if a version of this tree has already been read
if(tree_names.find(tree->GetName()) != tree_names.end()) {
LOG(TRACE) << "Skipping copy of tree with name " << tree->GetName()
<< " because one with identical name has already been processed";
continue;
}
tree_names.insert(tree->GetName());
// Check if this tree should be used
if((!include_.empty() && include_.find(tree->GetName()) == include_.end()) ||
(!exclude_.empty() && exclude_.find(tree->GetName()) != exclude_.end())) {
LOG(TRACE) << "Ignoring tree with " << tree->GetName()
<< " objects because it has been excluded or not explicitly included";
continue;
}
trees_.push_back(tree);
}
}
if(trees_.empty()) {
LOG(ERROR) << "Provided ROOT file does not contain any trees, module will not read any data";
}
// Loop over all found trees
for(auto& tree : trees_) {
// Loop over the list of branches and create the set of receiver objects
TObjArray* branches = tree->GetListOfBranches();
for(int i = 0; i < branches->GetEntries(); i++) {
auto* branch = static_cast<TBranch*>(branches->At(i));
// Add a new vector of objects and bind it to the branch
message_info message_inf;
message_inf.objects = new std::vector<Object*>;
message_info_array_.emplace_back(message_inf);
branch->SetAddress(&(message_info_array_.back().objects));
// Fill the rest of the message information
// FIXME: we want to index this in a different way
std::string branch_name = branch->GetName();
auto split = allpix::split<std::string>(branch_name, "_");
// Fetch information from the tree name
size_t expected_size = 2;
size_t det_idx = 0;
size_t name_idx = 1;
if(branch_name.front() == '_' || branch_name.empty()) {
--expected_size;
det_idx = INT_MAX;
--name_idx;
}
if(branch_name.find('_') == std::string::npos) {
--expected_size;
name_idx = INT_MAX;
}
// Check tree structure and if object type matches name
auto split_type = allpix::split<std::string>(branch->GetClassName(), "<>");
if(expected_size != split.size() || split_type.size() != 2 || split_type[1].size() <= 2) {
throw ModuleError("Tree is malformed and cannot be used for creating messages");
}
std::string class_name = split_type[1].substr(0, split_type[1].size() - 1);
std::string apx_namespace = "allpix::";
size_t ap_idx = class_name.find(apx_namespace);
if(ap_idx != std::string::npos) {
class_name.replace(ap_idx, apx_namespace.size(), "");
}
if(class_name != tree->GetName()) {
throw ModuleError("Tree contains objects of the wrong type");
}
if(name_idx != INT_MAX) {
message_info_array_.back().name = split[name_idx];
}
std::shared_ptr<Detector> detector = nullptr;
if(det_idx != INT_MAX) {
message_info_array_.back().detector = geo_mgr_->getDetector(split[det_idx]);
}
}
}
}
void ROOTObjectReaderModule::run(unsigned int event_num) {
--event_num;
for(auto& tree : trees_) {
if(event_num >= tree->GetEntries()) {
throw EndOfRunException("Requesting end of run because TTree only contains data for " +
std::to_string(event_num) + " events");
}
tree->GetEntry(event_num);
}
LOG(TRACE) << "Building messages from stored objects";
// Loop through all branches
for(auto message_inf : message_info_array_) {
auto objects = message_inf.objects;
// Skip empty objects in current event
if(objects->empty()) {
continue;
}
// Check if a pointer to a dispatcher method exist
auto first_object = (*objects)[0];
auto iter = message_creator_map_.find(typeid(*first_object));
if(iter == message_creator_map_.end()) {
LOG(INFO) << "Cannot dispatch message with object " << allpix::demangle(typeid(*first_object).name())
<< " because it not registered for messaging";
continue;
}
// Update statistics
read_cnt_ += objects->size();
// Create a message
std::shared_ptr<BaseMessage> message = iter->second(*objects, message_inf.detector);
// Dispatch the message
messenger_->dispatchMessage(this, message, message_inf.name);
}
}
void ROOTObjectReaderModule::finalize() {
int branch_count = 0;
for(auto& tree : trees_) {
branch_count += tree->GetListOfBranches()->GetEntries();
}
// Print statistics
LOG(INFO) << "Read " << read_cnt_ << " objects from " << branch_count << " branches";
// Close the file
input_file_->Close();
}
<commit_msg>ROOTObjectReader: Compare random_seed_core between global config and input data This fixes #105<commit_after>/**
* @file
* @brief Implementation of ROOT data file reader module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "ROOTObjectReaderModule.hpp"
#include <climits>
#include <string>
#include <utility>
#include <TBranch.h>
#include <TKey.h>
#include <TObjArray.h>
#include <TTree.h>
#include "core/messenger/Messenger.hpp"
#include "core/utils/log.h"
#include "core/utils/type.h"
#include "objects/Object.hpp"
#include "objects/objects.h"
#include "core/utils/type.h"
using namespace allpix;
ROOTObjectReaderModule::ROOTObjectReaderModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr)
: Module(config), messenger_(messenger), geo_mgr_(geo_mgr) {}
/**
* @note Objects cannot be stored in smart pointers due to internal ROOT logic
*/
ROOTObjectReaderModule::~ROOTObjectReaderModule() {
for(auto message_inf : message_info_array_) {
delete message_inf.objects;
}
}
/**
* Adds lambda function map to convert a vector of generic objects to a templated message containing this particular type of
* object from its typeid.
*/
template <typename T> static void add_creator(ROOTObjectReaderModule::MessageCreatorMap& map) {
map[typeid(T)] = [&](std::vector<Object*> objects, std::shared_ptr<Detector> detector = nullptr) {
std::vector<T> data;
for(auto& object : objects) {
data.emplace_back(std::move(*static_cast<T*>(object)));
}
if(detector == nullptr) {
return std::make_shared<Message<T>>(data);
}
return std::make_shared<Message<T>>(data, detector);
};
}
/**
* Uses SFINAE trick to call the add_creator function for all template arguments of a container class. Used to add creators
* for every object in a tuple of objects.
*/
template <template <typename...> class T, typename... Args>
static void gen_creator_map_from_tag(ROOTObjectReaderModule::MessageCreatorMap& map, type_tag<T<Args...>>) {
std::initializer_list<int> value{(add_creator<Args>(map), 0)...};
(void)value;
}
/**
* Wrapper function to make the SFINAE trick in \ref gen_creator_map_from_tag work.
*/
template <typename T> static ROOTObjectReaderModule::MessageCreatorMap gen_creator_map() {
ROOTObjectReaderModule::MessageCreatorMap ret_map;
gen_creator_map_from_tag(ret_map, type_tag<T>());
return ret_map;
}
void ROOTObjectReaderModule::init() {
// Read include and exclude list
if(config_.has("include") && config_.has("exclude")) {
throw InvalidCombinationError(
config_, {"exclude", "include"}, "include and exclude parameter are mutually exclusive");
} else if(config_.has("include")) {
auto inc_arr = config_.getArray<std::string>("include");
include_.insert(inc_arr.begin(), inc_arr.end());
} else if(config_.has("exclude")) {
auto exc_arr = config_.getArray<std::string>("exclude");
exclude_.insert(exc_arr.begin(), exc_arr.end());
}
// Initialize the call map from the tuple of available objects
message_creator_map_ = gen_creator_map<allpix::OBJECTS>();
// Open the file with the objects
input_file_ = std::make_unique<TFile>(config_.getPath("file_name", true).c_str());
// Read all the trees in the file
TList* keys = input_file_->GetListOfKeys();
std::set<std::string> tree_names;
for(auto&& object : *keys) {
auto& key = dynamic_cast<TKey&>(*object);
if(std::string(key.GetClassName()) == "TTree") {
auto tree = static_cast<TTree*>(key.ReadObjectAny(nullptr));
// Check if a version of this tree has already been read
if(tree_names.find(tree->GetName()) != tree_names.end()) {
LOG(TRACE) << "Skipping copy of tree with name " << tree->GetName()
<< " because one with identical name has already been processed";
continue;
}
tree_names.insert(tree->GetName());
// Check if this tree should be used
if((!include_.empty() && include_.find(tree->GetName()) == include_.end()) ||
(!exclude_.empty() && exclude_.find(tree->GetName()) != exclude_.end())) {
LOG(TRACE) << "Ignoring tree with " << tree->GetName()
<< " objects because it has been excluded or not explicitly included";
continue;
}
trees_.push_back(tree);
}
}
if(trees_.empty()) {
LOG(ERROR) << "Provided ROOT file does not contain any trees, module will not read any data";
}
// Cross-check the core random seed stored in the file with the one configured:
auto global_config = getConfigManager()->getGlobalConfiguration();
auto config_seed = global_config.get<uint64_t>("random_seed_core");
std::string* str;
input_file_->GetObject("config/Allpix/random_seed_core", str);
if(!str) {
throw InvalidValueError(global_config,
"random_seed_core",
"no random seed for core set in the input data file, cross-check with configured value "
"impossible - this might lead to unexpected behavior.");
}
auto file_seed = allpix::from_string<uint64_t>(*str);
if(config_seed != file_seed) {
throw InvalidValueError(global_config,
"random_seed_core",
"mismatch between core random seed in configuration file and input data - this "
"might lead to unexpected behavior. Set to value configured in the input data file: " +
(*str));
}
// Loop over all found trees
for(auto& tree : trees_) {
// Loop over the list of branches and create the set of receiver objects
TObjArray* branches = tree->GetListOfBranches();
for(int i = 0; i < branches->GetEntries(); i++) {
auto* branch = static_cast<TBranch*>(branches->At(i));
// Add a new vector of objects and bind it to the branch
message_info message_inf;
message_inf.objects = new std::vector<Object*>;
message_info_array_.emplace_back(message_inf);
branch->SetAddress(&(message_info_array_.back().objects));
// Fill the rest of the message information
// FIXME: we want to index this in a different way
std::string branch_name = branch->GetName();
auto split = allpix::split<std::string>(branch_name, "_");
// Fetch information from the tree name
size_t expected_size = 2;
size_t det_idx = 0;
size_t name_idx = 1;
if(branch_name.front() == '_' || branch_name.empty()) {
--expected_size;
det_idx = INT_MAX;
--name_idx;
}
if(branch_name.find('_') == std::string::npos) {
--expected_size;
name_idx = INT_MAX;
}
// Check tree structure and if object type matches name
auto split_type = allpix::split<std::string>(branch->GetClassName(), "<>");
if(expected_size != split.size() || split_type.size() != 2 || split_type[1].size() <= 2) {
throw ModuleError("Tree is malformed and cannot be used for creating messages");
}
std::string class_name = split_type[1].substr(0, split_type[1].size() - 1);
std::string apx_namespace = "allpix::";
size_t ap_idx = class_name.find(apx_namespace);
if(ap_idx != std::string::npos) {
class_name.replace(ap_idx, apx_namespace.size(), "");
}
if(class_name != tree->GetName()) {
throw ModuleError("Tree contains objects of the wrong type");
}
if(name_idx != INT_MAX) {
message_info_array_.back().name = split[name_idx];
}
std::shared_ptr<Detector> detector = nullptr;
if(det_idx != INT_MAX) {
message_info_array_.back().detector = geo_mgr_->getDetector(split[det_idx]);
}
}
}
}
void ROOTObjectReaderModule::run(unsigned int event_num) {
--event_num;
for(auto& tree : trees_) {
if(event_num >= tree->GetEntries()) {
throw EndOfRunException("Requesting end of run because TTree only contains data for " +
std::to_string(event_num) + " events");
}
tree->GetEntry(event_num);
}
LOG(TRACE) << "Building messages from stored objects";
// Loop through all branches
for(auto message_inf : message_info_array_) {
auto objects = message_inf.objects;
// Skip empty objects in current event
if(objects->empty()) {
continue;
}
// Check if a pointer to a dispatcher method exist
auto first_object = (*objects)[0];
auto iter = message_creator_map_.find(typeid(*first_object));
if(iter == message_creator_map_.end()) {
LOG(INFO) << "Cannot dispatch message with object " << allpix::demangle(typeid(*first_object).name())
<< " because it not registered for messaging";
continue;
}
// Update statistics
read_cnt_ += objects->size();
// Create a message
std::shared_ptr<BaseMessage> message = iter->second(*objects, message_inf.detector);
// Dispatch the message
messenger_->dispatchMessage(this, message, message_inf.name);
}
}
void ROOTObjectReaderModule::finalize() {
int branch_count = 0;
for(auto& tree : trees_) {
branch_count += tree->GetListOfBranches()->GetEntries();
}
// Print statistics
LOG(INFO) << "Read " << read_cnt_ << " objects from " << branch_count << " branches";
// Close the file
input_file_->Close();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/settings/settingsbackupwallet.h"
#include "qt/pivx/settings/forms/ui_settingsbackupwallet.h"
#include <QFile>
#include <QGraphicsDropShadowEffect>
#include "guiutil.h"
#include "qt/pivx/qtutils.h"
#include "guiinterface.h"
#include "qt/pivx/qtutils.h"
SettingsBackupWallet::SettingsBackupWallet(PIVXGUI* _window, QWidget *parent) :
PWidget(_window, parent),
ui(new Ui::SettingsBackupWallet)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
/* Containers */
ui->left->setProperty("cssClass", "container");
ui->left->setContentsMargins(10,10,10,10);
// Title
ui->labelTitle->setText(tr("Backup Wallet "));
ui->labelTitle->setProperty("cssClass", "text-title-screen");
ui->labelTitle_2->setText(tr("Change Wallet Passphrase"));
ui->labelTitle_2->setProperty("cssClass", "text-title-screen");
ui->labelDivider->setProperty("cssClass", "container-divider");
// Subtitle
ui->labelSubtitle1->setText(tr("Keep your wallet safe doing regular backups, store your backup file externally.\nThis option creates a wallet.dat file that can be used to recover your whole balance (transactions and addresses) from another device."));
ui->labelSubtitle1->setProperty("cssClass", "text-subtitle");
ui->labelSubtitle_2->setText(tr("Change your wallet encryption passphrase for another one that you like. This will decrypt and encrypt your whole data under the new passphrase.\nRemember to write it down to not lose access to your funds."));
ui->labelSubtitle_2->setProperty("cssClass", "text-subtitle");
// Location
ui->labelSubtitleLocation->setText(tr("Where"));
ui->labelSubtitleLocation->setProperty("cssClass", "text-title");
ui->pushButtonDocuments->setText(tr("Set a folder location"));
ui->pushButtonDocuments->setProperty("cssClass", "btn-edit-primary-folder");
setShadow(ui->pushButtonDocuments);
// Buttons
ui->pushButtonSave->setText(tr("Backup"));
setCssBtnPrimary(ui->pushButtonSave);
ui->pushButtonSave_2->setText(tr("Change Passphrase"));
setCssBtnPrimary(ui->pushButtonSave_2);
connect(ui->pushButtonSave, SIGNAL(clicked()), this, SLOT(backupWallet()));
connect(ui->pushButtonDocuments, SIGNAL(clicked()), this, SLOT(selectFileOutput()));
connect(ui->pushButtonSave_2, SIGNAL(clicked()), this, SLOT(changePassphrase()));
}
void SettingsBackupWallet::selectFileOutput()
{
QString filenameRet = GUIUtil::getSaveFileName(this,
tr("Backup Wallet"), QString(),
tr("Wallet Data (*.dat)"), NULL);
if (!filenameRet.isEmpty()) {
filename = filenameRet;
ui->pushButtonDocuments->setText(filename);
}
}
void SettingsBackupWallet::backupWallet()
{
if(walletModel && !filename.isEmpty()) {
inform(walletModel->backupWallet(filename) ? tr("Backup created") : tr("Backup creation failed"));
filename = QString();
ui->pushButtonDocuments->setText(tr("Set a folder location"));
} else {
inform(tr("Please select a folder to export the backup first."));
}
}
void SettingsBackupWallet::changePassphrase()
{
showHideOp(true);
AskPassphraseDialog *dlg = nullptr;
if (walletModel->getEncryptionStatus() == WalletModel::Unencrypted) {
dlg = new AskPassphraseDialog(AskPassphraseDialog::Mode::Encrypt, window,
walletModel, AskPassphraseDialog::Context::Encrypt);
} else {
dlg = new AskPassphraseDialog(AskPassphraseDialog::Mode::ChangePass, window,
walletModel, AskPassphraseDialog::Context::ChangePass);
}
dlg->adjustSize();
emit execDialog(dlg);
dlg->deleteLater();
}
SettingsBackupWallet::~SettingsBackupWallet()
{
delete ui;
}
<commit_msg>Rewording text under Change Wallet Passphrase<commit_after>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/settings/settingsbackupwallet.h"
#include "qt/pivx/settings/forms/ui_settingsbackupwallet.h"
#include <QFile>
#include <QGraphicsDropShadowEffect>
#include "guiutil.h"
#include "qt/pivx/qtutils.h"
#include "guiinterface.h"
#include "qt/pivx/qtutils.h"
SettingsBackupWallet::SettingsBackupWallet(PIVXGUI* _window, QWidget *parent) :
PWidget(_window, parent),
ui(new Ui::SettingsBackupWallet)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
/* Containers */
ui->left->setProperty("cssClass", "container");
ui->left->setContentsMargins(10,10,10,10);
// Title
ui->labelTitle->setText(tr("Backup Wallet "));
ui->labelTitle->setProperty("cssClass", "text-title-screen");
ui->labelTitle_2->setText(tr("Change Wallet Passphrase"));
ui->labelTitle_2->setProperty("cssClass", "text-title-screen");
ui->labelDivider->setProperty("cssClass", "container-divider");
// Subtitle
ui->labelSubtitle1->setText(tr("Keep your wallet safe doing regular backups, store your backup file externally.\nThis option creates a wallet.dat file that can be used to recover your whole balance (transactions and addresses) from another device."));
ui->labelSubtitle1->setProperty("cssClass", "text-subtitle");
ui->labelSubtitle_2->setText(tr("This will decrypt the whole wallet data and encrypt it back with the new passphrase.\nRemember to write it down and store it safely, otherwise you might lose access to your funds."));
ui->labelSubtitle_2->setProperty("cssClass", "text-subtitle");
// Location
ui->labelSubtitleLocation->setText(tr("Where"));
ui->labelSubtitleLocation->setProperty("cssClass", "text-title");
ui->pushButtonDocuments->setText(tr("Set a folder location"));
ui->pushButtonDocuments->setProperty("cssClass", "btn-edit-primary-folder");
setShadow(ui->pushButtonDocuments);
// Buttons
ui->pushButtonSave->setText(tr("Backup"));
setCssBtnPrimary(ui->pushButtonSave);
ui->pushButtonSave_2->setText(tr("Change Passphrase"));
setCssBtnPrimary(ui->pushButtonSave_2);
connect(ui->pushButtonSave, SIGNAL(clicked()), this, SLOT(backupWallet()));
connect(ui->pushButtonDocuments, SIGNAL(clicked()), this, SLOT(selectFileOutput()));
connect(ui->pushButtonSave_2, SIGNAL(clicked()), this, SLOT(changePassphrase()));
}
void SettingsBackupWallet::selectFileOutput()
{
QString filenameRet = GUIUtil::getSaveFileName(this,
tr("Backup Wallet"), QString(),
tr("Wallet Data (*.dat)"), NULL);
if (!filenameRet.isEmpty()) {
filename = filenameRet;
ui->pushButtonDocuments->setText(filename);
}
}
void SettingsBackupWallet::backupWallet()
{
if(walletModel && !filename.isEmpty()) {
inform(walletModel->backupWallet(filename) ? tr("Backup created") : tr("Backup creation failed"));
filename = QString();
ui->pushButtonDocuments->setText(tr("Set a folder location"));
} else {
inform(tr("Please select a folder to export the backup first."));
}
}
void SettingsBackupWallet::changePassphrase()
{
showHideOp(true);
AskPassphraseDialog *dlg = nullptr;
if (walletModel->getEncryptionStatus() == WalletModel::Unencrypted) {
dlg = new AskPassphraseDialog(AskPassphraseDialog::Mode::Encrypt, window,
walletModel, AskPassphraseDialog::Context::Encrypt);
} else {
dlg = new AskPassphraseDialog(AskPassphraseDialog::Mode::ChangePass, window,
walletModel, AskPassphraseDialog::Context::ChangePass);
}
dlg->adjustSize();
emit execDialog(dlg);
dlg->deleteLater();
}
SettingsBackupWallet::~SettingsBackupWallet()
{
delete ui;
}
<|endoftext|> |
<commit_before>#ifndef TYPES_H
#define TYPES_H
/*
Defines a set of types for use on the hl-side.
*/
#include<cstring>
#include"objects.hpp"
class GenericTraverser {
public:
virtual void traverse(Object::ref&) =0;
virtual ~GenericTraverser();
};
/*-----------------------------------------------------------------------------
Generic
-----------------------------------------------------------------------------*/
class Generic {
public:
virtual void traverse_references(GenericTraverser* gt) {
/*default to having no references to traverse*/
/*example for Cons:
gt->traverse(a);
gt->traverse(d);
*/
}
/*some objects have extra allocated space at their ends
(e.g. Closure).
This virtual function returns the total size of the class
plus extra allocated space.
*/
virtual size_t real_size(void) const =0;
/*hash functions for table-ident and table-is*/
virtual size_t hash_ident(void) const {
return reinterpret_cast<size_t>(this);
}
virtual size_t hash_is(void) const {
return reinterpret_cast<size_t>(this);
}
/*broken hearts for GC*/
virtual void break_heart(Generic*) =0;
/*dtor*/
virtual ~Generic() { }
};
/*-----------------------------------------------------------------------------
Broken Heart tags
-----------------------------------------------------------------------------*/
void throw_OverBrokenHeart(Generic*);
class BrokenHeart : public Generic {
private:
// disallowed
BrokenHeart();
BrokenHeart(BrokenHeart const&);
public:
Generic* to;
virtual void break_heart(Generic* to) {
/*already broken - don't break too much!*/
throw_OverBrokenHeart(to);
}
BrokenHeart(Generic* nto) : to(nto) { }
};
class BrokenHeartVariadic : public BrokenHeart {
private:
// disallowed
BrokenHeartVariadic();
BrokenHeartVariadic(BrokenHeart const&);
protected:
size_t sz;
public:
/*exists only for RTTI*/
virtual void break_heart(Generic* to) {
throw_OverBrokenHeart(to);
}
BrokenHeartVariadic(Generic* x, size_t nsz)
: BrokenHeart(x), sz(nsz) { }
};
template<class T>
class BrokenHeartFor : public BrokenHeart {
private:
// disallowed
BrokenHeartFor<T>();
BrokenHeartFor<T>(BrokenHeartFor<T> const&);
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T));
}
explicit BrokenHeartFor<T>(Generic* x) : BrokenHeart(x) { }
};
template<class T>
class BrokenHeartForVariadic : public BrokenHeartVariadic {
private:
// disallowed
BrokenHeartForVariadic<T>();
BrokenHeartForVariadic<T>(BrokenHeartForVariadic<T> const&);
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T))
+ Object::round_up_to_alignment(
sz * sizeof(Object::ref)
)
;
}
BrokenHeartForVariadic<T>(Generic* x, size_t nsz)
: BrokenHeartVariadic(x, nsz) { }
};
/*-----------------------------------------------------------------------------
Base classes for Generic-derived objects
-----------------------------------------------------------------------------*/
template<class T>
class GenericDerived : public Generic {
protected:
GenericDerived<T>(void) { }
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T));
}
virtual void break_heart(Generic* to) {
Generic* gp = this;
gp->~Generic();
new((void*) gp) BrokenHeartFor<T>(to);
};
};
/*This class implements a variable-size object by informing the
memory system to reserve extra space.
Note that classes which derive from this should provide
a factory function!
*/
template<class T>
class GenericDerivedVariadic : public Generic {
GenericDerivedVariadic<T>(void); // disallowed!
protected:
/*number of extra Object::ref's*/
size_t sz;
/*used by the derived classes to get access to
the variadic data at the end of the object.
*/
inline Object::ref& index(size_t i) {
void* vp = this;
char* cp = (char*) vp;
cp = cp + sizeof(T);
Object::ref* op = (void*) cp;
return op[i];
}
explicit GenericDerivedVariadic<T>(size_t nsz) : sz(nsz) {
/*clear the extra references*/
for(size_t i; i < nsz; ++i) {
index(i) = Object::nil();
}
}
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T))
+ Object::round_up_to_alignment(
sz * sizeof(Object::ref)
)
;
}
virtual void break_heart(Object::ref to) {
Generic* gp = this;
size_t nsz = sz; //save this before dtoring!
gp->~Generic();
new((void*) gp) BrokenHeartForVariadic<T>(to, nsz);
}
};
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
void throw_HlError(char const*);
/*Usage:
Cons* cp = expect_type<Cons>(proc.stack().top(),
"Your mom expects a Cons cell on top"
);
*/
template<class T>
static inline T* expect_type(Object::ref x, char const* error) {
if(!is_a<Generic*>(x)) throw_HlError(error);
T* tmp = dynamic_cast<T*>(as_a<Generic*>(x));
if(!tmp) throw_HlError(error);
return tmp;
}
/*
* Cons cell
*/
class Cons : public GenericDerived<Cons> {
private:
Object::ref car_ref;
Object::ref cdr_ref;
public:
inline Object::ref car() { return car_ref; }
inline Object::ref cdr() { return cdr_ref; }
Cons() : car_ref(Object::nil()), cdr_ref(Object::nil()) {}
void traverse_references(GenericTraverser *gt) {
gt->traverse(car_ref);
gt->traverse(cdr_ref);
}
};
static inline Object::ref car(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'car expects a Cons cell")->car();
}
static inline Object::ref cdr(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'cdr expects a Cons cell")->cdr();
}
#endif //TYPES_H
<commit_msg>inc/types.hpp: Added warning regarding ctors for Generic-derived objects, added scar/scdr<commit_after>#ifndef TYPES_H
#define TYPES_H
/*
Defines a set of types for use on the hl-side.
*/
#include<cstring>
#include"objects.hpp"
class GenericTraverser {
public:
virtual void traverse(Object::ref&) =0;
virtual ~GenericTraverser();
};
/*-----------------------------------------------------------------------------
Generic
-----------------------------------------------------------------------------*/
class Generic {
public:
virtual void traverse_references(GenericTraverser* gt) {
/*default to having no references to traverse*/
/*example for Cons:
gt->traverse(a);
gt->traverse(d);
*/
}
/*some objects have extra allocated space at their ends
(e.g. Closure).
This virtual function returns the total size of the class
plus extra allocated space.
*/
virtual size_t real_size(void) const =0;
/*hash functions for table-ident and table-is*/
virtual size_t hash_ident(void) const {
return reinterpret_cast<size_t>(this);
}
virtual size_t hash_is(void) const {
return reinterpret_cast<size_t>(this);
}
/*broken hearts for GC*/
virtual void break_heart(Generic*) =0;
/*dtor*/
virtual ~Generic() { }
};
/*-----------------------------------------------------------------------------
Broken Heart tags
-----------------------------------------------------------------------------*/
void throw_OverBrokenHeart(Generic*);
class BrokenHeart : public Generic {
private:
// disallowed
BrokenHeart();
BrokenHeart(BrokenHeart const&);
public:
Generic* to;
virtual void break_heart(Generic* to) {
/*already broken - don't break too much!*/
throw_OverBrokenHeart(to);
}
BrokenHeart(Generic* nto) : to(nto) { }
};
class BrokenHeartVariadic : public BrokenHeart {
private:
// disallowed
BrokenHeartVariadic();
BrokenHeartVariadic(BrokenHeart const&);
protected:
size_t sz;
public:
/*exists only for RTTI*/
virtual void break_heart(Generic* to) {
throw_OverBrokenHeart(to);
}
BrokenHeartVariadic(Generic* x, size_t nsz)
: BrokenHeart(x), sz(nsz) { }
};
template<class T>
class BrokenHeartFor : public BrokenHeart {
private:
// disallowed
BrokenHeartFor<T>();
BrokenHeartFor<T>(BrokenHeartFor<T> const&);
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T));
}
explicit BrokenHeartFor<T>(Generic* x) : BrokenHeart(x) { }
};
template<class T>
class BrokenHeartForVariadic : public BrokenHeartVariadic {
private:
// disallowed
BrokenHeartForVariadic<T>();
BrokenHeartForVariadic<T>(BrokenHeartForVariadic<T> const&);
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T))
+ Object::round_up_to_alignment(
sz * sizeof(Object::ref)
)
;
}
BrokenHeartForVariadic<T>(Generic* x, size_t nsz)
: BrokenHeartVariadic(x, nsz) { }
};
/*-----------------------------------------------------------------------------
Base classes for Generic-derived objects
-----------------------------------------------------------------------------*/
template<class T>
class GenericDerived : public Generic {
protected:
GenericDerived<T>(void) { }
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T));
}
virtual void break_heart(Generic* to) {
Generic* gp = this;
gp->~Generic();
new((void*) gp) BrokenHeartFor<T>(to);
};
};
/*This class implements a variable-size object by informing the
memory system to reserve extra space.
Note that classes which derive from this should provide
a factory function!
*/
template<class T>
class GenericDerivedVariadic : public Generic {
GenericDerivedVariadic<T>(void); // disallowed!
protected:
/*number of extra Object::ref's*/
size_t sz;
/*used by the derived classes to get access to
the variadic data at the end of the object.
*/
inline Object::ref& index(size_t i) {
void* vp = this;
char* cp = (char*) vp;
cp = cp + sizeof(T);
Object::ref* op = (void*) cp;
return op[i];
}
explicit GenericDerivedVariadic<T>(size_t nsz) : sz(nsz) {
/*clear the extra references*/
for(size_t i; i < nsz; ++i) {
index(i) = Object::nil();
}
}
public:
virtual size_t real_size(void) const {
return Object::round_up_to_alignment(sizeof(T))
+ Object::round_up_to_alignment(
sz * sizeof(Object::ref)
)
;
}
virtual void break_heart(Object::ref to) {
Generic* gp = this;
size_t nsz = sz; //save this before dtoring!
gp->~Generic();
new((void*) gp) BrokenHeartForVariadic<T>(to, nsz);
}
};
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
void throw_HlError(char const*);
/*Usage:
Cons* cp = expect_type<Cons>(proc.stack().top(),
"Your mom expects a Cons cell on top"
);
*/
template<class T>
static inline T* expect_type(Object::ref x, char const* error) {
if(!is_a<Generic*>(x)) throw_HlError(error);
T* tmp = dynamic_cast<T*>(as_a<Generic*>(x));
if(!tmp) throw_HlError(error);
return tmp;
}
/*
* Cons cell
*/
class Cons : public GenericDerived<Cons> {
private:
Object::ref car_ref;
Object::ref cdr_ref;
public:
inline Object::ref car() { return car_ref; }
inline Object::ref cdr() { return cdr_ref; }
inline Object::ref scar(Object::ref x) { return car_ref = x; }
inline Object::ref scdr(Object::ref x) { return cdr_ref = x; }
Cons() : car_ref(Object::nil()), cdr_ref(Object::nil()) {}
/*
* Note that we *can't* safely construct any heap-based objects
* by, say, passing them any of their data. This is because the
* act of allocating space for these objects may start a garbage
* collection, which can move *other* objects. So any references
* passed into the constructor will be invalid; instead, the
* process must save the data to be put in the new object in a
* root location (such as the process stack) and after it is
* given the newly-constructed object, it must store the data
* straight from the root location.
*/
void traverse_references(GenericTraverser *gt) {
gt->traverse(car_ref);
gt->traverse(cdr_ref);
}
};
static inline Object::ref car(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'car expects a Cons cell")->car();
}
static inline Object::ref cdr(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'cdr expects a Cons cell")->cdr();
}
static inline Object::ref scar(Object::ref c, Object::ref v) {
return expect_type<Cons>(c,"'scar expects a true Cons cell")->scar(v);
}
static inline Object::ref scdr(Object::ref c, Object::ref v) {
return expect_type<Cons>(c,"'scdr expects a true Cons cell")->scdr(v);
}
#endif //TYPES_H
<|endoftext|> |
<commit_before>#include "generated_nrm2.o.h"
#include <Halide.h>
#include <tiramisu/tiramisu.h>
#include <tiramisu/utils.h>
#include <iostream>
#include "benchmarks.h"
#include <math.h>
#define M_DIM M
#define N_DIM N
int nrm2_ref(int n, double * X, double *nrm)
{
double sum = 0;
for (int i = 0; i < n; ++i)
sum += X[i] * X[i];
nrm[0] = sqrt(sum);
return 0;
}
int main(int argc, char** argv)
{
std::vector<std::chrono::duration<double, std::milli>> duration_vector_1, duration_vector_2;
bool run_ref = false, run_tiramisu = false;
const char* env_ref = std::getenv("RUN_REF");
if (env_ref != NULL && env_ref[0] == '1')
run_ref = true;
const char* env_tiramisu = std::getenv("RUN_TIRAMISU");
if (env_tiramisu != NULL && env_tiramisu[0] == '1')
run_tiramisu = true;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
Halide::Buffer<double> b_result(1), b_result_ref(1);
Halide::Buffer<double> b_X(N_DIM);
init_buffer(b_X, (double) 1);
/**
X vector is initialized to 1
**/
{
for (int i = 0; i < NB_TESTS; ++i)
{
auto start = std::chrono::high_resolution_clock::now();
if (run_ref)
nrm2_ref(N_DIM, b_X.data(), b_result_ref.data() );
auto end = std::chrono::high_resolution_clock::now();
duration_vector_1.push_back(end - start);
}
}
{
for (int i = 0; i < NB_TESTS; ++i)
{
auto start = std::chrono::high_resolution_clock::now();
if (run_tiramisu)
nrm2(b_X.raw_buffer(), b_result.raw_buffer());
auto end = std::chrono::high_resolution_clock::now();
duration_vector_2.push_back(end - start);
}
}
print_time("performance_cpu.csv", "nrm2",
{"Ref", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS && run_ref && run_tiramisu)
compare_buffers("nrm2", b_result, b_result_ref);
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu " << std::endl;
print_buffer(b_result);
std::cout << "Reference " << std::endl;
print_buffer(b_result_ref);
}
return 0;
}
<commit_msg>Fix code style<commit_after>#include "generated_nrm2.o.h"
#include <Halide.h>
#include <tiramisu/tiramisu.h>
#include <tiramisu/utils.h>
#include <iostream>
#include "benchmarks.h"
#include <math.h>
#define M_DIM M
#define N_DIM N
int nrm2_ref(int n, double * X, double * nrm)
{
double sum = 0;
for (int i = 0; i < n; ++i)
sum += X[i] * X[i];
nrm[0] = sqrt(sum);
return 0;
}
int main(int argc, char** argv)
{
std::vector<std::chrono::duration<double, std::milli>> duration_vector_1, duration_vector_2;
bool run_ref = false, run_tiramisu = false;
const char* env_ref = std::getenv("RUN_REF");
if (env_ref != NULL && env_ref[0] == '1')
run_ref = true;
const char* env_tiramisu = std::getenv("RUN_TIRAMISU");
if (env_tiramisu != NULL && env_tiramisu[0] == '1')
run_tiramisu = true;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
Halide::Buffer<double> b_result(1), b_result_ref(1);
Halide::Buffer<double> b_X(N_DIM);
init_buffer(b_X, (double) 1);
/**
X vector is initialized to 1
**/
{
for (int i = 0; i < NB_TESTS; ++i)
{
auto start = std::chrono::high_resolution_clock::now();
if (run_ref)
nrm2_ref(N_DIM, b_X.data(), b_result_ref.data());
auto end = std::chrono::high_resolution_clock::now();
duration_vector_1.push_back(end - start);
}
}
{
for (int i = 0; i < NB_TESTS; ++i)
{
auto start = std::chrono::high_resolution_clock::now();
if (run_tiramisu)
nrm2(b_X.raw_buffer(), b_result.raw_buffer());
auto end = std::chrono::high_resolution_clock::now();
duration_vector_2.push_back(end - start);
}
}
print_time("performance_cpu.csv", "nrm2",
{"Ref", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS && run_ref && run_tiramisu)
compare_buffers("nrm2", b_result, b_result_ref);
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu " << std::endl;
print_buffer(b_result);
std::cout << "Reference " << std::endl;
print_buffer(b_result_ref);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "PrimeTower.h"
#include <limits>
#include "ExtruderTrain.h"
#include "sliceDataStorage.h"
#include "gcodeExport.h"
#include "LayerPlan.h"
#include "infill.h"
#include "PrintFeature.h"
namespace cura
{
PrimeTower::PrimeTower(const SliceDataStorage& storage)
: is_hollow(false)
, wipe_from_middle(false)
{
enabled = storage.getSettingBoolean("prime_tower_enable")
&& storage.getSettingInMicrons("prime_tower_wall_thickness") > 10
&& storage.getSettingInMicrons("prime_tower_size") > 10;
if (enabled)
{
generateGroundpoly(storage);
}
}
void PrimeTower::generateGroundpoly(const SliceDataStorage& storage)
{
extruder_count = storage.meshgroup->getExtruderCount();
int64_t prime_tower_wall_thickness = storage.getSettingInMicrons("prime_tower_wall_thickness");
int64_t tower_size = storage.getSettingInMicrons("prime_tower_size");
if (prime_tower_wall_thickness * 2 < tower_size)
{
is_hollow = true;
}
PolygonRef p = ground_poly.newPoly();
int tower_distance = 0;
int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x
int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y
p.add(Point(x + tower_distance, y + tower_distance));
p.add(Point(x + tower_distance, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance));
middle = Point(x - tower_size / 2, y + tower_size / 2);
if (is_hollow)
{
ground_poly = ground_poly.difference(ground_poly.offset(-prime_tower_wall_thickness));
}
post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
}
void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
if (enabled)
{
generatePaths_denseInfill(storage);
generateWipeLocations(storage);
}
}
void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage)
{
int n_patterns = 2; // alternating patterns between layers
int infill_overlap = 60; // so that it can't be zero; EDIT: wtf?
int extra_infill_shift = 0;
int64_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position
for (int extruder = 0; extruder < extruder_count; extruder++)
{
int line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width");
patterns_per_extruder.emplace_back(n_patterns);
std::vector<ExtrusionMoves>& patterns = patterns_per_extruder.back();
patterns.resize(n_patterns);
for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++)
{
patterns[pattern_idx].polygons = ground_poly.offset(-line_width / 2);
Polygons& result_lines = patterns[pattern_idx].lines;
int outline_offset = -line_width;
int line_distance = line_width;
double fill_angle = 45 + pattern_idx * 90;
Polygons result_polygons; // should remain empty, since we generate lines pattern!
Infill infill_comp(EFillMethod::LINES, ground_poly, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift);
infill_comp.generate(result_polygons, result_lines);
}
}
}
void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) const
{
if (!enabled)
{
return;
}
if (gcodeLayer.getPrimeTowerIsPlanned())
{ // don't print the prime tower if it has been printed already
return;
}
if (layer_nr > storage.max_print_height_second_to_last_extruder + 1)
{
return;
}
bool pre_wipe = storage.meshgroup->getExtruderTrain(new_extruder)->getSettingBoolean("dual_pre_wipe");
bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled");
if (prev_extruder == new_extruder)
{
pre_wipe = false;
post_wipe = false;
}
// pre-wipe:
if (pre_wipe)
{
preWipe(storage, gcodeLayer, layer_nr, new_extruder);
}
addToGcode_denseInfill(gcodeLayer, layer_nr, new_extruder);
// post-wipe:
if (post_wipe)
{ //Make sure we wipe the old extruder on the prime tower.
gcodeLayer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder));
}
gcodeLayer.setPrimeTowerIsPlanned();
}
void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const
{
const ExtrusionMoves& pattern = patterns_per_extruder[extruder_nr][((layer_nr % 2) + 2) % 2]; // +2) %2 to handle negative layer numbers
const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];
gcode_layer.addPolygonsByOptimizer(pattern.polygons, &config);
gcode_layer.addLinesByOptimizer(pattern.lines, &config, SpaceFillType::Lines);
}
Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const
{
Point ret(0, 0);
int absolute_starting_points = 0;
for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)
{
ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0);
if (train.getSettingBoolean("machine_extruder_start_pos_abs"))
{
ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y"));
absolute_starting_points++;
}
}
if (absolute_starting_points > 0)
{ // take the average over all absolute starting positions
ret /= absolute_starting_points;
}
else
{ // use the middle of the bed
if (!storage.getSettingBoolean("machine_center_is_zero"))
{
ret = Point(storage.getSettingInMicrons("machine_width"), storage.getSettingInMicrons("machine_depth")) / 2;
}
// otherwise keep (0, 0)
}
return ret;
}
void PrimeTower::generateWipeLocations(const SliceDataStorage& storage)
{
wipe_from_middle = is_hollow;
// only wipe from the middle of the prime tower if we have a z hop already on the first move after the layer switch
for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)
{
const ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr);
wipe_from_middle &= train.getSettingBoolean("retraction_hop_enabled")
&& (!train.getSettingBoolean("retraction_hop_only_when_collides") || train.getSettingBoolean("retraction_hop_after_extruder_switch"));
}
PolygonsPointIndex segment_start; // from where to start the sequence of wipe points
PolygonsPointIndex segment_end; // where to end the sequence of wipe points
if (wipe_from_middle)
{
// take the same start as end point so that the whole poly os covered.
// find the inner polygon.
segment_start = segment_end = PolygonUtils::findNearestVert(middle, ground_poly);
}
else
{
// take the closer corner of the wipe tower and generate wipe locations on that side only:
//
// |
// |
// +-----
// .
// ^ nozzle switch location
Point from = getLocationBeforePrimeTower(storage);
// find the single line segment closest to [from] pointing most toward [from]
PolygonsPointIndex closest_vert = PolygonUtils::findNearestVert(from, ground_poly);
PolygonsPointIndex prev = closest_vert.prev();
PolygonsPointIndex next = closest_vert.next();
int64_t prev_dot_score = dot(from - closest_vert.p(), turn90CCW(prev.p() - closest_vert.p()));
int64_t next_dot_score = dot(from - closest_vert.p(), turn90CCW(closest_vert.p() - next.p()));
if (prev_dot_score > next_dot_score)
{
segment_start = prev;
segment_end = closest_vert;
}
else
{
segment_start = closest_vert;
segment_end = next;
}
}
PolygonUtils::spreadDots(segment_start, segment_end, number_of_pre_wipe_locations, pre_wipe_locations);
}
void PrimeTower::preWipe(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const
{
int current_pre_wipe_location_idx = (pre_wipe_location_skip * layer_nr) % number_of_pre_wipe_locations;
const ClosestPolygonPoint wipe_location = pre_wipe_locations[current_pre_wipe_location_idx];
ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr);
const int inward_dist = train.getSettingInMicrons("machine_nozzle_size") * 3 / 2 ;
const int start_dist = train.getSettingInMicrons("machine_nozzle_size") * 2;
const Point end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist);
const Point outward_dir = wipe_location.location - end;
const Point start = wipe_location.location + normal(outward_dir, start_dist);
if (wipe_from_middle)
{
// for hollow wipe tower:
// start from above
// go to wipe start
// go to the Z height of the previous/current layer
// wipe
// go to normal layer height (automatically on the next extrusion move)...
GCodePath& toward_middle = gcode_layer.addTravel(middle);
toward_middle.perform_z_hop = true;
gcode_layer.forceNewPathStart();
GCodePath& toward_wipe_start = gcode_layer.addTravel_simple(start);
toward_wipe_start.perform_z_hop = false;
toward_wipe_start.retract = true;
}
else
{
gcode_layer.addTravel(start);
}
float flow = 0.0001; // Force this path being interpreted as an extrusion path, so that no Z hop will occur (TODO: really separately handle travel and extrusion moves)
// Check if we need to purge before wiping on the prime tower.
if(train.getSettingBoolean("prime_tower_purge_enabled"))
{
// We can't do a "real" stand still & extrude move, we need to fake one.
// We do this by changing the flow of the "move to end of wipe" position.
const unsigned int infill_line_width = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr].getLineWidth();
const double layer_height_mm = (layer_nr == 0)? train.getSettingInMillimeters("layer_height_0") : train.getSettingInMillimeters("layer_height");
const double normal_volume = INT2MM(INT2MM(start_dist * infill_line_width)) * layer_height_mm; // Volume extruded on the "normal" move
const double total_volume = train.getSettingBoolean("prime_tower_purge_volume"); // Volume to be primed
flow = total_volume / normal_volume; // New flow ratio
}
gcode_layer.addExtrusionMove(end, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, flow);
}
void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
const Polygons outside_polygon = ground_poly.getOutsidePolygons();
for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
{
storage.support.supportLayers[layer].supportAreas = storage.support.supportLayers[layer].supportAreas.difference(outside_polygon);
}
}
}//namespace cura
<commit_msg>Purging now always happens before we do a wipe<commit_after>#include "PrimeTower.h"
#include <limits>
#include "ExtruderTrain.h"
#include "sliceDataStorage.h"
#include "gcodeExport.h"
#include "LayerPlan.h"
#include "infill.h"
#include "PrintFeature.h"
namespace cura
{
PrimeTower::PrimeTower(const SliceDataStorage& storage)
: is_hollow(false)
, wipe_from_middle(false)
{
enabled = storage.getSettingBoolean("prime_tower_enable")
&& storage.getSettingInMicrons("prime_tower_wall_thickness") > 10
&& storage.getSettingInMicrons("prime_tower_size") > 10;
if (enabled)
{
generateGroundpoly(storage);
}
}
void PrimeTower::generateGroundpoly(const SliceDataStorage& storage)
{
extruder_count = storage.meshgroup->getExtruderCount();
int64_t prime_tower_wall_thickness = storage.getSettingInMicrons("prime_tower_wall_thickness");
int64_t tower_size = storage.getSettingInMicrons("prime_tower_size");
if (prime_tower_wall_thickness * 2 < tower_size)
{
is_hollow = true;
}
PolygonRef p = ground_poly.newPoly();
int tower_distance = 0;
int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x
int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y
p.add(Point(x + tower_distance, y + tower_distance));
p.add(Point(x + tower_distance, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance));
middle = Point(x - tower_size / 2, y + tower_size / 2);
if (is_hollow)
{
ground_poly = ground_poly.difference(ground_poly.offset(-prime_tower_wall_thickness));
}
post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
}
void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
if (enabled)
{
generatePaths_denseInfill(storage);
generateWipeLocations(storage);
}
}
void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage)
{
int n_patterns = 2; // alternating patterns between layers
int infill_overlap = 60; // so that it can't be zero; EDIT: wtf?
int extra_infill_shift = 0;
int64_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position
for (int extruder = 0; extruder < extruder_count; extruder++)
{
int line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width");
patterns_per_extruder.emplace_back(n_patterns);
std::vector<ExtrusionMoves>& patterns = patterns_per_extruder.back();
patterns.resize(n_patterns);
for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++)
{
patterns[pattern_idx].polygons = ground_poly.offset(-line_width / 2);
Polygons& result_lines = patterns[pattern_idx].lines;
int outline_offset = -line_width;
int line_distance = line_width;
double fill_angle = 45 + pattern_idx * 90;
Polygons result_polygons; // should remain empty, since we generate lines pattern!
Infill infill_comp(EFillMethod::LINES, ground_poly, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift);
infill_comp.generate(result_polygons, result_lines);
}
}
}
void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) const
{
if (!enabled)
{
return;
}
if (gcodeLayer.getPrimeTowerIsPlanned())
{ // don't print the prime tower if it has been printed already
return;
}
if (layer_nr > storage.max_print_height_second_to_last_extruder + 1)
{
return;
}
bool pre_wipe = storage.meshgroup->getExtruderTrain(new_extruder)->getSettingBoolean("dual_pre_wipe");
bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled");
if (prev_extruder == new_extruder)
{
pre_wipe = false;
post_wipe = false;
}
// pre-wipe:
if (pre_wipe)
{
preWipe(storage, gcodeLayer, layer_nr, new_extruder);
}
addToGcode_denseInfill(gcodeLayer, layer_nr, new_extruder);
// post-wipe:
if (post_wipe)
{ //Make sure we wipe the old extruder on the prime tower.
gcodeLayer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder));
}
gcodeLayer.setPrimeTowerIsPlanned();
}
void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const
{
const ExtrusionMoves& pattern = patterns_per_extruder[extruder_nr][((layer_nr % 2) + 2) % 2]; // +2) %2 to handle negative layer numbers
const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];
gcode_layer.addPolygonsByOptimizer(pattern.polygons, &config);
gcode_layer.addLinesByOptimizer(pattern.lines, &config, SpaceFillType::Lines);
}
Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const
{
Point ret(0, 0);
int absolute_starting_points = 0;
for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)
{
ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0);
if (train.getSettingBoolean("machine_extruder_start_pos_abs"))
{
ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y"));
absolute_starting_points++;
}
}
if (absolute_starting_points > 0)
{ // take the average over all absolute starting positions
ret /= absolute_starting_points;
}
else
{ // use the middle of the bed
if (!storage.getSettingBoolean("machine_center_is_zero"))
{
ret = Point(storage.getSettingInMicrons("machine_width"), storage.getSettingInMicrons("machine_depth")) / 2;
}
// otherwise keep (0, 0)
}
return ret;
}
void PrimeTower::generateWipeLocations(const SliceDataStorage& storage)
{
wipe_from_middle = is_hollow;
// only wipe from the middle of the prime tower if we have a z hop already on the first move after the layer switch
for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)
{
const ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr);
wipe_from_middle &= train.getSettingBoolean("retraction_hop_enabled")
&& (!train.getSettingBoolean("retraction_hop_only_when_collides") || train.getSettingBoolean("retraction_hop_after_extruder_switch"));
}
PolygonsPointIndex segment_start; // from where to start the sequence of wipe points
PolygonsPointIndex segment_end; // where to end the sequence of wipe points
if (wipe_from_middle)
{
// take the same start as end point so that the whole poly os covered.
// find the inner polygon.
segment_start = segment_end = PolygonUtils::findNearestVert(middle, ground_poly);
}
else
{
// take the closer corner of the wipe tower and generate wipe locations on that side only:
//
// |
// |
// +-----
// .
// ^ nozzle switch location
Point from = getLocationBeforePrimeTower(storage);
// find the single line segment closest to [from] pointing most toward [from]
PolygonsPointIndex closest_vert = PolygonUtils::findNearestVert(from, ground_poly);
PolygonsPointIndex prev = closest_vert.prev();
PolygonsPointIndex next = closest_vert.next();
int64_t prev_dot_score = dot(from - closest_vert.p(), turn90CCW(prev.p() - closest_vert.p()));
int64_t next_dot_score = dot(from - closest_vert.p(), turn90CCW(closest_vert.p() - next.p()));
if (prev_dot_score > next_dot_score)
{
segment_start = prev;
segment_end = closest_vert;
}
else
{
segment_start = closest_vert;
segment_end = next;
}
}
PolygonUtils::spreadDots(segment_start, segment_end, number_of_pre_wipe_locations, pre_wipe_locations);
}
void PrimeTower::preWipe(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const
{
int current_pre_wipe_location_idx = (pre_wipe_location_skip * layer_nr) % number_of_pre_wipe_locations;
const ClosestPolygonPoint wipe_location = pre_wipe_locations[current_pre_wipe_location_idx];
ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr);
const int inward_dist = train.getSettingInMicrons("machine_nozzle_size") * 3 / 2 ;
const int start_dist = train.getSettingInMicrons("machine_nozzle_size") * 2;
const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist);
const Point outward_dir = wipe_location.location - prime_end;
const Point prime_start = wipe_location.location + normal(outward_dir, start_dist);
const double purge_volume = train.getSettingInCubicMillimeters("prime_tower_purge_volume"); // Volume to be primed
if (wipe_from_middle)
{
// for hollow wipe tower:
// start from above
// go to wipe start
// go to the Z height of the previous/current layer
// wipe
// go to normal layer height (automatically on the next extrusion move)...
GCodePath& toward_middle = gcode_layer.addTravel(middle);
toward_middle.perform_z_hop = true;
gcode_layer.forceNewPathStart();
if(purge_volume > 0)
{
// Find out how much purging needs to be done.
int purge_move_length = vSize(middle - prime_start);
const unsigned int line_width = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr].getLineWidth();
const double layer_height_mm = (layer_nr == 0)? train.getSettingInMillimeters("layer_height_0") : train.getSettingInMillimeters("layer_height");
const double normal_volume = INT2MM(INT2MM(purge_move_length * line_width)) * layer_height_mm; // Volume extruded on the "normal" move
float purge_flow = purge_volume / normal_volume;
// As we need a plan, which can't have a stationary extrusion, we use an extrusion move to prime.
// This has the added benefit that it will evenly spread the primed material inside the tower.
gcode_layer.addExtrusionMove(prime_start, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, purge_flow);
} else
{
// Normal move behavior to wipe start location.
GCodePath& toward_wipe_start = gcode_layer.addTravel_simple(prime_start);
toward_wipe_start.perform_z_hop = false;
toward_wipe_start.retract = true;
}
}
else
{
if(purge_volume > 0)
{
// Find location to start purge (we're purging right outside of the tower)
const Point purge_start = prime_start + normal(outward_dir, start_dist);
gcode_layer.addTravel(purge_start);
// Calculate how much we need to purge
int purge_move_length = vSize(purge_start - prime_start);
const unsigned int line_width = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr].getLineWidth();
const double layer_height_mm = (layer_nr == 0)? train.getSettingInMillimeters("layer_height_0") : train.getSettingInMillimeters("layer_height");
const double normal_volume = INT2MM(INT2MM(purge_move_length * line_width)) * layer_height_mm; // Volume extruded on the "normal" move
float purge_flow = purge_volume / normal_volume;
// As we need a plan, which can't have a stationary extrusion, we use an extrusion move to prime.
gcode_layer.addExtrusionMove(prime_start, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, purge_flow);
}
gcode_layer.addTravel(prime_start);
}
float flow = 0.0001; // Force this path being interpreted as an extrusion path, so that no Z hop will occur (TODO: really separately handle travel and extrusion moves)
gcode_layer.addExtrusionMove(prime_end, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, flow);
}
void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
const Polygons outside_polygon = ground_poly.getOutsidePolygons();
for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
{
storage.support.supportLayers[layer].supportAreas = storage.support.supportLayers[layer].supportAreas.difference(outside_polygon);
}
}
}//namespace cura
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageViewer2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageViewer2.h"
#include "vtkObjectFactory.h"
#include "vtkInteractorStyleImage.h"
#include "vtkCommand.h"
vtkCxxRevisionMacro(vtkImageViewer2, "1.8");
vtkStandardNewMacro(vtkImageViewer2);
//----------------------------------------------------------------------------
vtkImageViewer2::vtkImageViewer2()
{
this->RenderWindow = vtkRenderWindow::New();
this->Renderer = vtkRenderer::New();
this->ImageActor = vtkImageActor::New();
this->WindowLevel = vtkImageMapToWindowLevelColors::New();
// setup the pipeline
this->ImageActor->SetInput(this->WindowLevel->GetOutput());
this->Renderer->AddProp(this->ImageActor);
this->RenderWindow->AddRenderer(this->Renderer);
this->FirstRender = 1;
this->Interactor = 0;
this->InteractorStyle = 0;
}
//----------------------------------------------------------------------------
vtkImageViewer2::~vtkImageViewer2()
{
this->WindowLevel->Delete();
this->ImageActor->Delete();
this->Renderer->Delete();
this->RenderWindow->Delete();
if (this->Interactor)
{
this->Interactor->Delete();
}
if (this->InteractorStyle)
{
this->InteractorStyle->Delete();
}
}
//----------------------------------------------------------------------------
void vtkImageViewer2::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << *this->RenderWindow << endl;
os << indent << *this->Renderer << endl;
os << indent << *this->ImageActor << endl;
os << indent << *this->WindowLevel << endl;
}
//----------------------------------------------------------------------------
void vtkImageViewer2::SetSize(int a[2])
{
this->SetSize(a[0],a[1]);
}
//----------------------------------------------------------------------------
void vtkImageViewer2::SetPosition(int a[2])
{
this->SetPosition(a[0],a[1]);
}
class vtkImageViewer2Callback : public vtkCommand
{
public:
static vtkImageViewer2Callback *New() {
return new vtkImageViewer2Callback; }
void Execute(vtkObject *caller, unsigned long vtkNotUsed(event),
void *callData)
{
if (callData)
{
this->InitialWindow = this->IV->GetWindowLevel()->GetWindow();
this->InitialLevel = this->IV->GetWindowLevel()->GetLevel();
return;
}
// adjust the window level here
vtkInteractorStyleImage *isi =
static_cast<vtkInteractorStyleImage *>(caller);
int *size = this->IV->GetRenderWindow()->GetSize();
float window = this->InitialWindow;
float level = this->InitialLevel;
// compute normalized delta
float dx = 4.0 * (isi->GetWindowLevelCurrentPosition()[0] -
isi->GetWindowLevelStartPosition()[0]) / size[0];
float dy = 4.0 * (isi->GetWindowLevelStartPosition()[1] -
isi->GetWindowLevelCurrentPosition()[1]) / size[1];
// scale by current values
if (fabs(window) > 0.01)
{
dx = dx * window;
}
else
{
dx = dx * (window < 0 ? -0.01 : 0.01);
}
if (fabs(level) > 0.01)
{
dy = dy * level;
}
else
{
dy = dy * (level < 0 ? -0.01 : 0.01);
}
// abs so that direction does not flip
if (window < 0.0)
{
dx = -1*dx;
}
if (level < 0.0)
{
dy = -1*dy;
}
// compute new window level
float newWindow = dx + window;
float newLevel;
newLevel = level - dy;
// stay away from zero and really
if (fabs(newWindow) < 0.01)
{
newWindow = 0.01*(newWindow < 0 ? -1 : 1);
}
if (fabs(newLevel) < 0.01)
{
newLevel = 0.01*(newLevel < 0 ? -1 : 1);
}
this->IV->GetWindowLevel()->SetWindow(newWindow);
this->IV->GetWindowLevel()->SetLevel(newLevel);
this->IV->Render();
}
vtkImageViewer2 *IV;
float InitialWindow;
float InitialLevel;
};
void vtkImageViewer2::SetupInteractor(vtkRenderWindowInteractor *rwi)
{
if (this->Interactor && rwi != this->Interactor)
{
this->Interactor->Delete();
}
if (!this->InteractorStyle)
{
this->InteractorStyle = vtkInteractorStyleImage::New();
vtkImageViewer2Callback *cbk = vtkImageViewer2Callback::New();
cbk->IV = this;
this->InteractorStyle->AddObserver(vtkCommand::WindowLevelEvent,cbk);
cbk->Delete();
}
if (!this->Interactor)
{
this->Interactor = rwi;
rwi->Register(this);
}
this->Interactor->SetInteractorStyle(this->InteractorStyle);
this->Interactor->SetRenderWindow(this->RenderWindow);
}
void vtkImageViewer2::Render()
{
if (this->FirstRender)
{
// initialize the size if not set yet
if (this->RenderWindow->GetSize()[0] == 0 && this->ImageActor->GetInput())
{
// get the size from the mappers input
this->WindowLevel->GetInput()->UpdateInformation();
int *ext = this->WindowLevel->GetInput()->GetWholeExtent();
// if it would be smaller than 100 by 100 then limit to 100 by 100
int xs = ext[1] - ext[0] + 1;
int ys = ext[3] - ext[2] + 1;
this->RenderWindow->SetSize(xs < 150 ? 150 : xs,
ys < 100 ? 100 : ys);
this->Renderer->GetActiveCamera()->SetParallelScale(xs < 150 ? 75 : xs/2);
}
this->Renderer->GetActiveCamera()->ParallelProjectionOn();
this->FirstRender = 0;
}
this->RenderWindow->Render();
}
<commit_msg>minor change to parallel scaling<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageViewer2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageViewer2.h"
#include "vtkObjectFactory.h"
#include "vtkInteractorStyleImage.h"
#include "vtkCommand.h"
vtkCxxRevisionMacro(vtkImageViewer2, "1.9");
vtkStandardNewMacro(vtkImageViewer2);
//----------------------------------------------------------------------------
vtkImageViewer2::vtkImageViewer2()
{
this->RenderWindow = vtkRenderWindow::New();
this->Renderer = vtkRenderer::New();
this->ImageActor = vtkImageActor::New();
this->WindowLevel = vtkImageMapToWindowLevelColors::New();
// setup the pipeline
this->ImageActor->SetInput(this->WindowLevel->GetOutput());
this->Renderer->AddProp(this->ImageActor);
this->RenderWindow->AddRenderer(this->Renderer);
this->FirstRender = 1;
this->Interactor = 0;
this->InteractorStyle = 0;
}
//----------------------------------------------------------------------------
vtkImageViewer2::~vtkImageViewer2()
{
this->WindowLevel->Delete();
this->ImageActor->Delete();
this->Renderer->Delete();
this->RenderWindow->Delete();
if (this->Interactor)
{
this->Interactor->Delete();
}
if (this->InteractorStyle)
{
this->InteractorStyle->Delete();
}
}
//----------------------------------------------------------------------------
void vtkImageViewer2::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << *this->RenderWindow << endl;
os << indent << *this->Renderer << endl;
os << indent << *this->ImageActor << endl;
os << indent << *this->WindowLevel << endl;
}
//----------------------------------------------------------------------------
void vtkImageViewer2::SetSize(int a[2])
{
this->SetSize(a[0],a[1]);
}
//----------------------------------------------------------------------------
void vtkImageViewer2::SetPosition(int a[2])
{
this->SetPosition(a[0],a[1]);
}
class vtkImageViewer2Callback : public vtkCommand
{
public:
static vtkImageViewer2Callback *New() {
return new vtkImageViewer2Callback; }
void Execute(vtkObject *caller, unsigned long vtkNotUsed(event),
void *callData)
{
if (callData)
{
this->InitialWindow = this->IV->GetWindowLevel()->GetWindow();
this->InitialLevel = this->IV->GetWindowLevel()->GetLevel();
return;
}
// adjust the window level here
vtkInteractorStyleImage *isi =
static_cast<vtkInteractorStyleImage *>(caller);
int *size = this->IV->GetRenderWindow()->GetSize();
float window = this->InitialWindow;
float level = this->InitialLevel;
// compute normalized delta
float dx = 4.0 * (isi->GetWindowLevelCurrentPosition()[0] -
isi->GetWindowLevelStartPosition()[0]) / size[0];
float dy = 4.0 * (isi->GetWindowLevelStartPosition()[1] -
isi->GetWindowLevelCurrentPosition()[1]) / size[1];
// scale by current values
if (fabs(window) > 0.01)
{
dx = dx * window;
}
else
{
dx = dx * (window < 0 ? -0.01 : 0.01);
}
if (fabs(level) > 0.01)
{
dy = dy * level;
}
else
{
dy = dy * (level < 0 ? -0.01 : 0.01);
}
// abs so that direction does not flip
if (window < 0.0)
{
dx = -1*dx;
}
if (level < 0.0)
{
dy = -1*dy;
}
// compute new window level
float newWindow = dx + window;
float newLevel;
newLevel = level - dy;
// stay away from zero and really
if (fabs(newWindow) < 0.01)
{
newWindow = 0.01*(newWindow < 0 ? -1 : 1);
}
if (fabs(newLevel) < 0.01)
{
newLevel = 0.01*(newLevel < 0 ? -1 : 1);
}
this->IV->GetWindowLevel()->SetWindow(newWindow);
this->IV->GetWindowLevel()->SetLevel(newLevel);
this->IV->Render();
}
vtkImageViewer2 *IV;
float InitialWindow;
float InitialLevel;
};
void vtkImageViewer2::SetupInteractor(vtkRenderWindowInteractor *rwi)
{
if (this->Interactor && rwi != this->Interactor)
{
this->Interactor->Delete();
}
if (!this->InteractorStyle)
{
this->InteractorStyle = vtkInteractorStyleImage::New();
vtkImageViewer2Callback *cbk = vtkImageViewer2Callback::New();
cbk->IV = this;
this->InteractorStyle->AddObserver(vtkCommand::WindowLevelEvent,cbk);
cbk->Delete();
}
if (!this->Interactor)
{
this->Interactor = rwi;
rwi->Register(this);
}
this->Interactor->SetInteractorStyle(this->InteractorStyle);
this->Interactor->SetRenderWindow(this->RenderWindow);
}
void vtkImageViewer2::Render()
{
if (this->FirstRender)
{
// initialize the size if not set yet
if (this->RenderWindow->GetSize()[0] == 0 && this->ImageActor->GetInput())
{
// get the size from the mappers input
this->WindowLevel->GetInput()->UpdateInformation();
int *ext = this->WindowLevel->GetInput()->GetWholeExtent();
// if it would be smaller than 100 by 100 then limit to 100 by 100
int xs = ext[1] - ext[0] + 1;
int ys = ext[3] - ext[2] + 1;
this->RenderWindow->SetSize(xs < 150 ? 150 : xs,
ys < 100 ? 100 : ys);
this->Renderer->GetActiveCamera()->SetParallelScale(xs < 150 ? 75 : (xs-1)/2.0);
}
this->Renderer->GetActiveCamera()->ParallelProjectionOn();
this->FirstRender = 0;
}
this->RenderWindow->Render();
}
<|endoftext|> |
<commit_before>#include "opengl_properties.h"
int
main (void)
{
print_opengl_properties();
}
<commit_msg>Fixed Illegal instruction bug<commit_after>#include "opengl_properties.h"
#include <GL/glew.h>
#include <SDL/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
void
init_opengl ()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(20.0f);
}
void
quit (int return_code)
{
SDL_Quit();
exit(return_code);
}
void
init_sdl ()
{
const SDL_VideoInfo *video_info;
if (SDL_Init( SDL_INIT_VIDEO ) < 0)
{
fprintf(stderr, "Video initialization failed: %s", SDL_GetError());
quit(1);
}
video_info = SDL_GetVideoInfo();
if (!video_info)
{
fprintf(stderr, "Video info query failed: %s", SDL_GetError());
quit(1);
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);
SDL_Surface *surface = SDL_SetVideoMode(600, 600, 32,
SDL_OPENGL | SDL_GL_DOUBLEBUFFER);
if (!surface)
{
fprintf(stderr, "Video mode set failed: %s", SDL_GetError());
quit(1);
}
}
void
init_extensions ()
{
bool vbo_capable = false;
GLenum err = glewInit();
if (err != GLEW_OK)
{
printf("GLEW initialization error: %s\n", glewGetErrorString(err));
return;
}
vbo_capable = GL_ARB_vertex_buffer_object;
}
int
main (int argc, char *argv[])
{
init_sdl();
print_opengl_properties();
quit(0);
}
<|endoftext|> |
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "namenode_info.h"
#include "common/util.h"
#include "common/logging.h"
#include <sstream>
#include <utility>
#include <future>
#include <memory>
namespace hdfs {
ResolvedNamenodeInfo& ResolvedNamenodeInfo::operator=(const NamenodeInfo &info) {
nameservice = info.nameservice;
name = info.name;
uri = info.uri;
return *this;
}
std::string ResolvedNamenodeInfo::str() const {
std::stringstream ss;
ss << "ResolvedNamenodeInfo {nameservice: " << nameservice << ", name: " << name << ", uri: " << uri.str();
ss << ", host: " << uri.get_host();
auto port = uri.get_port();
if(port)
ss << ", port: " << port.value();
else
ss << ", port: unable to parse";
ss << ", scheme: " << uri.get_scheme();
ss << " [";
for(unsigned int i=0;i<endpoints.size();i++)
ss << endpoints[i] << " ";
ss << "] }";
return ss.str();
}
bool ResolveInPlace(::asio::io_service *ioservice, ResolvedNamenodeInfo &info) {
// this isn't very memory friendly, but if it needs to be called often there are bigger issues at hand
info.endpoints.clear();
std::vector<ResolvedNamenodeInfo> resolved = BulkResolve(ioservice, {info});
if(resolved.size() != 1)
return false;
info.endpoints = resolved[0].endpoints;
if(info.endpoints.size() == 0)
return false;
return true;
}
typedef std::vector<asio::ip::tcp::endpoint> endpoint_vector;
// RAII wrapper
class ScopedResolver {
private:
::asio::io_service *io_service_;
std::string host_;
std::string port_;
::asio::ip::tcp::resolver::query query_;
::asio::ip::tcp::resolver resolver_;
endpoint_vector endpoints_;
// Caller blocks on access if resolution isn't finished
std::shared_ptr<std::promise<Status>> result_status_;
public:
ScopedResolver(::asio::io_service *service, const std::string &host, const std::string &port) :
io_service_(service), host_(host), port_(port), query_(host, port), resolver_(*io_service_)
{
if(!io_service_)
LOG_ERROR(kAsyncRuntime, << "ScopedResolver@" << this << " passed nullptr to io_service");
}
~ScopedResolver() {
resolver_.cancel();
}
bool BeginAsyncResolve() {
// result_status_ would only exist if this was previously called. Invalid state.
if(result_status_) {
LOG_ERROR(kAsyncRuntime, << "ScopedResolver@" << this << "::BeginAsyncResolve invalid call: may only be called once per instance");
return false;
} else if(!io_service_) {
LOG_ERROR(kAsyncRuntime, << "ScopedResolver@" << this << "::BeginAsyncResolve invalid call: null io_service");
return false;
}
// Now set up the promise, set it in async_resolve's callback
result_status_ = std::make_shared<std::promise<Status>>();
// Callback to pull a copy of endpoints out of resolver and set promise
auto callback = [this](const asio::error_code &ec, ::asio::ip::tcp::resolver::iterator out) {
if(!ec) {
std::copy(out, ::asio::ip::tcp::resolver::iterator(), std::back_inserter(endpoints_));
}
result_status_->set_value( ToStatus(ec) );
};
resolver_.async_resolve(query_, callback);
return true;
}
Status Join() {
if(!result_status_) {
std::ostringstream errmsg;
errmsg << "ScopedResolver@" << this << "Join invalid call: promise never set";
return Status::InvalidArgument(errmsg.str().c_str());
}
std::future<Status> future_result = result_status_->get_future();
Status res = future_result.get();
return res;
}
endpoint_vector GetEndpoints() {
// Explicitly return by value to decouple lifecycles.
return endpoints_;
}
};
std::vector<ResolvedNamenodeInfo> BulkResolve(::asio::io_service *ioservice, const std::vector<NamenodeInfo> &nodes) {
std::vector< std::unique_ptr<ScopedResolver> > resolvers;
resolvers.reserve(nodes.size());
std::vector<ResolvedNamenodeInfo> resolved_info;
resolved_info.reserve(nodes.size());
for(unsigned int i=0; i<nodes.size(); i++) {
std::string host = nodes[i].get_host();
std::string port = nodes[i].get_port();
resolvers.emplace_back(new ScopedResolver(ioservice, host, port));
resolvers[i]->BeginAsyncResolve();
}
// Join all async operations
for(unsigned int i=0; i < resolvers.size(); i++) {
Status asyncReturnStatus = resolvers[i]->Join();
ResolvedNamenodeInfo info;
info = nodes[i];
if(asyncReturnStatus.ok()) {
// Copy out endpoints if things went well
info.endpoints = resolvers[i]->GetEndpoints();
} else {
LOG_ERROR(kAsyncRuntime, << "Unabled to resolve endpoints for host: " << nodes[i].get_host()
<< " port: " << nodes[i].get_port());
}
resolved_info.push_back(info);
}
return resolved_info;
}
}
<commit_msg>HDFS-11436: libhdfs++: Fix race condition in ScopedResolver. Contributed by James Clampffer.<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "namenode_info.h"
#include "common/util.h"
#include "common/logging.h"
#include <sstream>
#include <utility>
#include <future>
#include <memory>
namespace hdfs {
ResolvedNamenodeInfo& ResolvedNamenodeInfo::operator=(const NamenodeInfo &info) {
nameservice = info.nameservice;
name = info.name;
uri = info.uri;
return *this;
}
std::string ResolvedNamenodeInfo::str() const {
std::stringstream ss;
ss << "ResolvedNamenodeInfo {nameservice: " << nameservice << ", name: " << name << ", uri: " << uri.str();
ss << ", host: " << uri.get_host();
auto port = uri.get_port();
if(port)
ss << ", port: " << port.value();
else
ss << ", port: unable to parse";
ss << ", scheme: " << uri.get_scheme();
ss << " [";
for(unsigned int i=0;i<endpoints.size();i++)
ss << endpoints[i] << " ";
ss << "] }";
return ss.str();
}
bool ResolveInPlace(::asio::io_service *ioservice, ResolvedNamenodeInfo &info) {
// this isn't very memory friendly, but if it needs to be called often there are bigger issues at hand
info.endpoints.clear();
std::vector<ResolvedNamenodeInfo> resolved = BulkResolve(ioservice, {info});
if(resolved.size() != 1)
return false;
info.endpoints = resolved[0].endpoints;
if(info.endpoints.size() == 0)
return false;
return true;
}
typedef std::vector<asio::ip::tcp::endpoint> endpoint_vector;
// RAII wrapper
class ScopedResolver {
private:
::asio::io_service *io_service_;
std::string host_;
std::string port_;
::asio::ip::tcp::resolver::query query_;
::asio::ip::tcp::resolver resolver_;
endpoint_vector endpoints_;
// Caller blocks on access if resolution isn't finished
std::shared_ptr<std::promise<Status>> result_status_;
public:
ScopedResolver(::asio::io_service *service, const std::string &host, const std::string &port) :
io_service_(service), host_(host), port_(port), query_(host, port), resolver_(*io_service_)
{
if(!io_service_)
LOG_ERROR(kAsyncRuntime, << "ScopedResolver@" << this << " passed nullptr to io_service");
}
~ScopedResolver() {
resolver_.cancel();
}
bool BeginAsyncResolve() {
// result_status_ would only exist if this was previously called. Invalid state.
if(result_status_) {
LOG_ERROR(kAsyncRuntime, << "ScopedResolver@" << this << "::BeginAsyncResolve invalid call: may only be called once per instance");
return false;
} else if(!io_service_) {
LOG_ERROR(kAsyncRuntime, << "ScopedResolver@" << this << "::BeginAsyncResolve invalid call: null io_service");
return false;
}
// Now set up the promise, set it in async_resolve's callback
result_status_ = std::make_shared<std::promise<Status>>();
std::shared_ptr<std::promise<Status>> shared_result = result_status_;
// Callback to pull a copy of endpoints out of resolver and set promise
auto callback = [this, shared_result](const asio::error_code &ec, ::asio::ip::tcp::resolver::iterator out) {
if(!ec) {
std::copy(out, ::asio::ip::tcp::resolver::iterator(), std::back_inserter(endpoints_));
}
shared_result->set_value( ToStatus(ec) );
};
resolver_.async_resolve(query_, callback);
return true;
}
Status Join() {
if(!result_status_) {
std::ostringstream errmsg;
errmsg << "ScopedResolver@" << this << "Join invalid call: promise never set";
return Status::InvalidArgument(errmsg.str().c_str());
}
std::future<Status> future_result = result_status_->get_future();
Status res = future_result.get();
return res;
}
endpoint_vector GetEndpoints() {
// Explicitly return by value to decouple lifecycles.
return endpoints_;
}
};
std::vector<ResolvedNamenodeInfo> BulkResolve(::asio::io_service *ioservice, const std::vector<NamenodeInfo> &nodes) {
std::vector< std::unique_ptr<ScopedResolver> > resolvers;
resolvers.reserve(nodes.size());
std::vector<ResolvedNamenodeInfo> resolved_info;
resolved_info.reserve(nodes.size());
for(unsigned int i=0; i<nodes.size(); i++) {
std::string host = nodes[i].get_host();
std::string port = nodes[i].get_port();
resolvers.emplace_back(new ScopedResolver(ioservice, host, port));
resolvers[i]->BeginAsyncResolve();
}
// Join all async operations
for(unsigned int i=0; i < resolvers.size(); i++) {
Status asyncReturnStatus = resolvers[i]->Join();
ResolvedNamenodeInfo info;
info = nodes[i];
if(asyncReturnStatus.ok()) {
// Copy out endpoints if things went well
info.endpoints = resolvers[i]->GetEndpoints();
} else {
LOG_ERROR(kAsyncRuntime, << "Unabled to resolve endpoints for host: " << nodes[i].get_host()
<< " port: " << nodes[i].get_port());
}
resolved_info.push_back(info);
}
return resolved_info;
}
}
<|endoftext|> |
<commit_before>
#include <osgParticle/ParticleSystemUpdater>
#include <osg/ref_ptr>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
bool PSU_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool PSU_writeLocalData(const osg::Object &obj, osgDB::Output &fr);
osgDB::RegisterDotOsgWrapperProxy PSU_Proxy
(
new osgParticle::ParticleSystemUpdater,
"ParticleSystemUpdater",
"Object Node ParticleSystemUpdater",
PSU_readLocalData,
PSU_writeLocalData
);
bool PSU_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osgParticle::ParticleSystemUpdater &myobj = static_cast<osgParticle::ParticleSystemUpdater &>(obj);
bool itAdvanced = false;
osg::ref_ptr<osgParticle::ParticleSystem> proto = new osgParticle::ParticleSystem;
osgParticle::ParticleSystem *ps = static_cast<osgParticle::ParticleSystem *>(fr.readObjectOfType(*proto));
if (ps) {
myobj.addParticleSystem(ps);
itAdvanced = true;
}
return itAdvanced;
}
bool PSU_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osgParticle::ParticleSystemUpdater &myobj = static_cast<const osgParticle::ParticleSystemUpdater &>(obj);
for (int i=0; i<myobj.getNumParticleSystems(); ++i) {
fw.writeObject(*myobj.getParticleSystem(i));
}
return true;
}
<commit_msg>Warnings fix for VS7.0 from Mike Weiblen<commit_after>
#include <osgParticle/ParticleSystemUpdater>
#include <osg/ref_ptr>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
bool PSU_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool PSU_writeLocalData(const osg::Object &obj, osgDB::Output &fr);
osgDB::RegisterDotOsgWrapperProxy PSU_Proxy
(
new osgParticle::ParticleSystemUpdater,
"ParticleSystemUpdater",
"Object Node ParticleSystemUpdater",
PSU_readLocalData,
PSU_writeLocalData
);
bool PSU_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osgParticle::ParticleSystemUpdater &myobj = static_cast<osgParticle::ParticleSystemUpdater &>(obj);
bool itAdvanced = false;
osg::ref_ptr<osgParticle::ParticleSystem> proto = new osgParticle::ParticleSystem;
osgParticle::ParticleSystem *ps = static_cast<osgParticle::ParticleSystem *>(fr.readObjectOfType(*proto));
if (ps) {
myobj.addParticleSystem(ps);
itAdvanced = true;
}
return itAdvanced;
}
bool PSU_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osgParticle::ParticleSystemUpdater &myobj = static_cast<const osgParticle::ParticleSystemUpdater &>(obj);
for (unsigned int i=0; i<myobj.getNumParticleSystems(); ++i) {
fw.writeObject(*myobj.getParticleSystem(i));
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright 2014 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 "net/http/disk_cache_based_quic_server_info.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
#include "net/base/net_errors.h"
#include "net/http/mock_http_cache.h"
#include "net/quic/crypto/quic_server_info.h"
#include "net/quic/quic_session_key.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// This is an empty transaction, needed to register the URL and the test mode.
const MockTransaction kHostInfoTransaction1 = {
"quicserverinfo:https://www.google.com:443",
"",
base::Time(),
"",
net::LOAD_NORMAL,
"",
"",
base::Time(),
"",
TEST_MODE_NORMAL,
NULL,
0
};
const MockTransaction kHostInfoTransaction2 = {
"quicserverinfo:http://www.google.com:80",
"",
base::Time(),
"",
net::LOAD_NORMAL,
"",
"",
base::Time(),
"",
TEST_MODE_NORMAL,
NULL,
0
};
// Tests that we can delete a DiskCacheBasedQuicServerInfo object in a
// completion callback for DiskCacheBasedQuicServerInfo::WaitForDataReady.
TEST(DiskCacheBasedQuicServerInfo, DeleteInCallback) {
// Use the blocking mock backend factory to force asynchronous completion
// of quic_server_info->WaitForDataReady(), so that the callback will run.
MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
MockHttpCache cache(factory);
net::QuicSessionKey server_key("www.verisign.com", 443, true);
scoped_ptr<net::QuicServerInfo> quic_server_info(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
net::TestCompletionCallback callback;
int rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, rv);
// Now complete the backend creation and let the callback run.
factory->FinishCreation();
EXPECT_EQ(net::OK, callback.GetResult(rv));
}
// Tests the basic logic of storing, retrieving and updating data.
TEST(DiskCacheBasedQuicServerInfo, Update) {
MockHttpCache cache;
AddMockTransaction(&kHostInfoTransaction1);
net::TestCompletionCallback callback;
net::QuicSessionKey server_key("www.google.com", 443, true);
scoped_ptr<net::QuicServerInfo> quic_server_info(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
int rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
net::QuicServerInfo::State* state = quic_server_info->mutable_state();
EXPECT_TRUE(state->certs.empty());
const string server_config_a = "server_config_a";
const string source_address_token_a = "source_address_token_a";
const string server_config_sig_a = "server_config_sig_a";
const string cert_a = "cert_a";
const string cert_b = "cert_b";
state->server_config = server_config_a;
state->source_address_token = source_address_token_a;
state->server_config_sig = server_config_sig_a;
state->certs.push_back(cert_a);
quic_server_info->Persist();
// Wait until Persist() does the work.
base::MessageLoop::current()->RunUntilIdle();
// Open the stored QuicServerInfo.
quic_server_info.reset(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
// And now update the data.
state = quic_server_info->mutable_state();
state->certs.push_back(cert_b);
// Fail instead of DCHECKing double creates.
cache.disk_cache()->set_double_create_check(false);
quic_server_info->Persist();
base::MessageLoop::current()->RunUntilIdle();
// Verify that the state was updated.
quic_server_info.reset(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
const net::QuicServerInfo::State& state1 = quic_server_info->state();
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(server_config_a, state1.server_config);
EXPECT_EQ(source_address_token_a, state1.source_address_token);
EXPECT_EQ(server_config_sig_a, state1.server_config_sig);
EXPECT_EQ(2U, state1.certs.size());
EXPECT_EQ(cert_a, state1.certs[0]);
EXPECT_EQ(cert_b, state1.certs[1]);
RemoveMockTransaction(&kHostInfoTransaction1);
}
// Test that demonstrates different info is returned when the ports differ.
TEST(DiskCacheBasedQuicServerInfo, UpdateDifferentPorts) {
MockHttpCache cache;
AddMockTransaction(&kHostInfoTransaction1);
AddMockTransaction(&kHostInfoTransaction2);
net::TestCompletionCallback callback;
// Persist data for port 443.
net::QuicSessionKey server_key1("www.google.com", 443, true);
scoped_ptr<net::QuicServerInfo> quic_server_info1(
new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
quic_server_info1->Start();
int rv = quic_server_info1->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
net::QuicServerInfo::State* state1 = quic_server_info1->mutable_state();
EXPECT_TRUE(state1->certs.empty());
const string server_config_a = "server_config_a";
const string source_address_token_a = "source_address_token_a";
const string server_config_sig_a = "server_config_sig_a";
const string cert_a = "cert_a";
state1->server_config = server_config_a;
state1->source_address_token = source_address_token_a;
state1->server_config_sig = server_config_sig_a;
state1->certs.push_back(cert_a);
quic_server_info1->Persist();
// Wait until Persist() does the work.
base::MessageLoop::current()->RunUntilIdle();
// Persist data for port 80.
net::QuicSessionKey server_key2("www.google.com", 80, false);
scoped_ptr<net::QuicServerInfo> quic_server_info2(
new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
quic_server_info2->Start();
rv = quic_server_info2->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
net::QuicServerInfo::State* state2 = quic_server_info2->mutable_state();
EXPECT_TRUE(state2->certs.empty());
const string server_config_b = "server_config_b";
const string source_address_token_b = "source_address_token_b";
const string server_config_sig_b = "server_config_sig_b";
const string cert_b = "cert_b";
state2->server_config = server_config_b;
state2->source_address_token = source_address_token_b;
state2->server_config_sig = server_config_sig_b;
state2->certs.push_back(cert_b);
quic_server_info2->Persist();
// Wait until Persist() does the work.
base::MessageLoop::current()->RunUntilIdle();
// Verify the stored QuicServerInfo for port 443.
scoped_ptr<net::QuicServerInfo> quic_server_info(
new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
const net::QuicServerInfo::State& state_a = quic_server_info->state();
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(server_config_a, state_a.server_config);
EXPECT_EQ(source_address_token_a, state_a.source_address_token);
EXPECT_EQ(server_config_sig_a, state_a.server_config_sig);
EXPECT_EQ(1U, state_a.certs.size());
EXPECT_EQ(cert_a, state_a.certs[0]);
// Verify the stored QuicServerInfo for port 80.
quic_server_info.reset(
new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
const net::QuicServerInfo::State& state_b = quic_server_info->state();
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(server_config_b, state_b.server_config);
EXPECT_EQ(source_address_token_b, state_b.source_address_token);
EXPECT_EQ(server_config_sig_b, state_b.server_config_sig);
EXPECT_EQ(1U, state_b.certs.size());
EXPECT_EQ(cert_b, state_b.certs[0]);
RemoveMockTransaction(&kHostInfoTransaction2);
RemoveMockTransaction(&kHostInfoTransaction1);
}
} // namespace
<commit_msg>QUIC - Added unit test for IsDataReady to verify that it returns false if there is a pending write. IsDataReady is called before we save the server config to disk cache.<commit_after>// Copyright 2014 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 "net/http/disk_cache_based_quic_server_info.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
#include "net/base/net_errors.h"
#include "net/http/mock_http_cache.h"
#include "net/quic/crypto/quic_server_info.h"
#include "net/quic/quic_session_key.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// This is an empty transaction, needed to register the URL and the test mode.
const MockTransaction kHostInfoTransaction1 = {
"quicserverinfo:https://www.google.com:443",
"",
base::Time(),
"",
net::LOAD_NORMAL,
"",
"",
base::Time(),
"",
TEST_MODE_NORMAL,
NULL,
0
};
const MockTransaction kHostInfoTransaction2 = {
"quicserverinfo:http://www.google.com:80",
"",
base::Time(),
"",
net::LOAD_NORMAL,
"",
"",
base::Time(),
"",
TEST_MODE_NORMAL,
NULL,
0
};
// Tests that we can delete a DiskCacheBasedQuicServerInfo object in a
// completion callback for DiskCacheBasedQuicServerInfo::WaitForDataReady.
TEST(DiskCacheBasedQuicServerInfo, DeleteInCallback) {
// Use the blocking mock backend factory to force asynchronous completion
// of quic_server_info->WaitForDataReady(), so that the callback will run.
MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
MockHttpCache cache(factory);
net::QuicSessionKey server_key("www.verisign.com", 443, true);
scoped_ptr<net::QuicServerInfo> quic_server_info(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
net::TestCompletionCallback callback;
int rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::ERR_IO_PENDING, rv);
// Now complete the backend creation and let the callback run.
factory->FinishCreation();
EXPECT_EQ(net::OK, callback.GetResult(rv));
}
// Tests the basic logic of storing, retrieving and updating data.
TEST(DiskCacheBasedQuicServerInfo, Update) {
MockHttpCache cache;
AddMockTransaction(&kHostInfoTransaction1);
net::TestCompletionCallback callback;
net::QuicSessionKey server_key("www.google.com", 443, true);
scoped_ptr<net::QuicServerInfo> quic_server_info(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
int rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
net::QuicServerInfo::State* state = quic_server_info->mutable_state();
EXPECT_TRUE(state->certs.empty());
const string server_config_a = "server_config_a";
const string source_address_token_a = "source_address_token_a";
const string server_config_sig_a = "server_config_sig_a";
const string cert_a = "cert_a";
const string cert_b = "cert_b";
state->server_config = server_config_a;
state->source_address_token = source_address_token_a;
state->server_config_sig = server_config_sig_a;
state->certs.push_back(cert_a);
quic_server_info->Persist();
// Wait until Persist() does the work.
base::MessageLoop::current()->RunUntilIdle();
// Open the stored QuicServerInfo.
quic_server_info.reset(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
// And now update the data.
state = quic_server_info->mutable_state();
state->certs.push_back(cert_b);
// Fail instead of DCHECKing double creates.
cache.disk_cache()->set_double_create_check(false);
quic_server_info->Persist();
base::MessageLoop::current()->RunUntilIdle();
// Verify that the state was updated.
quic_server_info.reset(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
const net::QuicServerInfo::State& state1 = quic_server_info->state();
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(server_config_a, state1.server_config);
EXPECT_EQ(source_address_token_a, state1.source_address_token);
EXPECT_EQ(server_config_sig_a, state1.server_config_sig);
EXPECT_EQ(2U, state1.certs.size());
EXPECT_EQ(cert_a, state1.certs[0]);
EXPECT_EQ(cert_b, state1.certs[1]);
RemoveMockTransaction(&kHostInfoTransaction1);
}
// Test that demonstrates different info is returned when the ports differ.
TEST(DiskCacheBasedQuicServerInfo, UpdateDifferentPorts) {
MockHttpCache cache;
AddMockTransaction(&kHostInfoTransaction1);
AddMockTransaction(&kHostInfoTransaction2);
net::TestCompletionCallback callback;
// Persist data for port 443.
net::QuicSessionKey server_key1("www.google.com", 443, true);
scoped_ptr<net::QuicServerInfo> quic_server_info1(
new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
quic_server_info1->Start();
int rv = quic_server_info1->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
net::QuicServerInfo::State* state1 = quic_server_info1->mutable_state();
EXPECT_TRUE(state1->certs.empty());
const string server_config_a = "server_config_a";
const string source_address_token_a = "source_address_token_a";
const string server_config_sig_a = "server_config_sig_a";
const string cert_a = "cert_a";
state1->server_config = server_config_a;
state1->source_address_token = source_address_token_a;
state1->server_config_sig = server_config_sig_a;
state1->certs.push_back(cert_a);
quic_server_info1->Persist();
// Wait until Persist() does the work.
base::MessageLoop::current()->RunUntilIdle();
// Persist data for port 80.
net::QuicSessionKey server_key2("www.google.com", 80, false);
scoped_ptr<net::QuicServerInfo> quic_server_info2(
new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
quic_server_info2->Start();
rv = quic_server_info2->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
net::QuicServerInfo::State* state2 = quic_server_info2->mutable_state();
EXPECT_TRUE(state2->certs.empty());
const string server_config_b = "server_config_b";
const string source_address_token_b = "source_address_token_b";
const string server_config_sig_b = "server_config_sig_b";
const string cert_b = "cert_b";
state2->server_config = server_config_b;
state2->source_address_token = source_address_token_b;
state2->server_config_sig = server_config_sig_b;
state2->certs.push_back(cert_b);
quic_server_info2->Persist();
// Wait until Persist() does the work.
base::MessageLoop::current()->RunUntilIdle();
// Verify the stored QuicServerInfo for port 443.
scoped_ptr<net::QuicServerInfo> quic_server_info(
new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
const net::QuicServerInfo::State& state_a = quic_server_info->state();
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(server_config_a, state_a.server_config);
EXPECT_EQ(source_address_token_a, state_a.source_address_token);
EXPECT_EQ(server_config_sig_a, state_a.server_config_sig);
EXPECT_EQ(1U, state_a.certs.size());
EXPECT_EQ(cert_a, state_a.certs[0]);
// Verify the stored QuicServerInfo for port 80.
quic_server_info.reset(
new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
const net::QuicServerInfo::State& state_b = quic_server_info->state();
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(server_config_b, state_b.server_config);
EXPECT_EQ(source_address_token_b, state_b.source_address_token);
EXPECT_EQ(server_config_sig_b, state_b.server_config_sig);
EXPECT_EQ(1U, state_b.certs.size());
EXPECT_EQ(cert_b, state_b.certs[0]);
RemoveMockTransaction(&kHostInfoTransaction2);
RemoveMockTransaction(&kHostInfoTransaction1);
}
// Test IsDataReady when there is a pending write.
TEST(DiskCacheBasedQuicServerInfo, IsDataReady) {
MockHttpCache cache;
AddMockTransaction(&kHostInfoTransaction1);
net::TestCompletionCallback callback;
net::QuicSessionKey server_key("www.google.com", 443, true);
scoped_ptr<net::QuicServerInfo> quic_server_info(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
EXPECT_TRUE(quic_server_info->IsDataReady());
int rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(net::OK, callback.GetResult(rv));
net::QuicServerInfo::State* state = quic_server_info->mutable_state();
EXPECT_TRUE(state->certs.empty());
const string server_config_a = "server_config_a";
const string source_address_token_a = "source_address_token_a";
const string server_config_sig_a = "server_config_sig_a";
const string cert_a = "cert_a";
state->server_config = server_config_a;
state->source_address_token = source_address_token_a;
state->server_config_sig = server_config_sig_a;
state->certs.push_back(cert_a);
EXPECT_TRUE(quic_server_info->IsDataReady());
quic_server_info->Persist();
// Once we call Persist, IsDataReady should return false until Persist has
// completed.
EXPECT_FALSE(quic_server_info->IsDataReady());
// Wait until Persist() does the work.
base::MessageLoop::current()->RunUntilIdle();
EXPECT_TRUE(quic_server_info->IsDataReady());
// Verify that the state was updated.
quic_server_info.reset(
new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
quic_server_info->Start();
rv = quic_server_info->WaitForDataReady(callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(rv));
EXPECT_TRUE(quic_server_info->IsDataReady());
const net::QuicServerInfo::State& state1 = quic_server_info->state();
EXPECT_TRUE(quic_server_info->IsDataReady());
EXPECT_EQ(server_config_a, state1.server_config);
EXPECT_EQ(source_address_token_a, state1.source_address_token);
EXPECT_EQ(server_config_sig_a, state1.server_config_sig);
EXPECT_EQ(1U, state1.certs.size());
EXPECT_EQ(cert_a, state1.certs[0]);
RemoveMockTransaction(&kHostInfoTransaction1);
}
} // namespace
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include "CharCounter.h"
#include "Dictionary.h"
static Dictionary dict;
void output(const std::string& result, const std::vector<std::string>& prefixes = {}) {
static unsigned long count = 0;
std::cout << std::setw(10) << ++count << ": ";
for (const std::string& prefix : prefixes) {
std::cout << prefix << " ";
}
std::cout << result << std::endl;
}
void findAnagrams(Dictionary::Iterator* it, CharCounter* counter) {
if (counter->empty()) {
output(it->word());
return;
}
for (unsigned i = 0; i < counter->unique(); ++i) {
char ch = (*counter)[i];
if (it->move(ch)) {
counter->remove(i);
findAnagrams(it, counter);
counter->restore(ch, i);
it->back();
}
}
}
void findMultiwordAnagrams(Dictionary::Iterator* it, CharCounter* counter, std::vector<std::string>* prefixes) {
if (counter->empty() && it->isWord()) {
output(it->word(), *prefixes);
return;
}
for (unsigned i = 0; i < counter->unique(); ++i) {
char ch = (*counter)[i];
if (it->move(ch)) {
counter->remove(i);
if (it->isWord()) {
Dictionary::Iterator new_it(dict.iterator());
prefixes->emplace_back(it->word());
findMultiwordAnagrams(&new_it, counter, prefixes);
prefixes->pop_back();
}
findMultiwordAnagrams(it, counter, prefixes);
counter->restore(ch, i);
it->back();
}
}
}
#include <fstream>
int main(int argc, char* argv[]) {
std::ifstream wordlist("good_dictionary");
dict.readFromFile(wordlist);
for (int i = 1; i < argc; ++i) {
CharCounter counter(argv[i]);
std::cout << argv[i] << ": " << counter << std::endl;
Dictionary::Iterator it(dict.iterator());
//findAnagrams(&it, &counter);
std::vector<std::string> prefixes;
findMultiwordAnagrams(&it, &counter, &prefixes);
}
}
<commit_msg>Command line options<commit_after>#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include "CharCounter.h"
#include "Dictionary.h"
static Dictionary dict;
void output(const std::string& result, const std::vector<std::string>& prefixes = {}) {
for (const std::string& prefix : prefixes) {
std::cout << prefix << " ";
}
std::cout << result << std::endl;
}
void findAnagrams(Dictionary::Iterator* it, CharCounter* counter) {
if (counter->empty()) {
if (it->isWord()) output(it->word());
return;
}
for (unsigned i = 0; i < counter->unique(); ++i) {
char ch = (*counter)[i];
if (it->move(ch)) {
counter->remove(i);
findAnagrams(it, counter);
counter->restore(ch, i);
it->back();
}
}
}
void findMultiwordAnagrams(Dictionary::Iterator* it, CharCounter* counter, std::vector<std::string>* prefixes) {
if (counter->empty()) {
if (it->isWord()) output(it->word(), *prefixes);
return;
}
for (unsigned i = 0; i < counter->unique(); ++i) {
char ch = (*counter)[i];
if (it->move(ch)) {
counter->remove(i);
if (it->isWord()) {
Dictionary::Iterator new_it(dict.iterator());
prefixes->emplace_back(it->word());
findMultiwordAnagrams(&new_it, counter, prefixes);
prefixes->pop_back();
}
findMultiwordAnagrams(it, counter, prefixes);
counter->restore(ch, i);
it->back();
}
}
}
#include <fstream>
void printUsage(const char* prog_name) {
std::cerr << "Find all anagrams of a word or phrase. The anagrams are output one per line.\n"
<< "\n"
<< "Usage:\n"
<< "\t" << prog_name << " [-s] [-d DICTIONARY_FILE] PHRASE...\n"
"\n"
"\tPHRASE\tThe word or words of which to find anagrams.\n"
"\n"
"\t-d\tSpecify which dictionary file to use. Default: \"dictionary\"\n"
"\t-h\tDisplay this message. In case you forgot something?\n"
"\t-s\tOnly find single-word anagrams.\n"
<< std::endl;
}
template<typename T>
bool parseOptions(int argc, char* argv[], T* settings) {
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
for (char *c = &argv[i][1]; *c != '\0'; ++c) {
switch (*c) {
case 'd':
if (i < (argc-1)){
settings->dictionary = argv[++i];
}
else {
printf("No value provided for -%c option.\n", *c);
return false;
}
break;
case 'h': printUsage(argv[0]); return false;
case 's': settings->single_word = true; break;
default:
printf("Unknown option \"%s\".\n", argv[i]);
printUsage(argv[0]);
return false;
}
}
}
else {
settings->phrase += argv[i];
}
}
return true;
}
int main(int argc, char* argv[]) {
using namespace std;
struct {
bool single_word = false;
std::string dictionary = "dictionary";
std::string phrase;
} settings;
if (!parseOptions(argc, argv, &settings)) {
return 1;
}
if (!Dictionary::processWord(&settings.phrase)) {
cerr << "Illegal character in " << settings.phrase
<< ". Only the 26 characters of the Latin alphabet are allowed." << endl;
return 1;
}
std::ifstream wordlist(settings.dictionary);
if (!wordlist.is_open()) {
cerr << "Cannot find dictionary file \"" << settings.dictionary << "\"." << endl;
return 1;
}
dict.readFromFile(wordlist);
CharCounter counter(settings.phrase);
Dictionary::Iterator it(dict.iterator());
if (settings.single_word) {
findAnagrams(&it, &counter);
}
else {
std::vector<std::string> prefixes;
findMultiwordAnagrams(&it, &counter, &prefixes);
}
return 0;
}
<|endoftext|> |
<commit_before>//=============================================================================
// ■ tiled_map.cpp
//-----------------------------------------------------------------------------
// Tile地图
//=============================================================================
#include "tiled_map.hpp"
namespace VM76 {
void TiledMap::init_cinstances (Tiles* cinstance[]) {
#define FILL_ID(id, f) cinstance[id - 1] = new f;
FILL_ID(Grass, MultiFaceCubeTile(49,49,0,2,49,49))
FILL_ID(Stone, SimpleCubeTile(1))
FILL_ID(Dirt, SimpleCubeTile(2))
FILL_ID(Glass, SimpleCubeTile(3))
FILL_ID(WoodPlank, SimpleCubeTile(4))
FILL_ID(HalfBrick, MultiFaceCubeTile(5,5,6,6,5,5))
FILL_ID(Brick, SimpleCubeTile(7))
FILL_ID(TNT, MultiFaceCubeTile(8,8,9,10,8,8))
FILL_ID(CobbleStone, SimpleCubeTile(16))
// Fill the rest with MISSING TEXTURE
for (int i = CobbleStone; i < 16; i ++) {
FILL_ID(i + 1, SimpleCubeTile(31))
}
#undef FILL_ID
}
Tiles* TiledMap::get_instances (int id) {
switch (id) {
case Grass:
return new MultiFaceCubeTile(49,49,0,2,49,49);
break;
case Stone:
return new SimpleCubeTile(1);
break;
case Dirt:
return new SimpleCubeTile(2);
break;
case Glass:
return new SimpleCubeTile(3);
break;
case WoodPlank:
return new SimpleCubeTile(4);
break;
case HalfBrick:
return new MultiFaceCubeTile(5,5,6,6,5,5);
break;
case Brick:
return new SimpleCubeTile(7);
break;
case TNT:
return new MultiFaceCubeTile(8,8,9,10,8,8);
break;
case CobbleStone:
return new SimpleCubeTile(16);
break;
default:
return NULL;
break;
}
}
TiledMap::TiledMap(int x, int y, int z, glm::vec3 wp, DataMap* m) {
width = x; length = z; height = y;
//init_cinstances(cinstance);
memset(cinstance, 0, sizeof(cinstance));
map = m;
mount_point = wp;
}
void TiledMap::bake_tiles() {
int count[16][6];
glm::mat4* temp[16][6];
for (int x = 0; x < 16; x++)
for (int y = 0; y < 6; y++)
temp[x][y] = (glm::mat4*) malloc(sizeof(glm::mat4) * 8192);
memset(count, 0, sizeof(count));
for (int x = mount_point.x; x < mount_point.x + width; x++) {
for (int z = mount_point.z; z < length + mount_point.z; z++) {
for (int y = mount_point.y; y < height + mount_point.y; y++) {
int id = map->tidQuery(x, y, z);
if (id > 0) {
id --;
glm::mat4 tr = glm::translate(glm::mat4(1.0), glm::vec3(x,y,z));
if (map->tidQuery(x, y, z - 1) == 0) {
temp[id][0][count[id][0]] = tr;
count[id][0] ++;
}
if (map->tidQuery(x, y, z + 1) == 0) {
temp[id][1][count[id][1]] = tr;
count[id][1] ++;
}
if (map->tidQuery(x, y + 1, z) == 0) {
temp[id][2][count[id][2]] = tr;
count[id][2] ++;
}
if (map->tidQuery(x, y - 1, z) == 0) {
temp[id][3][count[id][3]] = tr;
count[id][3] ++;
}
if (map->tidQuery(x - 1, y, z) == 0) {
temp[id][4][count[id][4]] = tr;
count[id][4] ++;
}
if (map->tidQuery(x + 1, y, z) == 0) {
temp[id][5][count[id][5]] = tr;
count[id][5] ++;
}
}
}
}
}
for (int id = 0; id < 16; id ++) {
bool has_block_valid = false;
for (int x = 0; x < 6; x++) if (count[id][x]) {
has_block_valid = true;
break;
}
if (has_block_valid) {
if (!cinstance[id]) cinstance[id] = get_instances(id + 1);
for (int x = 0; x < 6; x++) {
if (count[id][x] > 0) {
xefree(cinstance[id]->mat[x]);
cinstance[id]->mat[x] = new glm::mat4[count[id][x]];
memcpy(cinstance[id]->mat[x], temp[id][x], sizeof(glm::mat4) * count[id][x]);
}
}
} else if (cinstance[id]) {
VMDE_Dispose(cinstance[id]);
}
}
for (int x = 0; x < 16; x++)
for (int y = 0; y < 6; y++)
xefree(temp[x][y]);
for (int id = 0; id < 16; id++) {
if (cinstance[id]) cinstance[id]->update_instance(
count[id][0],count[id][1],count[id][2],
count[id][3],count[id][4],count[id][5]
);
}
}
void TiledMap::render() {
for (int i = 0; i < 16; i++)
if (cinstance[i]) cinstance[i]->render();
}
void TiledMap::dispose() {
for (int i = 0; i < 16; i++)
if (cinstance[i]) VMDE_Dispose(cinstance[i]);
}
}
<commit_msg>好好利用get_instance<commit_after>//=============================================================================
// ■ tiled_map.cpp
//-----------------------------------------------------------------------------
// Tile地图
//=============================================================================
#include "tiled_map.hpp"
namespace VM76 {
void TiledMap::init_cinstances (Tiles* cinstance[]) {
for (int i = 0; i < 16; i ++)
cinstance[i] = get_instances(i + 1);
}
Tiles* TiledMap::get_instances (int id) {
switch (id) {
case Grass:
return new MultiFaceCubeTile(49,49,0,2,49,49);
break;
case Stone:
return new SimpleCubeTile(1);
break;
case Dirt:
return new SimpleCubeTile(2);
break;
case Glass:
return new SimpleCubeTile(3);
break;
case WoodPlank:
return new SimpleCubeTile(4);
break;
case HalfBrick:
return new MultiFaceCubeTile(5,5,6,6,5,5);
break;
case Brick:
return new SimpleCubeTile(7);
break;
case TNT:
return new MultiFaceCubeTile(8,8,9,10,8,8);
break;
case CobbleStone:
return new SimpleCubeTile(16);
break;
default:
return new SimpleCubeTile(31);
break;
}
}
TiledMap::TiledMap(int x, int y, int z, glm::vec3 wp, DataMap* m) {
width = x; length = z; height = y;
//init_cinstances(cinstance);
memset(cinstance, 0, sizeof(cinstance));
map = m;
mount_point = wp;
}
void TiledMap::bake_tiles() {
int count[16][6];
glm::mat4* temp[16][6];
for (int x = 0; x < 16; x++)
for (int y = 0; y < 6; y++)
temp[x][y] = (glm::mat4*) malloc(sizeof(glm::mat4) * 8192);
memset(count, 0, sizeof(count));
for (int x = mount_point.x; x < mount_point.x + width; x++) {
for (int z = mount_point.z; z < length + mount_point.z; z++) {
for (int y = mount_point.y; y < height + mount_point.y; y++) {
int id = map->tidQuery(x, y, z);
if (id > 0) {
id --;
glm::mat4 tr = glm::translate(glm::mat4(1.0), glm::vec3(x,y,z));
if (map->tidQuery(x, y, z - 1) == 0) {
temp[id][0][count[id][0]] = tr;
count[id][0] ++;
}
if (map->tidQuery(x, y, z + 1) == 0) {
temp[id][1][count[id][1]] = tr;
count[id][1] ++;
}
if (map->tidQuery(x, y + 1, z) == 0) {
temp[id][2][count[id][2]] = tr;
count[id][2] ++;
}
if (map->tidQuery(x, y - 1, z) == 0) {
temp[id][3][count[id][3]] = tr;
count[id][3] ++;
}
if (map->tidQuery(x - 1, y, z) == 0) {
temp[id][4][count[id][4]] = tr;
count[id][4] ++;
}
if (map->tidQuery(x + 1, y, z) == 0) {
temp[id][5][count[id][5]] = tr;
count[id][5] ++;
}
}
}
}
}
for (int id = 0; id < 16; id ++) {
bool has_block_valid = false;
for (int x = 0; x < 6; x++) if (count[id][x]) {
has_block_valid = true;
break;
}
if (has_block_valid) {
if (!cinstance[id]) cinstance[id] = get_instances(id + 1);
for (int x = 0; x < 6; x++) {
if (count[id][x] > 0) {
xefree(cinstance[id]->mat[x]);
cinstance[id]->mat[x] = new glm::mat4[count[id][x]];
memcpy(cinstance[id]->mat[x], temp[id][x], sizeof(glm::mat4) * count[id][x]);
}
}
} else if (cinstance[id]) {
VMDE_Dispose(cinstance[id]);
}
}
for (int x = 0; x < 16; x++)
for (int y = 0; y < 6; y++)
xefree(temp[x][y]);
for (int id = 0; id < 16; id++) {
if (cinstance[id]) cinstance[id]->update_instance(
count[id][0],count[id][1],count[id][2],
count[id][3],count[id][4],count[id][5]
);
}
}
void TiledMap::render() {
for (int i = 0; i < 16; i++)
if (cinstance[i]) cinstance[i]->render();
}
void TiledMap::dispose() {
for (int i = 0; i < 16; i++)
if (cinstance[i]) VMDE_Dispose(cinstance[i]);
}
}
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "util/disk-info.h"
#ifdef __APPLE__
#include <sys/mount.h>
#else
#include <sys/vfs.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include "util/debug-util.h"
#include "common/names.h"
using boost::algorithm::is_any_of;
using boost::algorithm::split;
using boost::algorithm::token_compress_on;
using boost::algorithm::trim;
using boost::algorithm::trim_right_if;
namespace impala {
bool DiskInfo::initialized_;
vector<DiskInfo::Disk> DiskInfo::disks_;
map<dev_t, int> DiskInfo::device_id_to_disk_id_;
map<string, int> DiskInfo::disk_name_to_disk_id_;
// Parses /proc/partitions to get the number of disks. A bit of looking around
// seems to indicate this as the best way to do this.
// TODO: is there not something better than this?
void DiskInfo::GetDeviceNames() {
// Format of this file is:
// major, minor, #blocks, name
// We are only interesting in name which is formatted as device_name<partition #>
// The same device will show up multiple times for each partition (e.g. sda1, sda2).
ifstream partitions("/proc/partitions", ios::in);
while (partitions.good() && !partitions.eof()) {
string line;
getline(partitions, line);
trim(line);
vector<string> fields;
split(fields, line, is_any_of(" "), token_compress_on);
if (fields.size() != 4) continue;
string name = fields[3];
if (name == "name") continue;
// Remove the partition# from the name. e.g. sda2 --> sda
trim_right_if(name, is_any_of("0123456789"));
// Create a mapping of all device ids (one per partition) to the disk id.
int major_dev_id = atoi(fields[0].c_str());
int minor_dev_id = atoi(fields[1].c_str());
dev_t dev = makedev(major_dev_id, minor_dev_id);
DCHECK(device_id_to_disk_id_.find(dev) == device_id_to_disk_id_.end());
int disk_id = -1;
map<string, int>::iterator it = disk_name_to_disk_id_.find(name);
if (it == disk_name_to_disk_id_.end()) {
// First time seeing this disk
disk_id = disks_.size();
disks_.push_back(Disk(name, disk_id));
disk_name_to_disk_id_[name] = disk_id;
} else {
disk_id = it->second;
}
device_id_to_disk_id_[dev] = disk_id;
}
if (partitions.is_open()) partitions.close();
if (disks_.empty()) {
// If all else fails, return 1
LOG(WARNING) << "Could not determine number of disks on this machine.";
disks_.push_back(Disk("sda", 0));
return;
}
// Determine if the disk is rotational or not.
for (int i = 0; i < disks_.size(); ++i) {
// We can check if it is rotational by reading:
// /sys/block/<device>/queue/rotational
// If the file is missing or has unexpected data, default to rotational.
stringstream ss;
ss << "/sys/block/" << disks_[i].name << "/queue/rotational";
ifstream rotational(ss.str().c_str(), ios::in);
if (rotational.good()) {
string line;
getline(rotational, line);
if (line == "0") disks_[i].is_rotational = false;
}
if (rotational.is_open()) rotational.close();
}
}
void DiskInfo::Init() {
GetDeviceNames();
initialized_ = true;
}
int DiskInfo::disk_id(const char* path) {
struct stat s;
stat(path, &s);
map<dev_t, int>::iterator it = device_id_to_disk_id_.find(s.st_dev);
if (it == device_id_to_disk_id_.end()) return -1;
return it->second;
}
string DiskInfo::DebugString() {
DCHECK(initialized_);
stringstream stream;
stream << "Disk Info: " << endl;
stream << " Num disks " << num_disks() << ": " << endl;
for (int i = 0; i < disks_.size(); ++i) {
stream << " " << disks_[i].name
<< " (rotational=" << (disks_[i].is_rotational ? "true" : "false") << ")\n";
}
stream << endl;
return stream.str();
}
}
<commit_msg>sys/types.h no longer includes sys/sysmacros.h<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "util/disk-info.h"
#ifdef __APPLE__
#include <sys/mount.h>
#else
#include <sys/vfs.h>
#endif
#include <sys/types.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include <unistd.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include "util/debug-util.h"
#include "common/names.h"
using boost::algorithm::is_any_of;
using boost::algorithm::split;
using boost::algorithm::token_compress_on;
using boost::algorithm::trim;
using boost::algorithm::trim_right_if;
namespace impala {
bool DiskInfo::initialized_;
vector<DiskInfo::Disk> DiskInfo::disks_;
map<dev_t, int> DiskInfo::device_id_to_disk_id_;
map<string, int> DiskInfo::disk_name_to_disk_id_;
// Parses /proc/partitions to get the number of disks. A bit of looking around
// seems to indicate this as the best way to do this.
// TODO: is there not something better than this?
void DiskInfo::GetDeviceNames() {
// Format of this file is:
// major, minor, #blocks, name
// We are only interesting in name which is formatted as device_name<partition #>
// The same device will show up multiple times for each partition (e.g. sda1, sda2).
ifstream partitions("/proc/partitions", ios::in);
while (partitions.good() && !partitions.eof()) {
string line;
getline(partitions, line);
trim(line);
vector<string> fields;
split(fields, line, is_any_of(" "), token_compress_on);
if (fields.size() != 4) continue;
string name = fields[3];
if (name == "name") continue;
// Remove the partition# from the name. e.g. sda2 --> sda
trim_right_if(name, is_any_of("0123456789"));
// Create a mapping of all device ids (one per partition) to the disk id.
int major_dev_id = atoi(fields[0].c_str());
int minor_dev_id = atoi(fields[1].c_str());
dev_t dev = makedev(major_dev_id, minor_dev_id);
DCHECK(device_id_to_disk_id_.find(dev) == device_id_to_disk_id_.end());
int disk_id = -1;
map<string, int>::iterator it = disk_name_to_disk_id_.find(name);
if (it == disk_name_to_disk_id_.end()) {
// First time seeing this disk
disk_id = disks_.size();
disks_.push_back(Disk(name, disk_id));
disk_name_to_disk_id_[name] = disk_id;
} else {
disk_id = it->second;
}
device_id_to_disk_id_[dev] = disk_id;
}
if (partitions.is_open()) partitions.close();
if (disks_.empty()) {
// If all else fails, return 1
LOG(WARNING) << "Could not determine number of disks on this machine.";
disks_.push_back(Disk("sda", 0));
return;
}
// Determine if the disk is rotational or not.
for (int i = 0; i < disks_.size(); ++i) {
// We can check if it is rotational by reading:
// /sys/block/<device>/queue/rotational
// If the file is missing or has unexpected data, default to rotational.
stringstream ss;
ss << "/sys/block/" << disks_[i].name << "/queue/rotational";
ifstream rotational(ss.str().c_str(), ios::in);
if (rotational.good()) {
string line;
getline(rotational, line);
if (line == "0") disks_[i].is_rotational = false;
}
if (rotational.is_open()) rotational.close();
}
}
void DiskInfo::Init() {
GetDeviceNames();
initialized_ = true;
}
int DiskInfo::disk_id(const char* path) {
struct stat s;
stat(path, &s);
map<dev_t, int>::iterator it = device_id_to_disk_id_.find(s.st_dev);
if (it == device_id_to_disk_id_.end()) return -1;
return it->second;
}
string DiskInfo::DebugString() {
DCHECK(initialized_);
stringstream stream;
stream << "Disk Info: " << endl;
stream << " Num disks " << num_disks() << ": " << endl;
for (int i = 0; i < disks_.size(); ++i) {
stream << " " << disks_[i].name
<< " (rotational=" << (disks_[i].is_rotational ? "true" : "false") << ")\n";
}
stream << endl;
return stream.str();
}
}
<|endoftext|> |
<commit_before>// Tools.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Tools.h"
#include "Program.h"
#include "interface/Tool.h"
#include "interface/PropertyChoice.h"
#include "CTool.h"
#include "CNCConfig.h"
#include "tinyxml/tinyxml.h"
#include <wx/stdpaths.h>
bool CTools::CanAdd(HeeksObj* object)
{
return ((object != NULL) && (object->GetType() == ToolType));
}
HeeksObj *CTools::MakeACopy(void) const
{
return(new CTools(*this)); // Call the copy constructor.
}
CTools::CTools()
{
CNCConfig config;
config.Read(_T("title_format"), (int *) (&m_title_format), int(eGuageReplacesSize) );
}
CTools::CTools( const CTools & rhs ) : ObjList(rhs)
{
m_title_format = rhs.m_title_format;
}
CTools & CTools::operator= ( const CTools & rhs )
{
if (this != &rhs)
{
ObjList::operator=( rhs );
m_title_format = rhs.m_title_format;
}
return(*this);
}
const wxBitmap &CTools::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(theApp.GetResFolder() + _T("/icons/tools.png")));
return *icon;
}
/**
We need to copy the tools from the CTools object passed in into our own
list. We don't want to duplicate tools that are already in our local tool table.
If we import a tool, we need to make sure the tool number is unique within the
whole tool table. If we need to renumber a tool during this import, we need to
also update any associated Operations objects that refer to this tool number
so that they now point to the new tool number.
*/
void CTools::CopyFrom(const HeeksObj* object)
{
/*
if (object->GetType() == GetType())
{
for (HeeksObj *tool = object->GetFirstChild(); tool != NULL; tool = object->GetNextChild())
{
}
}
*/
}
void CTools::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = heeksCAD->NewXMLElement( "Tools" );
heeksCAD->LinkXMLEndChild( root, element );
WriteBaseXML(element);
}
//static
HeeksObj* CTools::ReadFromXMLElement(TiXmlElement* pElem)
{
CTools* new_object = new CTools;
new_object->ReadBaseXML(pElem);
return new_object;
}
class ExportTools: public Tool{
bool m_for_default;
// Tool's virtual functions
const wxChar* GetTitle(){return m_for_default ? _("Save As Default"):_("Export");}
void Run()
{
#if wxCHECK_VERSION(3, 0, 0)
wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
wxStandardPaths standard_paths;
#endif
if (previous_path.Length() == 0) previous_path = _T("default.tooltable");
if(m_for_default)
{
previous_path = theApp.GetResourceFilename(wxT("default.tooltable"), true);
}
else
{
// Prompt the user to select a file to import.
wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to export to"),
standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
+ _T("*.tool;*.TOOL;*.Tool;")
+ _T("*.tools;*.TOOLS;*.Tools;")
+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
fd.SetFilterIndex(1);
if (fd.ShowModal() == wxID_CANCEL) return;
previous_path = fd.GetPath().c_str();
}
std::list<HeeksObj *> tools;
for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
tool != NULL;
tool = theApp.m_program->Tools()->GetNextChild() )
{
tools.push_back( tool );
} // End for
wprintf(wxT("Exporting tools as ") + previous_path + wxT("\n"));
heeksCAD->SaveXMLFile( tools, previous_path.c_str(), false );
}
wxString BitmapPath(){ return _T("export");}
wxString previous_path;
public:
ExportTools(bool for_default = false)
{
m_for_default = for_default;
}
};
static ExportTools export_tools;
static ExportTools save_default_tools(true);
void ImportToolsFile( const wxChar *file_path )
{
// Delete the speed references that we've already got. Otherwise we end
// up with duplicates. Do this in two passes. Otherwise we end up
// traversing the same list that we're modifying.
std::list<HeeksObj *> tools;
for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
tool != NULL;
tool = theApp.m_program->Tools()->GetNextChild() )
{
tools.push_back( tool );
} // End for
for (std::list<HeeksObj *>::iterator l_itObject = tools.begin(); l_itObject != tools.end(); l_itObject++)
{
heeksCAD->Remove( *l_itObject );
} // End for
// And read the default speed references.
// heeksCAD->OpenXMLFile( _T("default.speeds"), true, theApp.m_program->m_tools );
heeksCAD->OpenXMLFile( file_path, theApp.m_program->Tools() );
}
class ImportTools: public Tool{
bool m_for_default;
// Tool's virtual functions
const wxChar* GetTitle(){return m_for_default ? _("Restore Default Tools"):_("Import");}
void Run()
{
#if wxCHECK_VERSION(3, 0, 0)
wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
wxStandardPaths standard_paths;
#endif
if (previous_path.Length() == 0) previous_path = _T("default.tooltable");
if(m_for_default)
{
previous_path = theApp.GetResourceFilename(wxT("default.tooltable"));
}
else
{
// Prompt the user to select a file to import.
wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to import"),
standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
+ _T("*.tool;*.TOOL;*.Tool;")
+ _T("*.tools;*.TOOLS;*.Tools;")
+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
wxFD_OPEN | wxFD_FILE_MUST_EXIST );
fd.SetFilterIndex(1);
if (fd.ShowModal() == wxID_CANCEL) return;
previous_path = fd.GetPath().c_str();
}
ImportToolsFile( previous_path.c_str() );
}
wxString BitmapPath(){ return _T("import");}
wxString previous_path;
public:
ImportTools(bool for_default = false)
{
m_for_default = for_default;
}
};
static ImportTools import_tools;
static ImportTools import_default_tools(true);
void CTools::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
t_list->push_back(&save_default_tools);
t_list->push_back(&import_default_tools);
t_list->push_back(&import_tools);
t_list->push_back(&export_tools);
CHeeksCNCApp::GetNewToolTools(t_list);
ObjList::GetTools(t_list, p);
}
static void on_set_title_format(int value, HeeksObj* object, bool from_undo_redo)
{
((CTools *)object)->m_title_format = CTools::TitleFormat_t(value);
CNCConfig config;
config.Write(_T("title_format"), (int)(((CTools *)object)->m_title_format));
}
void CTools::GetProperties(std::list<Property *> *list)
{
{
std::list< wxString > choices;
choices.push_back( _("Guage number replaces size") );
choices.push_back( _("Include guage number and size") );
list->push_back ( new PropertyChoice ( _("Title Format"), choices, m_title_format, this, on_set_title_format ) );
}
HeeksObj::GetProperties(list);
}
<commit_msg>UI: explicit terms for tool table entries<commit_after>// Tools.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Tools.h"
#include "Program.h"
#include "interface/Tool.h"
#include "interface/PropertyChoice.h"
#include "CTool.h"
#include "CNCConfig.h"
#include "tinyxml/tinyxml.h"
#include <wx/stdpaths.h>
bool CTools::CanAdd(HeeksObj* object)
{
return ((object != NULL) && (object->GetType() == ToolType));
}
HeeksObj *CTools::MakeACopy(void) const
{
return(new CTools(*this)); // Call the copy constructor.
}
CTools::CTools()
{
CNCConfig config;
config.Read(_T("title_format"), (int *) (&m_title_format), int(eGuageReplacesSize) );
}
CTools::CTools( const CTools & rhs ) : ObjList(rhs)
{
m_title_format = rhs.m_title_format;
}
CTools & CTools::operator= ( const CTools & rhs )
{
if (this != &rhs)
{
ObjList::operator=( rhs );
m_title_format = rhs.m_title_format;
}
return(*this);
}
const wxBitmap &CTools::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(theApp.GetResFolder() + _T("/icons/tools.png")));
return *icon;
}
/**
We need to copy the tools from the CTools object passed in into our own
list. We don't want to duplicate tools that are already in our local tool table.
If we import a tool, we need to make sure the tool number is unique within the
whole tool table. If we need to renumber a tool during this import, we need to
also update any associated Operations objects that refer to this tool number
so that they now point to the new tool number.
*/
void CTools::CopyFrom(const HeeksObj* object)
{
/*
if (object->GetType() == GetType())
{
for (HeeksObj *tool = object->GetFirstChild(); tool != NULL; tool = object->GetNextChild())
{
}
}
*/
}
void CTools::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = heeksCAD->NewXMLElement( "Tools" );
heeksCAD->LinkXMLEndChild( root, element );
WriteBaseXML(element);
}
//static
HeeksObj* CTools::ReadFromXMLElement(TiXmlElement* pElem)
{
CTools* new_object = new CTools;
new_object->ReadBaseXML(pElem);
return new_object;
}
class ExportTools: public Tool{
bool m_for_default;
// Tool's virtual functions
const wxChar* GetTitle(){return m_for_default ? _("Save As Default"):_("Export Tool Table...");}
void Run()
{
#if wxCHECK_VERSION(3, 0, 0)
wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
wxStandardPaths standard_paths;
#endif
if (previous_path.Length() == 0) previous_path = _T("default.tooltable");
if(m_for_default)
{
previous_path = theApp.GetResourceFilename(wxT("default.tooltable"), true);
}
else
{
// Prompt the user to select a file to import.
wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to export to"),
standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
+ _T("*.tool;*.TOOL;*.Tool;")
+ _T("*.tools;*.TOOLS;*.Tools;")
+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
fd.SetFilterIndex(1);
if (fd.ShowModal() == wxID_CANCEL) return;
previous_path = fd.GetPath().c_str();
}
std::list<HeeksObj *> tools;
for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
tool != NULL;
tool = theApp.m_program->Tools()->GetNextChild() )
{
tools.push_back( tool );
} // End for
wprintf(wxT("Exporting tools as ") + previous_path + wxT("\n"));
heeksCAD->SaveXMLFile( tools, previous_path.c_str(), false );
}
wxString BitmapPath(){ return _T("export");}
wxString previous_path;
public:
ExportTools(bool for_default = false)
{
m_for_default = for_default;
}
};
static ExportTools export_tools;
static ExportTools save_default_tools(true);
void ImportToolsFile( const wxChar *file_path )
{
// Delete the speed references that we've already got. Otherwise we end
// up with duplicates. Do this in two passes. Otherwise we end up
// traversing the same list that we're modifying.
std::list<HeeksObj *> tools;
for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
tool != NULL;
tool = theApp.m_program->Tools()->GetNextChild() )
{
tools.push_back( tool );
} // End for
for (std::list<HeeksObj *>::iterator l_itObject = tools.begin(); l_itObject != tools.end(); l_itObject++)
{
heeksCAD->Remove( *l_itObject );
} // End for
// And read the default speed references.
// heeksCAD->OpenXMLFile( _T("default.speeds"), true, theApp.m_program->m_tools );
heeksCAD->OpenXMLFile( file_path, theApp.m_program->Tools() );
}
class ImportTools: public Tool{
bool m_for_default;
// Tool's virtual functions
const wxChar* GetTitle(){return m_for_default ? _("Restore Default Tools"):_("Import Tool Table...");}
void Run()
{
#if wxCHECK_VERSION(3, 0, 0)
wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
wxStandardPaths standard_paths;
#endif
if (previous_path.Length() == 0) previous_path = _T("default.tooltable");
if(m_for_default)
{
previous_path = theApp.GetResourceFilename(wxT("default.tooltable"));
}
else
{
// Prompt the user to select a file to import.
wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to import"),
standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
+ _T("*.tool;*.TOOL;*.Tool;")
+ _T("*.tools;*.TOOLS;*.Tools;")
+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
wxFD_OPEN | wxFD_FILE_MUST_EXIST );
fd.SetFilterIndex(1);
if (fd.ShowModal() == wxID_CANCEL) return;
previous_path = fd.GetPath().c_str();
}
ImportToolsFile( previous_path.c_str() );
}
wxString BitmapPath(){ return _T("import");}
wxString previous_path;
public:
ImportTools(bool for_default = false)
{
m_for_default = for_default;
}
};
static ImportTools import_tools;
static ImportTools import_default_tools(true);
void CTools::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
t_list->push_back(&save_default_tools);
t_list->push_back(&import_default_tools);
t_list->push_back(&import_tools);
t_list->push_back(&export_tools);
CHeeksCNCApp::GetNewToolTools(t_list);
ObjList::GetTools(t_list, p);
}
static void on_set_title_format(int value, HeeksObj* object, bool from_undo_redo)
{
((CTools *)object)->m_title_format = CTools::TitleFormat_t(value);
CNCConfig config;
config.Write(_T("title_format"), (int)(((CTools *)object)->m_title_format));
}
void CTools::GetProperties(std::list<Property *> *list)
{
{
std::list< wxString > choices;
choices.push_back( _("Guage number replaces size") );
choices.push_back( _("Include guage number and size") );
list->push_back ( new PropertyChoice ( _("Title Format"), choices, m_title_format, this, on_set_title_format ) );
}
HeeksObj::GetProperties(list);
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE libraries
Copyright (C) 2001 Christoph Cullmann <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// $Id$
#include "katefiledialog.h"
#include "katefiledialog.moc"
#include <kcombobox.h>
#include <ktoolbar.h>
#include <kglobal.h>
#include <kcharsets.h>
#include <qstringlist.h>
#include <qtextcodec.h>
KateFileDialog::KateFileDialog (const QString& startDir,
const QString& encoding,
QWidget *parent,
const QString& caption,
KFileDialog::OperationMode opMode )
: KFileDialog (startDir, QString::null, parent, "", true)
{
QString sEncoding (encoding);
setCaption (caption);
toolBar()->insertCombo(QStringList(), 33333, false, 0L, 0L, 0L, true);
QStringList filter;
filter << "all/allfiles";
filter << "text/plain";
if (opMode == Opening) {
setMode(KFile::Files);
setMimeFilter (filter, "all/allfiles");
}
else {
setMode(KFile::File);
setOperationMode( Saving );
setMimeFilter (filter, "text/plain");
}
m_encoding = toolBar()->getCombo(33333);
m_encoding->clear ();
QStringList encodings (KGlobal::charsets()->availableEncodingNames());
int insert = 0;
for (uint i=0; i < encodings.count(); i++)
{
bool found = false;
QTextCodec *codecForEnc = KGlobal::charsets()->codecForName(encodings[i], found);
if (found)
{
m_encoding->insertItem (encodings[i]);
if ( codecForEnc->name() == encoding )
{
m_encoding->setCurrentItem(insert);
}
insert++;
}
}
}
KateFileDialog::~KateFileDialog ()
{
}
KateFileDialogData KateFileDialog::exec()
{
int n = KDialogBase::exec();
KateFileDialogData data = KateFileDialogData ();
if (n)
{
data.encoding = m_encoding->currentText();
data.url = selectedURL ();
data.urls = selectedURLs ();
}
return data;
}
void KateFileDialog::slotApply()
{
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>all files<commit_after>/* This file is part of the KDE libraries
Copyright (C) 2001 Christoph Cullmann <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// $Id$
#include "katefiledialog.h"
#include "katefiledialog.moc"
#include <kcombobox.h>
#include <ktoolbar.h>
#include <kglobal.h>
#include <kcharsets.h>
#include <qstringlist.h>
#include <qtextcodec.h>
KateFileDialog::KateFileDialog (const QString& startDir,
const QString& encoding,
QWidget *parent,
const QString& caption,
KFileDialog::OperationMode opMode )
: KFileDialog (startDir, QString::null, parent, "", true)
{
QString sEncoding (encoding);
setCaption (caption);
toolBar()->insertCombo(QStringList(), 33333, false, 0L, 0L, 0L, true);
QStringList filter;
filter << "all/allfiles";
filter << "text/plain";
if (opMode == Opening) {
setMode(KFile::Files);
setMimeFilter (filter, "all/allfiles");
}
else {
setMode(KFile::File);
setOperationMode( Saving );
setMimeFilter (filter, "all/allfiles");
}
m_encoding = toolBar()->getCombo(33333);
m_encoding->clear ();
QStringList encodings (KGlobal::charsets()->availableEncodingNames());
int insert = 0;
for (uint i=0; i < encodings.count(); i++)
{
bool found = false;
QTextCodec *codecForEnc = KGlobal::charsets()->codecForName(encodings[i], found);
if (found)
{
m_encoding->insertItem (encodings[i]);
if ( codecForEnc->name() == encoding )
{
m_encoding->setCurrentItem(insert);
}
insert++;
}
}
}
KateFileDialog::~KateFileDialog ()
{
}
KateFileDialogData KateFileDialog::exec()
{
int n = KDialogBase::exec();
KateFileDialogData data = KateFileDialogData ();
if (n)
{
data.encoding = m_encoding->currentText();
data.url = selectedURL ();
data.urls = selectedURLs ();
}
return data;
}
void KateFileDialog::slotApply()
{
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>/*
Copyright (C) 2010 Collabora Multimedia.
@author Mauricio Piacentini <[email protected]>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query.h"
#include "element.h"
#include "../QGlib/error.h"
#include "../QGlib/string_p.h"
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <gst/gst.h>
namespace QGst {
QString Query::typeName() const
{
return QString::fromUtf8(GST_QUERY_TYPE_NAME(object<GstQuery>()));
}
QueryType Query::type() const
{
return static_cast<QueryType>(GST_QUERY_TYPE(object<GstQuery>()));
}
SharedStructure Query::structure()
{
return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}
const SharedStructure Query::structure() const
{
return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}
void Query::ref()
{
//We are not supposed to ref() query objects created with gst_query_new_* methods
//Workaround while the global hash is not implemented for refcounting
//gst_query_ref(object<GstQuery>());
}
void Query::unref()
{
//We have to unref() the object only once
//Workaround while the global hash is not implemented for refcounting, leak for now
//gst_query_unref(object<GstQuery>());
}
//********************************************************
PositionQueryPtr PositionQuery::create(Format format)
{
return PositionQueryPtr::wrap(gst_query_new_position(static_cast<GstFormat>(format)), false);
}
Format PositionQuery::format() const
{
GstFormat f;
gst_query_parse_position(object<GstQuery>(), &f, NULL);
return static_cast<Format>(f);
}
qint64 PositionQuery::position() const
{
gint64 p;
gst_query_parse_position(object<GstQuery>(), NULL, &p);
return p;
}
void PositionQuery::setValues(Format format, qint64 position)
{
gst_query_set_position(object<GstQuery>(), static_cast<GstFormat>(format), position);
}
//********************************************************
DurationQueryPtr DurationQuery::create(Format format)
{
return DurationQueryPtr::wrap(gst_query_new_duration(static_cast<GstFormat>(format)), false);
}
Format DurationQuery::format() const
{
GstFormat f;
gst_query_parse_duration(object<GstQuery>(), &f, NULL);
return static_cast<Format>(f);
}
qint64 DurationQuery::duration() const
{
gint64 d;
gst_query_parse_duration(object<GstQuery>(), NULL, &d);
return d;
}
void DurationQuery::setValues(Format format, qint64 duration)
{
gst_query_set_duration(object<GstQuery>(), static_cast<GstFormat>(format), duration);
}
//********************************************************
LatencyQueryPtr LatencyQuery::create()
{
return LatencyQueryPtr::wrap(gst_query_new_latency(), false);
}
bool LatencyQuery::hasLive() const
{
gboolean l;
gst_query_parse_latency(object<GstQuery>(), &l, NULL, NULL);
return l;
}
ClockTime LatencyQuery::minimumLatency() const
{
GstClockTime c;
gst_query_parse_latency(object<GstQuery>(), NULL, &c, NULL);
return c;
}
ClockTime LatencyQuery::maximumLatency() const
{
GstClockTime c;
gst_query_parse_latency(object<GstQuery>(), NULL, NULL, &c);
return c;
}
void LatencyQuery::setValues(bool live, ClockTime minimumLatency, ClockTime maximumLatency)
{
gst_query_set_latency(object<GstQuery>(), live, minimumLatency, maximumLatency);
}
//********************************************************
SeekingQueryPtr SeekingQuery::create(Format format)
{
return SeekingQueryPtr::wrap(gst_query_new_seeking(static_cast<GstFormat>(format)), false);
}
Format SeekingQuery::format() const
{
GstFormat f;
gst_query_parse_seeking(object<GstQuery>(), &f, NULL, NULL, NULL);
return static_cast<Format>(f);
}
bool SeekingQuery::seekable() const
{
gboolean s;
gst_query_parse_seeking(object<GstQuery>(), NULL, &s, NULL, NULL);
return s;
}
qint64 SeekingQuery::segmentStart() const
{
gint64 s;
gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, &s, NULL);
return s;
}
qint64 SeekingQuery::segmentEnd() const
{
gint64 s;
gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, NULL, &s);
return s;
}
void SeekingQuery::setValues(Format format, bool seekable, qint64 segmentStart, qint64 segmentEnd)
{
gst_query_set_seeking(object<GstQuery>(), static_cast<GstFormat>(format), seekable,
segmentStart, segmentEnd);
}
//********************************************************
SegmentQueryPtr SegmentQuery::create(Format format)
{
return SegmentQueryPtr::wrap(gst_query_new_segment(static_cast<GstFormat>(format)), false);
}
double SegmentQuery::rate() const
{
gdouble r;
gst_query_parse_segment(object<GstQuery>(), &r, NULL, NULL, NULL);
return r;
}
Format SegmentQuery::format() const
{
GstFormat f;
gst_query_parse_segment(object<GstQuery>(), NULL, &f, NULL, NULL);
return static_cast<Format>(f);
}
qint64 SegmentQuery::startValue() const
{
gint64 s;
gst_query_parse_segment(object<GstQuery>(), NULL, NULL, &s, NULL);
return s;
}
qint64 SegmentQuery::stopValue() const
{
gint64 s;
gst_query_parse_segment(object<GstQuery>(), NULL, NULL, NULL, &s);
return s;
}
void SegmentQuery::setValues(Format format, double rate, qint64 startValue, qint64 stopValue)
{
gst_query_set_segment(object<GstQuery>(), rate, static_cast<GstFormat>(format), startValue,
stopValue);
}
//********************************************************
ConvertQueryPtr ConvertQuery::create(Format sourceFormat, qint64 value, Format destinationFormat)
{
return ConvertQueryPtr::wrap(gst_query_new_convert(static_cast<GstFormat>(sourceFormat), value,
static_cast<GstFormat>(destinationFormat)), false);
}
Format ConvertQuery::sourceFormat() const
{
GstFormat f;
gst_query_parse_convert(object<GstQuery>(), &f, NULL, NULL, NULL);
return static_cast<Format>(f);
}
qint64 ConvertQuery::sourceValue() const
{
gint64 v;
gst_query_parse_convert(object<GstQuery>(), NULL, &v, NULL, NULL);
return v;
}
Format ConvertQuery::destinationFormat() const
{
GstFormat f;
gst_query_parse_convert(object<GstQuery>(), NULL, NULL, &f, NULL);
return static_cast<Format>(f);
}
qint64 ConvertQuery::destinationValue() const
{
gint64 v;
gst_query_parse_convert(object<GstQuery>(), NULL, NULL, NULL, &v);
return v;
}
void ConvertQuery::setValues(Format sourceFormat, qint64 sourceValue, Format destinationFormat,
qint64 destinationValue)
{
gst_query_set_convert(object<GstQuery>(), static_cast<GstFormat>(sourceFormat), sourceValue,
static_cast<GstFormat>(destinationFormat), destinationValue);
}
//********************************************************
FormatsQueryPtr FormatsQuery::create()
{
return FormatsQueryPtr::wrap(gst_query_new_formats(), false);
}
QList<Format> FormatsQuery::formats() const
{
guint cnt;
QList<Format> formats;
gst_query_parse_formats_length(object<GstQuery>(), &cnt);
GstFormat f;
for (uint i=0; i<cnt; i++) {
gst_query_parse_formats_nth(object<GstQuery>(), i, &f);
formats << static_cast<Format>(f);
}
return formats;
}
void FormatsQuery::setValue(const QList<Format> & formats)
{
int cnt = formats.count();
if (cnt==0) return;
GstFormat f[cnt];
for (int i=0; i<cnt; i++) {
f[i] = static_cast<GstFormat>(formats.at(i));
}
gst_query_set_formatsv(object<GstQuery>(), cnt, f);
}
//********************************************************
BufferingQueryPtr BufferingQuery::create(Format format)
{
return BufferingQueryPtr::wrap(gst_query_new_buffering(static_cast<GstFormat>(format)), false);
}
bool BufferingQuery::isBusy() const
{
gboolean b;
gst_query_parse_buffering_percent(object<GstQuery>(), &b, NULL);
return b;
}
int BufferingQuery::percent() const
{
gint p;
gst_query_parse_buffering_percent(object<GstQuery>(), NULL, &p);
return p;
}
void BufferingQuery::setValues(bool busy, int percent)
{
gst_query_set_buffering_percent(object<GstQuery>(), busy, percent);
}
BufferingMode BufferingQuery::mode() const
{
GstBufferingMode m;
gst_query_parse_buffering_stats(object<GstQuery>(), &m, NULL, NULL, NULL);
return static_cast<BufferingMode>(m);
}
int BufferingQuery::averageIn() const
{
gint a;
gst_query_parse_buffering_stats(object<GstQuery>(), NULL, &a, NULL, NULL);
return a;
}
int BufferingQuery::averageOut() const
{
gint a;
gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, &a, NULL);
return a;
}
qint64 BufferingQuery::bufferingLeft() const
{
gint64 l;
gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, NULL, &l);
return l;
}
;
void BufferingQuery::setValues(BufferingMode mode, int averageIn, int averageOut,
qint64 bufferingLeft)
{
gst_query_set_buffering_stats(object<GstQuery>(), static_cast<GstBufferingMode>(mode),
averageIn, averageOut, bufferingLeft);
}
Format BufferingQuery::format() const
{
GstFormat f;
gst_query_parse_buffering_range(object<GstQuery>(), &f, NULL, NULL, NULL);
return static_cast<Format>(f);
}
qint64 BufferingQuery::rangeStart() const
{
gint64 r;
gst_query_parse_buffering_range(object<GstQuery>(), NULL, &r, NULL, NULL);
return r;
}
qint64 BufferingQuery::rangeStop() const
{
gint64 r;
gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, &r, NULL);
return r;
}
qint64 BufferingQuery::estimatedTotal() const
{
gint64 r;
gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, NULL, &r);
return r;
}
void BufferingQuery::setValues(Format rangeFormat, qint64 rangeStart, qint64 rangeStop,
qint64 estimatedTotal)
{
gst_query_set_buffering_range(object<GstQuery>(), static_cast<GstFormat>(rangeFormat),
rangeStart, rangeStop, estimatedTotal);
}
//********************************************************
UriQueryPtr UriQuery::create()
{
return UriQueryPtr::wrap(gst_query_new_uri(), false);
}
QUrl UriQuery::uri() const
{
gchar *uri;
gst_query_parse_uri(object<GstQuery>(), &uri);
return QUrl::fromPercentEncoding(uri);
}
void UriQuery::setValue(const QUrl & uri)
{
gst_query_set_uri(object<GstQuery>(), uri.toEncoded());
}
//********************************************************
} //namespace QGst
QGLIB_REGISTER_VALUEIMPL_IMPLEMENTATION(
QGst::QueryPtr,
QGst::QueryPtr::wrap(GST_QUERY(gst_value_get_mini_object(value))),
gst_value_set_mini_object(value, GST_MINI_OBJECT(static_cast<GstQuery*>(data)))
)
QDebug operator<<(QDebug debug, QGst::QueryType type)
{
debug.nospace() << gst_query_type_get_name(static_cast<GstQueryType>(type));
return debug.space();
}
QDebug operator<<(QDebug debug, const QGst::QueryPtr & query)
{
debug.nospace() << "QGst::Query(Type: " << query->type() << ")";
return debug.space();
}
<commit_msg>Fix QGst::Query compilation with msvc.<commit_after>/*
Copyright (C) 2010 Collabora Multimedia.
@author Mauricio Piacentini <[email protected]>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query.h"
#include "element.h"
#include "../QGlib/error.h"
#include "../QGlib/string_p.h"
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <gst/gst.h>
namespace QGst {
QString Query::typeName() const
{
return QString::fromUtf8(GST_QUERY_TYPE_NAME(object<GstQuery>()));
}
QueryType Query::type() const
{
return static_cast<QueryType>(GST_QUERY_TYPE(object<GstQuery>()));
}
SharedStructure Query::structure()
{
return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}
const SharedStructure Query::structure() const
{
return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}
void Query::ref()
{
//We are not supposed to ref() query objects created with gst_query_new_* methods
//Workaround while the global hash is not implemented for refcounting
//gst_query_ref(object<GstQuery>());
}
void Query::unref()
{
//We have to unref() the object only once
//Workaround while the global hash is not implemented for refcounting, leak for now
//gst_query_unref(object<GstQuery>());
}
//********************************************************
PositionQueryPtr PositionQuery::create(Format format)
{
return PositionQueryPtr::wrap(gst_query_new_position(static_cast<GstFormat>(format)), false);
}
Format PositionQuery::format() const
{
GstFormat f;
gst_query_parse_position(object<GstQuery>(), &f, NULL);
return static_cast<Format>(f);
}
qint64 PositionQuery::position() const
{
gint64 p;
gst_query_parse_position(object<GstQuery>(), NULL, &p);
return p;
}
void PositionQuery::setValues(Format format, qint64 position)
{
gst_query_set_position(object<GstQuery>(), static_cast<GstFormat>(format), position);
}
//********************************************************
DurationQueryPtr DurationQuery::create(Format format)
{
return DurationQueryPtr::wrap(gst_query_new_duration(static_cast<GstFormat>(format)), false);
}
Format DurationQuery::format() const
{
GstFormat f;
gst_query_parse_duration(object<GstQuery>(), &f, NULL);
return static_cast<Format>(f);
}
qint64 DurationQuery::duration() const
{
gint64 d;
gst_query_parse_duration(object<GstQuery>(), NULL, &d);
return d;
}
void DurationQuery::setValues(Format format, qint64 duration)
{
gst_query_set_duration(object<GstQuery>(), static_cast<GstFormat>(format), duration);
}
//********************************************************
LatencyQueryPtr LatencyQuery::create()
{
return LatencyQueryPtr::wrap(gst_query_new_latency(), false);
}
bool LatencyQuery::hasLive() const
{
gboolean l;
gst_query_parse_latency(object<GstQuery>(), &l, NULL, NULL);
return l;
}
ClockTime LatencyQuery::minimumLatency() const
{
GstClockTime c;
gst_query_parse_latency(object<GstQuery>(), NULL, &c, NULL);
return c;
}
ClockTime LatencyQuery::maximumLatency() const
{
GstClockTime c;
gst_query_parse_latency(object<GstQuery>(), NULL, NULL, &c);
return c;
}
void LatencyQuery::setValues(bool live, ClockTime minimumLatency, ClockTime maximumLatency)
{
gst_query_set_latency(object<GstQuery>(), live, minimumLatency, maximumLatency);
}
//********************************************************
SeekingQueryPtr SeekingQuery::create(Format format)
{
return SeekingQueryPtr::wrap(gst_query_new_seeking(static_cast<GstFormat>(format)), false);
}
Format SeekingQuery::format() const
{
GstFormat f;
gst_query_parse_seeking(object<GstQuery>(), &f, NULL, NULL, NULL);
return static_cast<Format>(f);
}
bool SeekingQuery::seekable() const
{
gboolean s;
gst_query_parse_seeking(object<GstQuery>(), NULL, &s, NULL, NULL);
return s;
}
qint64 SeekingQuery::segmentStart() const
{
gint64 s;
gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, &s, NULL);
return s;
}
qint64 SeekingQuery::segmentEnd() const
{
gint64 s;
gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, NULL, &s);
return s;
}
void SeekingQuery::setValues(Format format, bool seekable, qint64 segmentStart, qint64 segmentEnd)
{
gst_query_set_seeking(object<GstQuery>(), static_cast<GstFormat>(format), seekable,
segmentStart, segmentEnd);
}
//********************************************************
SegmentQueryPtr SegmentQuery::create(Format format)
{
return SegmentQueryPtr::wrap(gst_query_new_segment(static_cast<GstFormat>(format)), false);
}
double SegmentQuery::rate() const
{
gdouble r;
gst_query_parse_segment(object<GstQuery>(), &r, NULL, NULL, NULL);
return r;
}
Format SegmentQuery::format() const
{
GstFormat f;
gst_query_parse_segment(object<GstQuery>(), NULL, &f, NULL, NULL);
return static_cast<Format>(f);
}
qint64 SegmentQuery::startValue() const
{
gint64 s;
gst_query_parse_segment(object<GstQuery>(), NULL, NULL, &s, NULL);
return s;
}
qint64 SegmentQuery::stopValue() const
{
gint64 s;
gst_query_parse_segment(object<GstQuery>(), NULL, NULL, NULL, &s);
return s;
}
void SegmentQuery::setValues(Format format, double rate, qint64 startValue, qint64 stopValue)
{
gst_query_set_segment(object<GstQuery>(), rate, static_cast<GstFormat>(format), startValue,
stopValue);
}
//********************************************************
ConvertQueryPtr ConvertQuery::create(Format sourceFormat, qint64 value, Format destinationFormat)
{
return ConvertQueryPtr::wrap(gst_query_new_convert(static_cast<GstFormat>(sourceFormat), value,
static_cast<GstFormat>(destinationFormat)), false);
}
Format ConvertQuery::sourceFormat() const
{
GstFormat f;
gst_query_parse_convert(object<GstQuery>(), &f, NULL, NULL, NULL);
return static_cast<Format>(f);
}
qint64 ConvertQuery::sourceValue() const
{
gint64 v;
gst_query_parse_convert(object<GstQuery>(), NULL, &v, NULL, NULL);
return v;
}
Format ConvertQuery::destinationFormat() const
{
GstFormat f;
gst_query_parse_convert(object<GstQuery>(), NULL, NULL, &f, NULL);
return static_cast<Format>(f);
}
qint64 ConvertQuery::destinationValue() const
{
gint64 v;
gst_query_parse_convert(object<GstQuery>(), NULL, NULL, NULL, &v);
return v;
}
void ConvertQuery::setValues(Format sourceFormat, qint64 sourceValue, Format destinationFormat,
qint64 destinationValue)
{
gst_query_set_convert(object<GstQuery>(), static_cast<GstFormat>(sourceFormat), sourceValue,
static_cast<GstFormat>(destinationFormat), destinationValue);
}
//********************************************************
FormatsQueryPtr FormatsQuery::create()
{
return FormatsQueryPtr::wrap(gst_query_new_formats(), false);
}
QList<Format> FormatsQuery::formats() const
{
guint cnt;
QList<Format> formats;
gst_query_parse_formats_length(object<GstQuery>(), &cnt);
GstFormat f;
for (uint i=0; i<cnt; i++) {
gst_query_parse_formats_nth(object<GstQuery>(), i, &f);
formats << static_cast<Format>(f);
}
return formats;
}
void FormatsQuery::setValue(const QList<Format> & formats)
{
int cnt = formats.count();
if (cnt==0) return;
GstFormat *f = new GstFormat[cnt];
for (int i=0; i<cnt; i++) {
f[i] = static_cast<GstFormat>(formats.at(i));
}
gst_query_set_formatsv(object<GstQuery>(), cnt, f);
delete [] f;
}
//********************************************************
BufferingQueryPtr BufferingQuery::create(Format format)
{
return BufferingQueryPtr::wrap(gst_query_new_buffering(static_cast<GstFormat>(format)), false);
}
bool BufferingQuery::isBusy() const
{
gboolean b;
gst_query_parse_buffering_percent(object<GstQuery>(), &b, NULL);
return b;
}
int BufferingQuery::percent() const
{
gint p;
gst_query_parse_buffering_percent(object<GstQuery>(), NULL, &p);
return p;
}
void BufferingQuery::setValues(bool busy, int percent)
{
gst_query_set_buffering_percent(object<GstQuery>(), busy, percent);
}
BufferingMode BufferingQuery::mode() const
{
GstBufferingMode m;
gst_query_parse_buffering_stats(object<GstQuery>(), &m, NULL, NULL, NULL);
return static_cast<BufferingMode>(m);
}
int BufferingQuery::averageIn() const
{
gint a;
gst_query_parse_buffering_stats(object<GstQuery>(), NULL, &a, NULL, NULL);
return a;
}
int BufferingQuery::averageOut() const
{
gint a;
gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, &a, NULL);
return a;
}
qint64 BufferingQuery::bufferingLeft() const
{
gint64 l;
gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, NULL, &l);
return l;
}
;
void BufferingQuery::setValues(BufferingMode mode, int averageIn, int averageOut,
qint64 bufferingLeft)
{
gst_query_set_buffering_stats(object<GstQuery>(), static_cast<GstBufferingMode>(mode),
averageIn, averageOut, bufferingLeft);
}
Format BufferingQuery::format() const
{
GstFormat f;
gst_query_parse_buffering_range(object<GstQuery>(), &f, NULL, NULL, NULL);
return static_cast<Format>(f);
}
qint64 BufferingQuery::rangeStart() const
{
gint64 r;
gst_query_parse_buffering_range(object<GstQuery>(), NULL, &r, NULL, NULL);
return r;
}
qint64 BufferingQuery::rangeStop() const
{
gint64 r;
gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, &r, NULL);
return r;
}
qint64 BufferingQuery::estimatedTotal() const
{
gint64 r;
gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, NULL, &r);
return r;
}
void BufferingQuery::setValues(Format rangeFormat, qint64 rangeStart, qint64 rangeStop,
qint64 estimatedTotal)
{
gst_query_set_buffering_range(object<GstQuery>(), static_cast<GstFormat>(rangeFormat),
rangeStart, rangeStop, estimatedTotal);
}
//********************************************************
UriQueryPtr UriQuery::create()
{
return UriQueryPtr::wrap(gst_query_new_uri(), false);
}
QUrl UriQuery::uri() const
{
gchar *uri;
gst_query_parse_uri(object<GstQuery>(), &uri);
return QUrl::fromPercentEncoding(uri);
}
void UriQuery::setValue(const QUrl & uri)
{
gst_query_set_uri(object<GstQuery>(), uri.toEncoded());
}
//********************************************************
} //namespace QGst
QGLIB_REGISTER_VALUEIMPL_IMPLEMENTATION(
QGst::QueryPtr,
QGst::QueryPtr::wrap(GST_QUERY(gst_value_get_mini_object(value))),
gst_value_set_mini_object(value, GST_MINI_OBJECT(static_cast<GstQuery*>(data)))
)
QDebug operator<<(QDebug debug, QGst::QueryType type)
{
debug.nospace() << gst_query_type_get_name(static_cast<GstQueryType>(type));
return debug.space();
}
QDebug operator<<(QDebug debug, const QGst::QueryPtr & query)
{
debug.nospace() << "QGst::Query(Type: " << query->type() << ")";
return debug.space();
}
<|endoftext|> |
<commit_before>AliAnalysisTaskSE *AddTaskLambdac(TString finname,Bool_t storeNtuple,Bool_t readMC,Bool_t MCPid,Bool_t realPid,Bool_t resPid,Bool_t useKF,
Bool_t fillVarHists=kFALSE, Bool_t priorsHists=kFALSE, Bool_t multiplicityHists=kFALSE)
{
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskLambdac", "No analysis manager to connect to.");
return NULL;
}
Bool_t stdcuts=kFALSE;
TFile* filecuts;
if( finname.EqualTo("") ) {
stdcuts=kTRUE;
} else {
filecuts=TFile::Open(finname.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
AliFatal("Input file not found : check your cut object");
}
}
AliRDHFCutsLctopKpi* prodcuts=new AliRDHFCutsLctopKpi();
if(stdcuts) prodcuts->SetStandardCutsPP2010();
else prodcuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiProdCuts");
prodcuts->SetName("LctopKpiProdCuts");
prodcuts->SetMinPtCandidate(-1.);
prodcuts->SetMaxPtCandidate(10000.);
AliRDHFCutsLctopKpi *analysiscuts = new AliRDHFCutsLctopKpi();
if(stdcuts) analysiscuts->SetStandardCutsPP2010();
else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiAnalysisCuts");
analysiscuts->SetName("LctopKpiAnalysisCuts");
analysiscuts->SetMinPtCandidate(-1.);
analysiscuts->SetMaxPtCandidate(10000.);
// Aanalysis task
AliAnalysisTaskSELambdac *lambdacTask = new AliAnalysisTaskSELambdac("LambdacAnalysis",storeNtuple,analysiscuts,prodcuts);
lambdacTask->SetReadMC(readMC);
if(MCPid) lambdacTask->SetMCPid();
if(resPid) lambdacTask->SetResonantPid();
if(realPid) lambdacTask->SetRealPid();
lambdacTask->SetFillVarHists(fillVarHists);
lambdacTask->SetPriorsHists(priorsHists);
lambdacTask->SetMultiplicityHists(multiplicityHists);
lambdacTask->SetAnalysis(kTRUE);
lambdacTask->SetDebugLevel(0);
if(useKF) {
lambdacTask->SetUseKF();
Float_t cuts[10]={0.1,0.1,1.5,0.5,0.1,1.5,0.5,0.1,1.5,0.5};
lambdacTask->SetCutsKF(cuts);
}
mgr->AddTask(lambdacTask);
//
// Create containers for input/output
TString outputfile = AliAnalysisManager::GetCommonFileName();
outputfile += ":PWG3_D2H_InvMassLambdac";
TString finDirname="First_PbPb";
TString inname = "cinputLc";
TString outname = "coutputLc";
TString cutsname = "coutputLcCuts";
TString normname = "coutputLcNorm";
TString ntuplename = "coutputLc2";
TString nev2 = "coutputNev";
TString outname2 = "coutputLambdacMC";
TString aPrioriname = "coutputAPriori";
TString multiplicityname = "coutputMultiplicity";
inname += finDirname.Data();
outname += finDirname.Data();
cutsname += finDirname.Data();
normname += finDirname.Data();
ntuplename += finDirname.Data();
nev2 += finDirname.Data();
outname2 += finDirname.Data();
aPrioriname += finDirname.Data();
multiplicityname += finDirname.Data();
TString centr=Form("%.0f%.0f",analysiscuts->GetMinCentrality(),analysiscuts->GetMaxCentrality());
inname += centr;
outname += centr;
cutsname += centr;
normname += centr;
ntuplename += centr;
nev2 += centr;
outname2 += centr;
aPrioriname += centr;
multiplicityname += centr;
AliAnalysisDataContainer *cinputLambdac = mgr->CreateContainer(inname,TChain::Class(),
AliAnalysisManager::kInputContainer);
mgr->ConnectInput(lambdacTask,0,mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutputLambdacCuts = mgr->CreateContainer(cutsname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,2,coutputLambdacCuts);
AliAnalysisDataContainer *coutputLambdac = mgr->CreateContainer(outname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,1,coutputLambdac);
AliAnalysisDataContainer *coutputLambdacMC = mgr->CreateContainer(outname2,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,3,coutputLambdacMC);
AliAnalysisDataContainer *coutputLambdacNev = mgr->CreateContainer(nev2,TH1F::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,4,coutputLambdacNev);
AliAnalysisDataContainer *coutputAPriori = mgr->CreateContainer(aPrioriname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,5,coutputAPriori);
AliAnalysisDataContainer *coutputMultiplicity = mgr->CreateContainer(multiplicityname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,6,coutputMultiplicity);
AliAnalysisDataContainer *coutputLambdacNorm = mgr->CreateContainer(normname,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,7,coutputLambdacNorm);
if (storeNtuple) {
AliAnalysisDataContainer *coutputLambdac2 = mgr->CreateContainer(ntuplename,TNtuple::Class(),
AliAnalysisManager::kOutputContainer,"InvMassLambdac_nt1.root");
coutputLambdac2->SetSpecialOutput();
mgr->ConnectOutput(lambdacTask,7,coutputLambdac2);
}
return lambdacTask;
}
<commit_msg>Update AddTask (Rossella)<commit_after>AliAnalysisTaskSE *AddTaskLambdac(TString finname,Bool_t storeNtuple,Bool_t readMC,Bool_t MCPid,Bool_t realPid,Bool_t resPid,Bool_t useKF,
Bool_t fillVarHists=kFALSE, Bool_t priorsHists=kFALSE, Bool_t multiplicityHists=kFALSE, TString postname="")
{
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskLambdac", "No analysis manager to connect to.");
return NULL;
}
Bool_t stdcuts=kFALSE;
TFile* filecuts;
if( finname.EqualTo("") ) {
stdcuts=kTRUE;
} else {
filecuts=TFile::Open(finname.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
AliFatal("Input file not found : check your cut object");
}
}
AliRDHFCutsLctopKpi* prodcuts=new AliRDHFCutsLctopKpi();
if(stdcuts) prodcuts->SetStandardCutsPP2010();
else prodcuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiProdCuts");
prodcuts->SetName("LctopKpiProdCuts");
prodcuts->SetMinPtCandidate(-1.);
prodcuts->SetMaxPtCandidate(10000.);
AliRDHFCutsLctopKpi *analysiscuts = new AliRDHFCutsLctopKpi();
if(stdcuts) analysiscuts->SetStandardCutsPP2010();
else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiAnalysisCuts");
analysiscuts->SetName("LctopKpiAnalysisCuts");
analysiscuts->SetMinPtCandidate(-1.);
analysiscuts->SetMaxPtCandidate(10000.);
// Aanalysis task
AliAnalysisTaskSELambdac *lambdacTask = new AliAnalysisTaskSELambdac("LambdacAnalysis",storeNtuple,analysiscuts,prodcuts);
lambdacTask->SetReadMC(readMC);
if(MCPid) lambdacTask->SetMCPid();
if(resPid) lambdacTask->SetResonantPid();
if(realPid) lambdacTask->SetRealPid();
lambdacTask->SetFillVarHists(fillVarHists);
lambdacTask->SetPriorsHists(priorsHists);
lambdacTask->SetMultiplicityHists(multiplicityHists);
lambdacTask->SetAnalysis(kTRUE);
lambdacTask->SetDebugLevel(0);
if(useKF) {
lambdacTask->SetUseKF();
Float_t cuts[10]={0.1,0.1,1.5,0.5,0.1,1.5,0.5,0.1,1.5,0.5};
lambdacTask->SetCutsKF(cuts);
}
mgr->AddTask(lambdacTask);
//
// Create containers for input/output
TString outputfile = AliAnalysisManager::GetCommonFileName();
outputfile += ":PWG3_D2H_InvMassLambdac";
TString finDirname="pp";
TString inname = "cinputLc";
TString outname = "coutputLc";
TString cutsname = "coutputLcCuts";
TString normname = "coutputLcNorm";
TString ntuplename = "coutputLc2";
TString nev2 = "coutputNev";
TString outname2 = "coutputLambdacMC";
TString aPrioriname = "coutputAPriori";
TString multiplicityname = "coutputMultiplicity";
inname += finDirname.Data();
outname += finDirname.Data();
cutsname += finDirname.Data();
normname += finDirname.Data();
ntuplename += finDirname.Data();
nev2 += finDirname.Data();
outname2 += finDirname.Data();
aPrioriname += finDirname.Data();
multiplicityname += finDirname.Data();
inname += postname.Data();
outname += postname.Data();
cutsname += postname.Data();
normname += postname.Data();
ntuplename += postname.Data();
nev2 += postname.Data();
outname2 += postname.Data();
aPrioriname += postname.Data();
multiplicityname += postname.Data();
AliAnalysisDataContainer *cinputLambdac = mgr->CreateContainer(inname,TChain::Class(),
AliAnalysisManager::kInputContainer);
mgr->ConnectInput(lambdacTask,0,mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutputLambdacCuts = mgr->CreateContainer(cutsname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,2,coutputLambdacCuts);
AliAnalysisDataContainer *coutputLambdac = mgr->CreateContainer(outname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,1,coutputLambdac);
AliAnalysisDataContainer *coutputLambdacMC = mgr->CreateContainer(outname2,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,3,coutputLambdacMC);
AliAnalysisDataContainer *coutputLambdacNev = mgr->CreateContainer(nev2,TH1F::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,4,coutputLambdacNev);
AliAnalysisDataContainer *coutputAPriori = mgr->CreateContainer(aPrioriname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,5,coutputAPriori);
AliAnalysisDataContainer *coutputMultiplicity = mgr->CreateContainer(multiplicityname,TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,6,coutputMultiplicity);
AliAnalysisDataContainer *coutputLambdacNorm = mgr->CreateContainer(normname,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
mgr->ConnectOutput(lambdacTask,7,coutputLambdacNorm);
if (storeNtuple) {
AliAnalysisDataContainer *coutputLambdac2 = mgr->CreateContainer(ntuplename,TNtuple::Class(),
AliAnalysisManager::kOutputContainer,"InvMassLambdac_nt1.root");
coutputLambdac2->SetSpecialOutput();
mgr->ConnectOutput(lambdacTask,7,coutputLambdac2);
}
return lambdacTask;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "PathBasedIndex.h"
#include "Aql/AstNode.h"
#include "Basics/Logger.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
arangodb::aql::AstNode const* PathBasedIndex::PermutationState::getValue()
const {
if (type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ) {
TRI_ASSERT(current == 0);
return value;
} else if (type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN) {
TRI_ASSERT(n > 0);
TRI_ASSERT(current < n);
return value->getMember(current);
}
TRI_ASSERT(false);
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief create the index
////////////////////////////////////////////////////////////////////////////////
PathBasedIndex::PathBasedIndex(
TRI_idx_iid_t iid, TRI_document_collection_t* collection,
std::vector<std::vector<arangodb::basics::AttributeName>> const& fields,
bool unique, bool sparse, bool allowPartialIndex)
: Index(iid, collection, fields, unique, sparse),
_useExpansion(false),
_allowPartialIndex(allowPartialIndex) {
TRI_ASSERT(!fields.empty());
TRI_ASSERT(iid != 0);
fillPaths(_paths, _expanding);
for (auto const& it : fields) {
if (TRI_AttributeNamesHaveExpansion(it)) {
_useExpansion = true;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief create an index stub with a hard-coded selectivity estimate
/// this is used in the cluster coordinator case
////////////////////////////////////////////////////////////////////////////////
PathBasedIndex::PathBasedIndex(VPackSlice const& slice, bool allowPartialIndex)
: Index(slice),
_paths(),
_useExpansion(false),
_allowPartialIndex(allowPartialIndex) {
TRI_ASSERT(!_fields.empty());
for (auto const& it : _fields) {
if (TRI_AttributeNamesHaveExpansion(it)) {
_useExpansion = true;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroy the index
////////////////////////////////////////////////////////////////////////////////
PathBasedIndex::~PathBasedIndex() {}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to insert a document into any index type
////////////////////////////////////////////////////////////////////////////////
int PathBasedIndex::fillElement(std::vector<TRI_index_element_t*>& elements,
TRI_doc_mptr_t const* document) {
TRI_ASSERT(document != nullptr);
TRI_ASSERT(document->getDataPtr() != nullptr);
VPackSlice const slice(document->vpack());
if (slice.isNone()) {
LOG(WARN) << "encountered invalid marker with slice of type None";
return TRI_ERROR_INTERNAL;
}
TRI_IF_FAILURE("FillElementIllegalSlice") { return TRI_ERROR_INTERNAL; }
size_t const n = _paths.size();
if (!_useExpansion) {
// fast path for inserts... no array elements used
auto slices = buildIndexValue(slice);
if (slices.size() == n) {
// if shapes.size() != n, then the value is not inserted into the index
// because of index sparsity!
TRI_index_element_t* element = TRI_index_element_t::allocate(n);
if (element == nullptr) {
return TRI_ERROR_OUT_OF_MEMORY;
}
TRI_IF_FAILURE("FillElementOOM") {
// clean up manually
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
element->document(const_cast<TRI_doc_mptr_t*>(document));
TRI_vpack_sub_t* subObjects = element->subObjects();
for (size_t i = 0; i < n; ++i) {
TRI_FillVPackSub(&subObjects[i], slice, slices[i]);
}
try {
TRI_IF_FAILURE("FillElementOOM2") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
elements.emplace_back(element);
} catch (...) {
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
}
} else {
// other path for handling array elements, too
std::vector<std::vector<VPackSlice>> toInsert;
std::vector<VPackSlice> sliceStack;
buildIndexValues(slice, 0, toInsert, sliceStack);
if (!toInsert.empty()) {
elements.reserve(toInsert.size());
for (auto& info : toInsert) {
TRI_ASSERT(info.size() == n);
TRI_index_element_t* element = TRI_index_element_t::allocate(n);
if (element == nullptr) {
return TRI_ERROR_OUT_OF_MEMORY;
}
TRI_IF_FAILURE("FillElementOOM") {
// clean up manually
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
element->document(const_cast<TRI_doc_mptr_t*>(document));
TRI_vpack_sub_t* subObjects = element->subObjects();
for (size_t j = 0; j < n; ++j) {
TRI_FillVPackSub(&subObjects[j], slice, info[j]);
}
try {
TRI_IF_FAILURE("FillElementOOM2") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
elements.emplace_back(element);
} catch (...) {
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
}
}
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to create the sole index value insert
////////////////////////////////////////////////////////////////////////////////
std::vector<VPackSlice> PathBasedIndex::buildIndexValue(
VPackSlice const documentSlice) {
size_t const n = _paths.size();
std::vector<VPackSlice> result;
for (size_t i = 0; i < n; ++i) {
TRI_ASSERT(!_paths[i].empty());
VPackSlice slice = documentSlice.get(_paths[i]);
if (slice.isNone()) {
// attribute not found
if (_sparse) {
// if sparse we do not have to index, this is indicated by result
// being shorter than n
result.clear();
break;
}
slice.set(reinterpret_cast<uint8_t const*>("\0x18"));
// null, note that this will be copied later!
}
result.push_back(slice);
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to create a set of index combinations to insert
////////////////////////////////////////////////////////////////////////////////
void PathBasedIndex::buildIndexValues(
VPackSlice const document, size_t level,
std::vector<std::vector<VPackSlice>>& toInsert,
std::vector<VPackSlice>& sliceStack) {
// Invariant: level == sliceStack.size()
// Stop the recursion:
if (level == _paths.size()) {
toInsert.push_back(sliceStack);
return;
}
if (_expanding[level] == -1) { // the trivial, non-expanding case
VPackSlice slice = document.get(_paths[level]);
if (slice.isNone()) {
if (_sparse) {
return;
}
slice.set(reinterpret_cast<uint8_t const*>("\0x18")); // null
}
sliceStack.push_back(slice);
buildIndexValues(document, level+1, toInsert, sliceStack);
sliceStack.pop_back();
return;
}
// Finally, the complex case, where we have to expand one entry.
// Note again that at most one step in the attribute path can be
// an array step. Furthermore, if _allowPartialIndex is true and
// anything goes wrong with this attribute path, we have to bottom out
// with None values to be able to use the index for a prefix match.
auto finishWithNones = [&]() -> void {
if (level > 0 && !_allowPartialIndex) {
return;
}
// Trivial case to bottom out with None types.
VPackSlice noneSlice;
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.push_back(noneSlice);
}
toInsert.push_back(sliceStack);
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.pop_back();
}
};
size_t const n = _paths[level].size();
// We have 0 <= _expanding[level] < n.
VPackSlice current(document);
for (size_t i = 0; i <= static_cast<size_t>(_expanding[level]); i++) {
if (!current.isObject()) {
finishWithNones();
return;
}
current = current.get(_paths[level][i]);
if (current.isNone()) {
finishWithNones();
return;
}
}
// Now the expansion:
if (!current.isArray() || current.length() == 0) {
finishWithNones();
return;
}
std::unordered_set<VPackSlice> seen;
auto moveOn = [&](VPackSlice something) -> void {
auto it = seen.find(something);
if (it != seen.end()) {
seen.insert(something);
sliceStack.push_back(something);
buildIndexValues(document, level+1, toInsert, sliceStack);
sliceStack.pop_back();
}
};
VPackSlice null("\x18");
for (auto const& member : VPackArrayIterator(current)) {
VPackSlice current2(member);
bool doneNull = false;
for (size_t i = _expanding[level]+1; i < n; i++) {
if (!current2.isObject()) {
if (!_sparse) {
moveOn(null);
}
doneNull = true;
break;
}
current2 = current2.get(_paths[level][i]);
if (current2.isNone()) {
if (!_sparse) {
moveOn(null);
}
doneNull = true;
break;
}
}
if (!doneNull) {
moveOn(current2);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to transform AttributeNames into strings.
////////////////////////////////////////////////////////////////////////////////
void PathBasedIndex::fillPaths(std::vector<std::vector<std::string>>& paths,
std::vector<int>& expanding) {
paths.clear();
expanding.clear();
for (std::vector<arangodb::basics::AttributeName> const& list : _fields) {
paths.emplace_back();
std::vector<std::string>& interior(paths.back());
int expands = -1;
int count = 0;
std::vector<std::string> joinedNames;
for (auto const& att : list) {
interior.push_back(att.name);
if (att.shouldExpand) {
expands = count;
}
++count;
}
expanding.push_back(expands);
}
}
<commit_msg>Fix buildIndexValues.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "PathBasedIndex.h"
#include "Aql/AstNode.h"
#include "Basics/Logger.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
arangodb::aql::AstNode const* PathBasedIndex::PermutationState::getValue()
const {
if (type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ) {
TRI_ASSERT(current == 0);
return value;
} else if (type == arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN) {
TRI_ASSERT(n > 0);
TRI_ASSERT(current < n);
return value->getMember(current);
}
TRI_ASSERT(false);
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief create the index
////////////////////////////////////////////////////////////////////////////////
PathBasedIndex::PathBasedIndex(
TRI_idx_iid_t iid, TRI_document_collection_t* collection,
std::vector<std::vector<arangodb::basics::AttributeName>> const& fields,
bool unique, bool sparse, bool allowPartialIndex)
: Index(iid, collection, fields, unique, sparse),
_useExpansion(false),
_allowPartialIndex(allowPartialIndex) {
TRI_ASSERT(!fields.empty());
TRI_ASSERT(iid != 0);
fillPaths(_paths, _expanding);
for (auto const& it : fields) {
if (TRI_AttributeNamesHaveExpansion(it)) {
_useExpansion = true;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief create an index stub with a hard-coded selectivity estimate
/// this is used in the cluster coordinator case
////////////////////////////////////////////////////////////////////////////////
PathBasedIndex::PathBasedIndex(VPackSlice const& slice, bool allowPartialIndex)
: Index(slice),
_paths(),
_useExpansion(false),
_allowPartialIndex(allowPartialIndex) {
TRI_ASSERT(!_fields.empty());
for (auto const& it : _fields) {
if (TRI_AttributeNamesHaveExpansion(it)) {
_useExpansion = true;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroy the index
////////////////////////////////////////////////////////////////////////////////
PathBasedIndex::~PathBasedIndex() {}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to insert a document into any index type
////////////////////////////////////////////////////////////////////////////////
int PathBasedIndex::fillElement(std::vector<TRI_index_element_t*>& elements,
TRI_doc_mptr_t const* document) {
TRI_ASSERT(document != nullptr);
TRI_ASSERT(document->getDataPtr() != nullptr);
VPackSlice const slice(document->vpack());
if (slice.isNone()) {
LOG(WARN) << "encountered invalid marker with slice of type None";
return TRI_ERROR_INTERNAL;
}
TRI_IF_FAILURE("FillElementIllegalSlice") { return TRI_ERROR_INTERNAL; }
size_t const n = _paths.size();
if (!_useExpansion) {
// fast path for inserts... no array elements used
auto slices = buildIndexValue(slice);
if (slices.size() == n) {
// if shapes.size() != n, then the value is not inserted into the index
// because of index sparsity!
TRI_index_element_t* element = TRI_index_element_t::allocate(n);
if (element == nullptr) {
return TRI_ERROR_OUT_OF_MEMORY;
}
TRI_IF_FAILURE("FillElementOOM") {
// clean up manually
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
element->document(const_cast<TRI_doc_mptr_t*>(document));
TRI_vpack_sub_t* subObjects = element->subObjects();
for (size_t i = 0; i < n; ++i) {
TRI_FillVPackSub(&subObjects[i], slice, slices[i]);
}
try {
TRI_IF_FAILURE("FillElementOOM2") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
elements.emplace_back(element);
} catch (...) {
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
}
} else {
// other path for handling array elements, too
std::vector<std::vector<VPackSlice>> toInsert;
std::vector<VPackSlice> sliceStack;
buildIndexValues(slice, 0, toInsert, sliceStack);
if (!toInsert.empty()) {
elements.reserve(toInsert.size());
for (auto& info : toInsert) {
TRI_ASSERT(info.size() == n);
TRI_index_element_t* element = TRI_index_element_t::allocate(n);
if (element == nullptr) {
return TRI_ERROR_OUT_OF_MEMORY;
}
TRI_IF_FAILURE("FillElementOOM") {
// clean up manually
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
element->document(const_cast<TRI_doc_mptr_t*>(document));
TRI_vpack_sub_t* subObjects = element->subObjects();
for (size_t j = 0; j < n; ++j) {
TRI_FillVPackSub(&subObjects[j], slice, info[j]);
}
try {
TRI_IF_FAILURE("FillElementOOM2") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
elements.emplace_back(element);
} catch (...) {
TRI_index_element_t::freeElement(element);
return TRI_ERROR_OUT_OF_MEMORY;
}
}
}
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to create the sole index value insert
////////////////////////////////////////////////////////////////////////////////
std::vector<VPackSlice> PathBasedIndex::buildIndexValue(
VPackSlice const documentSlice) {
size_t const n = _paths.size();
std::vector<VPackSlice> result;
for (size_t i = 0; i < n; ++i) {
TRI_ASSERT(!_paths[i].empty());
VPackSlice slice = documentSlice.get(_paths[i]);
if (slice.isNone()) {
// attribute not found
if (_sparse) {
// if sparse we do not have to index, this is indicated by result
// being shorter than n
result.clear();
break;
}
slice.set(reinterpret_cast<uint8_t const*>("\0x18"));
// null, note that this will be copied later!
}
result.push_back(slice);
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to create a set of index combinations to insert
////////////////////////////////////////////////////////////////////////////////
void PathBasedIndex::buildIndexValues(
VPackSlice const document, size_t level,
std::vector<std::vector<VPackSlice>>& toInsert,
std::vector<VPackSlice>& sliceStack) {
// Invariant: level == sliceStack.size()
// Stop the recursion:
if (level == _paths.size()) {
toInsert.push_back(sliceStack);
return;
}
if (_expanding[level] == -1) { // the trivial, non-expanding case
VPackSlice slice = document.get(_paths[level]);
if (slice.isNone()) {
if (_sparse) {
return;
}
slice.set(reinterpret_cast<uint8_t const*>("\0x18")); // null
}
sliceStack.push_back(slice);
buildIndexValues(document, level+1, toInsert, sliceStack);
sliceStack.pop_back();
return;
}
// Finally, the complex case, where we have to expand one entry.
// Note again that at most one step in the attribute path can be
// an array step. Furthermore, if _allowPartialIndex is true and
// anything goes wrong with this attribute path, we have to bottom out
// with None values to be able to use the index for a prefix match.
auto finishWithNones = [&]() -> void {
if (level > 0 && !_allowPartialIndex) {
return;
}
// Trivial case to bottom out with None types.
VPackSlice noneSlice;
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.push_back(noneSlice);
}
toInsert.push_back(sliceStack);
for (size_t i = level; i < _paths.size(); i++) {
sliceStack.pop_back();
}
};
size_t const n = _paths[level].size();
// We have 0 <= _expanding[level] < n.
VPackSlice current(document);
for (size_t i = 0; i <= static_cast<size_t>(_expanding[level]); i++) {
if (!current.isObject()) {
finishWithNones();
return;
}
current = current.get(_paths[level][i]);
if (current.isNone()) {
finishWithNones();
return;
}
}
// Now the expansion:
if (!current.isArray() || current.length() == 0) {
finishWithNones();
return;
}
std::unordered_set<VPackSlice> seen;
auto moveOn = [&](VPackSlice something) -> void {
auto it = seen.find(something);
if (it != seen.end()) {
seen.insert(something);
sliceStack.push_back(something);
buildIndexValues(document, level+1, toInsert, sliceStack);
sliceStack.pop_back();
}
};
VPackSlice null("\x18");
for (auto const& member : VPackArrayIterator(current)) {
VPackSlice current2(member);
bool doneNull = false;
for (size_t i = _expanding[level]+1; i < n; i++) {
if (!current2.isObject()) {
if (!_sparse) {
moveOn(null);
}
doneNull = true;
break;
}
current2 = current2.get(_paths[level][i]);
if (current2.isNone()) {
if (!_sparse) {
moveOn(null);
}
doneNull = true;
break;
}
}
if (!doneNull) {
moveOn(current2);
}
// Finally, if, because of sparsity, we have not inserted anything by now,
// we need to play the above trick with None because of the above mentioned
// reasons:
if (seen.empty()) {
finishWithNones();
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to transform AttributeNames into strings.
////////////////////////////////////////////////////////////////////////////////
void PathBasedIndex::fillPaths(std::vector<std::vector<std::string>>& paths,
std::vector<int>& expanding) {
paths.clear();
expanding.clear();
for (std::vector<arangodb::basics::AttributeName> const& list : _fields) {
paths.emplace_back();
std::vector<std::string>& interior(paths.back());
int expands = -1;
int count = 0;
std::vector<std::string> joinedNames;
for (auto const& att : list) {
interior.push_back(att.name);
if (att.shouldExpand) {
expands = count;
}
++count;
}
expanding.push_back(expands);
}
}
<|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 "base/registry.h"
#include "base/string_util.h"
#include "chrome/common/win_util.h"
#include "testing/gtest/include/gtest/gtest.h"
class WinUtilTest: public testing::Test {
};
// Retrieve the OS primary language
unsigned GetSystemLanguage() {
RegKey language_key(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Nls\\Language");
std::wstring language;
language_key.ReadValue(L"InstallLanguage", &language);
wchar_t * unused_endptr;
return PRIMARYLANGID(wcstol(language.c_str(), &unused_endptr, 16));
}
TEST(WinUtilTest, FormatMessage) {
const int kAccessDeniedErrorCode = 5;
SetLastError(kAccessDeniedErrorCode);
ASSERT_EQ(GetLastError(), kAccessDeniedErrorCode);
std::wstring value;
unsigned language = GetSystemLanguage();
ASSERT_TRUE(language);
if (language == LANG_ENGLISH) {
// This test would fail on non-English system.
TrimWhitespace(win_util::FormatLastWin32Error(), TRIM_ALL, &value);
EXPECT_EQ(value, std::wstring(L"Access is denied."));
} else if (language == LANG_FRENCH) {
// This test would fail on non-French system.
TrimWhitespace(win_util::FormatLastWin32Error(), TRIM_ALL, &value);
EXPECT_EQ(value, std::wstring(L"Acc\00e8s refus\00e9."));
} else {
EXPECT_TRUE(0) << "Please implement the test for your OS language.";
}
// Manually call the OS function
wchar_t * string_buffer = NULL;
unsigned string_length = ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
kAccessDeniedErrorCode, 0,
reinterpret_cast<wchar_t *>(&string_buffer),
0, NULL);
// Verify the call succeeded
ASSERT_TRUE(string_length);
ASSERT_TRUE(string_buffer);
// Verify the string is the same by different calls
EXPECT_EQ(win_util::FormatLastWin32Error(), std::wstring(string_buffer));
EXPECT_EQ(win_util::FormatMessage(kAccessDeniedErrorCode),
std::wstring(string_buffer));
// Done with the buffer allocated by ::FormatMessage()
LocalFree(string_buffer);
}
TEST(WinUtilTest, EnsureRectIsVisibleInRect) {
gfx::Rect parent_rect(0, 0, 500, 400);
{
// Child rect x < 0
gfx::Rect child_rect(-50, 20, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(10, 20, 100, 100), child_rect);
}
{
// Child rect y < 0
gfx::Rect child_rect(20, -50, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 10, 100, 100), child_rect);
}
{
// Child rect right > parent_rect.right
gfx::Rect child_rect(450, 20, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(390, 20, 100, 100), child_rect);
}
{
// Child rect bottom > parent_rect.bottom
gfx::Rect child_rect(20, 350, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 290, 100, 100), child_rect);
}
{
// Child rect width > parent_rect.width
gfx::Rect child_rect(20, 20, 700, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 20, 480, 100), child_rect);
}
{
// Child rect height > parent_rect.height
gfx::Rect child_rect(20, 20, 100, 700);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 20, 100, 380), child_rect);
}
}
<commit_msg>Fix the unit test when run from a MUI-Aware Vista installation and the current UI language is not the same as the installation language.<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 "base/registry.h"
#include "base/string_util.h"
#include "chrome/common/win_util.h"
#include "testing/gtest/include/gtest/gtest.h"
class WinUtilTest: public testing::Test {
protected:
// Retrieve the OS primary language
static unsigned GetSystemLanguage() {
std::wstring language;
typedef BOOL (WINAPI *fnGetThreadPreferredUILanguages)(
DWORD dwFlags,
PULONG pulNumLanguages,
PWSTR pwszLanguagesBuffer,
PULONG pcchLanguagesBuffer);
fnGetThreadPreferredUILanguages pGetThreadPreferredUILanguages = NULL;
pGetThreadPreferredUILanguages =
reinterpret_cast<fnGetThreadPreferredUILanguages>(
GetProcAddress(GetModuleHandle(L"kernel32.dll"),
"GetThreadPreferredUILanguages"));
if (pGetThreadPreferredUILanguages) {
// Vista, MUI-aware.
ULONG number = 0;
wchar_t buffer[256] = {0};
ULONG buffer_size = sizeof(buffer);
EXPECT_TRUE(pGetThreadPreferredUILanguages(MUI_LANGUAGE_ID, &number,
buffer, &buffer_size));
language = buffer;
} else {
// XP
RegKey language_key(HKEY_LOCAL_MACHINE,
L"SYSTEM\\CurrentControlSet\\Control\\Nls\\Language");
language_key.ReadValue(L"InstallLanguage", &language);
}
wchar_t * unused_endptr;
return PRIMARYLANGID(wcstol(language.c_str(), &unused_endptr, 16));
}
};
TEST_F(WinUtilTest, FormatMessage) {
const int kAccessDeniedErrorCode = 5;
SetLastError(kAccessDeniedErrorCode);
ASSERT_EQ(GetLastError(), kAccessDeniedErrorCode);
std::wstring value;
unsigned language = GetSystemLanguage();
ASSERT_TRUE(language);
if (language == LANG_ENGLISH) {
// This test would fail on non-English system.
TrimWhitespace(win_util::FormatLastWin32Error(), TRIM_ALL, &value);
EXPECT_EQ(std::wstring(L"Access is denied."), value);
} else if (language == LANG_FRENCH) {
// This test would fail on non-French system.
TrimWhitespace(win_util::FormatLastWin32Error(), TRIM_ALL, &value);
EXPECT_EQ(std::wstring(L"Acc\u00e8s refus\u00e9."), value);
} else {
EXPECT_TRUE(0) << "Please implement the test for your OS language.";
}
// Manually call the OS function
wchar_t * string_buffer = NULL;
unsigned string_length = ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
kAccessDeniedErrorCode, 0,
reinterpret_cast<wchar_t *>(&string_buffer),
0, NULL);
// Verify the call succeeded
ASSERT_TRUE(string_length);
ASSERT_TRUE(string_buffer);
// Verify the string is the same by different calls
EXPECT_EQ(win_util::FormatLastWin32Error(), std::wstring(string_buffer));
EXPECT_EQ(win_util::FormatMessage(kAccessDeniedErrorCode),
std::wstring(string_buffer));
// Done with the buffer allocated by ::FormatMessage()
LocalFree(string_buffer);
}
TEST_F(WinUtilTest, EnsureRectIsVisibleInRect) {
gfx::Rect parent_rect(0, 0, 500, 400);
{
// Child rect x < 0
gfx::Rect child_rect(-50, 20, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(10, 20, 100, 100), child_rect);
}
{
// Child rect y < 0
gfx::Rect child_rect(20, -50, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 10, 100, 100), child_rect);
}
{
// Child rect right > parent_rect.right
gfx::Rect child_rect(450, 20, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(390, 20, 100, 100), child_rect);
}
{
// Child rect bottom > parent_rect.bottom
gfx::Rect child_rect(20, 350, 100, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 290, 100, 100), child_rect);
}
{
// Child rect width > parent_rect.width
gfx::Rect child_rect(20, 20, 700, 100);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 20, 480, 100), child_rect);
}
{
// Child rect height > parent_rect.height
gfx::Rect child_rect(20, 20, 100, 700);
win_util::EnsureRectIsVisibleInRect(parent_rect, &child_rect, 10);
EXPECT_EQ(gfx::Rect(20, 20, 100, 380), child_rect);
}
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "PhononPlayerModule.h"
#include "Service.h"
//#include "Service.h"
namespace PlayerService
{
std::string PhononPlayerModule::type_name_static_ = "PhononPlayer";
PhononPlayerModule::PhononPlayerModule()
: ModuleInterface(type_name_static_)
{
}
PhononPlayerModule::~PhononPlayerModule()
{
}
void PhononPlayerModule::Load()
{
}
void PhononPlayerModule::Unload()
{
}
void PhononPlayerModule::Initialize()
{
player_service_ = Player::PlayerServicePtr(new PlayerService::Service());
framework_->GetServiceManager()->RegisterService(Foundation::Service::ST_Player, player_service_);
}
void PhononPlayerModule::PostInitialize()
{
}
void PhononPlayerModule::Uninitialize()
{
if (player_service_)
framework_->GetServiceManager()->UnregisterService(player_service_);
}
void PhononPlayerModule::Update(f64 frametime)
{
}
bool PhononPlayerModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data)
{
return false;
}
} // PlayerService
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
using namespace PlayerService;
POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
POCO_EXPORT_CLASS(PhononPlayerModule)
POCO_END_MANIFEST
<commit_msg>Fixed include header order.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "PhononPlayerModule.h"
#include "Service.h"
#include "MemoryLeakCheck.h"
namespace PlayerService
{
std::string PhononPlayerModule::type_name_static_ = "PhononPlayer";
PhononPlayerModule::PhononPlayerModule()
: ModuleInterface(type_name_static_)
{
}
PhononPlayerModule::~PhononPlayerModule()
{
}
void PhononPlayerModule::Load()
{
}
void PhononPlayerModule::Unload()
{
}
void PhononPlayerModule::Initialize()
{
player_service_ = Player::PlayerServicePtr(new PlayerService::Service());
framework_->GetServiceManager()->RegisterService(Foundation::Service::ST_Player, player_service_);
}
void PhononPlayerModule::PostInitialize()
{
}
void PhononPlayerModule::Uninitialize()
{
if (player_service_)
framework_->GetServiceManager()->UnregisterService(player_service_);
}
void PhononPlayerModule::Update(f64 frametime)
{
}
bool PhononPlayerModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data)
{
return false;
}
} // PlayerService
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
using namespace PlayerService;
POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
POCO_EXPORT_CLASS(PhononPlayerModule)
POCO_END_MANIFEST
<|endoftext|> |
<commit_before>#define _XOPEN_SOURCE 600
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#define snprintf _snprintf
//#define strdup _strdup
#define strerror_r(errno, buf, buflen) strerror_s(buf, buflen, errno)
typedef unsigned __int64 uint64_t;
typedef __int64 int64_t;
#define Log_GetThreadID() (uint64_t)(GetCurrentThreadId())
#else
#include <sys/time.h>
#include <pthread.h>
#include <stdint.h>
#define Log_GetThreadID() ((uint64_t)(pthread_self()))
#endif
#include "Log.h"
#include "Formatting.h"
#include "System/Threading/Mutex.h"
#define LOG_MSG_SIZE 1024
#define LOG_OLD_EXT ".old"
static bool timestamping = false;
static bool threadedOutput = false;
static bool trace = false;
#ifdef DEBUG
static bool debug = true;
#else
static bool debug = false;
#endif
static int maxLine = LOG_MSG_SIZE;
static int target = LOG_TARGET_NOWHERE;
static FILE* logfile = NULL;
static char* logfilename = NULL;
static uint64_t maxSize = 0;
static uint64_t logFileSize = 0;
static Mutex logFileMutex;
static bool autoFlush = true;
#ifdef _WIN32
typedef char log_timestamp_t[24];
#else
typedef char log_timestamp_t[27];
#endif
static const char* GetFullTimestamp(log_timestamp_t ts)
{
if (!timestamping)
return "";
#ifdef _WIN32
SYSTEMTIME st;
GetLocalTime(&st);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%03d",
(int) st.wYear,
(int) st.wMonth,
(int) st.wDay,
(int) st.wHour,
(int) st.wMinute,
(int) st.wSecond,
(int) st.wMilliseconds);
#else
struct tm tm;
time_t sec;
struct timeval tv;
gettimeofday(&tv, NULL);
sec = (time_t) tv.tv_sec;
localtime_r(&sec, &tm);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%06lu",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
(long unsigned int) tv.tv_usec);
#endif
return ts;
}
// These functions are duplicates of the functions in FileSystem, but here they don't use logging obviously
#ifdef _WIN32
static bool Log_RenameFile(const char* src, const char* dst)
{
BOOL ret;
ret = MoveFileEx(src, dst, MOVEFILE_WRITE_THROUGH);
if (!ret)
return false;
return true;
}
static bool Log_DeleteFile(const char* filename)
{
BOOL ret;
ret = DeleteFile(filename);
if (!ret)
return false;
return true;
}
static int64_t Log_FileSize(const char* path)
{
WIN32_FILE_ATTRIBUTE_DATA attrData;
BOOL ret;
ret = GetFileAttributesEx(path, GetFileExInfoStandard, &attrData);
if (!ret)
return -1;
return ((int64_t) attrData.nFileSizeHigh) << 32 | attrData.nFileSizeLow;
}
#else
static bool Log_RenameFile(const char* src, const char* dst)
{
int ret;
ret = rename(src, dst);
if (ret < 0)
return false;
return true;
}
static bool Log_DeleteFile(const char* filename)
{
int ret;
ret = unlink(filename);
if (ret < 0)
return false;
return true;
}
int64_t FS_FileSize(const char* path)
{
int64_t ret;
struct stat buf;
ret = stat(path, &buf);
if (ret < 0)
return ret;
return buf.st_size;
}
#endif
static void Log_Append(char*& p, int& remaining, const char* s, int len)
{
if (len > remaining)
len = remaining;
if (len > 0)
memcpy(p, s, len);
p += len;
remaining -= len;
}
static void Log_Rotate()
{
char* filenameCopy;
char* oldFilename;
size_t oldFilenameSize;
char* oldOldFilename;
size_t oldOldFilenameSize;
size_t filenameLen;
size_t extLen;
fprintf(stderr, "Rotating...\n");
filenameCopy = strdup(logfilename);
filenameLen = strlen(logfilename);
extLen = sizeof(LOG_OLD_EXT) - 1;
oldFilenameSize = filenameLen + extLen + 1;
oldFilename = new char[oldFilenameSize];
snprintf(oldFilename, oldFilenameSize, "%s" LOG_OLD_EXT, logfilename);
oldOldFilenameSize = filenameLen + extLen + extLen + 1;
oldOldFilename = new char[oldOldFilenameSize];
snprintf(oldOldFilename, oldOldFilenameSize, "%s" LOG_OLD_EXT LOG_OLD_EXT, logfilename);
// delete any previously created temporary file
Log_DeleteFile(oldOldFilename);
// rename the old version to a temporary name
if (!Log_RenameFile(oldFilename, oldOldFilename))
{
Log_DeleteFile(oldFilename);
}
// close the current file
if (logfile)
{
fclose(logfile);
logfile = NULL;
}
// rename the current to old
if (!Log_RenameFile(logfilename, oldFilename))
{
// TODO:
}
// create a new file
Log_SetOutputFile(filenameCopy, true);
// delete any previously created temporary file
Log_DeleteFile(oldOldFilename);
// cleanup
free(filenameCopy);
delete[] oldFilename;
delete[] oldOldFilename;
}
static void Log_Write(const char* buf, int size, int flush)
{
if ((target & LOG_TARGET_STDOUT) == LOG_TARGET_STDOUT)
{
if (buf)
fputs(buf, stdout);
if (flush)
fflush(stdout);
}
if ((target & LOG_TARGET_STDERR) == LOG_TARGET_STDERR)
{
if (buf)
fputs(buf, stderr);
if (flush)
fflush(stderr);
}
if ((target & LOG_TARGET_FILE) == LOG_TARGET_FILE && logfile)
{
logFileMutex.Lock();
if (buf)
fputs(buf, logfile);
if (flush)
fflush(logfile);
if (maxSize > 0)
{
// we keep the previous logfile, hence the division by two
if (logFileSize + size > maxSize / 2)
{
// rotate the logfile
Log_Rotate();
}
else
{
logFileSize += size;
}
}
logFileMutex.Unlock();
}
}
void Log_SetTimestamping(bool ts)
{
timestamping = ts;
}
void Log_SetThreadedOutput(bool to)
{
threadedOutput = to;
}
bool Log_SetTrace(bool trace_)
{
bool prev = trace;
trace = trace_;
return prev;
}
bool Log_SetDebug(bool debug_)
{
bool prev = debug;
debug = debug_;
return prev;
}
bool Log_SetAutoFlush(bool autoFlush_)
{
bool prev = autoFlush;
autoFlush = autoFlush_;
return prev;
}
void Log_SetMaxLine(int maxLine_)
{
maxLine = maxLine_ > LOG_MSG_SIZE ? LOG_MSG_SIZE : maxLine_;
}
void Log_SetTarget(int target_)
{
target = target_;
}
int Log_GetTarget()
{
return target;
}
bool Log_SetOutputFile(const char* filename, bool truncate)
{
if (logfile)
{
fclose(logfile);
free(logfilename);
logfilename = NULL;
}
if (!filename)
return false;
if (truncate)
logfile = fopen(filename, "w");
else
logfile = fopen(filename, "a");
if (!logfile)
{
target &= ~LOG_TARGET_FILE;
return false;
}
logfilename = strdup(filename);
logFileSize = Log_FileSize(filename);
return true;
}
void Log_SetMaxSize(unsigned maxSizeMB)
{
maxSize = ((uint64_t)maxSizeMB) * 1000 * 1000;
}
void Log_Flush()
{
Log_Write(NULL, 0, true);
}
void Log_Shutdown()
{
if (logfilename)
{
free(logfilename);
logfilename = NULL;
}
if (logfile)
{
fclose(logfile);
logfile = NULL;
}
fflush(stdout);
fflush(stderr);
trace = false;
timestamping = false;
}
void Log(const char* file, int line, const char* func, int type, const char* fmt, ...)
{
char buf[LOG_MSG_SIZE];
int remaining;
char *p;
const char *sep;
int ret;
va_list ap;
uint64_t threadID;
// In debug mode enable ERRNO type messages
if ((type == LOG_TYPE_TRACE || type == LOG_TYPE_ERRNO) && !trace)
return;
buf[maxLine - 1] = 0;
p = buf;
remaining = maxLine - 1;
// print timestamp
if (timestamping)
{
GetFullTimestamp(p);
p += sizeof(log_timestamp_t) - 1;
remaining -= sizeof(log_timestamp_t) - 1;
Log_Append(p, remaining, ": ", 2);
}
// print threadID
if (threadedOutput)
{
threadID = Log_GetThreadID();
ret = Writef(p, remaining, "[%U]: ", threadID);
if (ret < 0 || ret > remaining)
ret = remaining;
p += ret;
remaining -= ret;
}
// don't print filename and func in debug mode on ERRNO messages
if (file && func && (type == LOG_TYPE_TRACE || (type == LOG_TYPE_ERRNO && trace)))
{
#ifdef _WIN32
sep = strrchr(file, '/');
if (!sep)
sep = strrchr(file, '\\');
#else
sep = strrchr(file, '/');
#endif
if (sep)
file = sep + 1;
// print filename, number of line and function name
ret = snprintf(p, remaining + 1, "%s:%d:%s()", file, line, func);
if (ret < 0 || ret > remaining)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0' || type == LOG_TYPE_ERRNO)
Log_Append(p, remaining, ": ", 2);
}
// in case of error print the errno message otherwise print our message
if (type == LOG_TYPE_ERRNO)
{
#ifdef _GNU_SOURCE
// this is a workaround for g++ on Debian Lenny
// see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=485135
// _GNU_SOURCE is unconditionally defined so always the GNU style
// sterror_r() is used, which is broken
char* err = strerror_r(errno, p, remaining - 1);
if (err)
{
ret = strlen(err);
if (err != p)
{
memcpy(p, err, ret);
p[ret] = 0;
}
}
else
ret = -1;
#elif _WIN32
DWORD lastError = GetLastError();
ret = snprintf(p, remaining, "Error %u: ", lastError);
if (ret < 0 || ret >= remaining)
ret = remaining - 1;
p += ret;
remaining -= ret;
if (remaining > 2)
{
ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
(FORMAT_MESSAGE_MAX_WIDTH_MASK & remaining - 2),
NULL,
lastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) p,
remaining - 2,
NULL);
}
else
ret = 0;
#else
ret = strerror_r(errno, p, remaining - 1);
if (ret >= 0)
ret = (int) strlen(p);
#endif
if (ret < 0)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0')
Log_Append(p, remaining, ": ", 2);
}
// else
{
va_start(ap, fmt);
ret = VWritef(p, remaining, fmt, ap);
va_end(ap);
if (ret < 0 || ret >= remaining)
ret = remaining - 1;
p += ret;
remaining -= ret;
}
Log_Append(p, remaining, "\n", 2);
if (autoFlush)
Log_Write(buf, maxLine - remaining, type != LOG_TYPE_TRACE && type != LOG_TYPE_DEBUG);
else
Log_Write(buf, maxLine - remaining, false);
}
<commit_msg>Fixed switchable debug log option.<commit_after>#define _XOPEN_SOURCE 600
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#define snprintf _snprintf
//#define strdup _strdup
#define strerror_r(errno, buf, buflen) strerror_s(buf, buflen, errno)
typedef unsigned __int64 uint64_t;
typedef __int64 int64_t;
#define Log_GetThreadID() (uint64_t)(GetCurrentThreadId())
#else
#include <sys/time.h>
#include <pthread.h>
#include <stdint.h>
#define Log_GetThreadID() ((uint64_t)(pthread_self()))
#endif
#include "Log.h"
#include "Formatting.h"
#include "System/Threading/Mutex.h"
#define LOG_MSG_SIZE 1024
#define LOG_OLD_EXT ".old"
static bool timestamping = false;
static bool threadedOutput = false;
static bool trace = false;
#ifdef DEBUG
static bool debug = true;
#else
static bool debug = false;
#endif
static int maxLine = LOG_MSG_SIZE;
static int target = LOG_TARGET_NOWHERE;
static FILE* logfile = NULL;
static char* logfilename = NULL;
static uint64_t maxSize = 0;
static uint64_t logFileSize = 0;
static Mutex logFileMutex;
static bool autoFlush = true;
#ifdef _WIN32
typedef char log_timestamp_t[24];
#else
typedef char log_timestamp_t[27];
#endif
static const char* GetFullTimestamp(log_timestamp_t ts)
{
if (!timestamping)
return "";
#ifdef _WIN32
SYSTEMTIME st;
GetLocalTime(&st);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%03d",
(int) st.wYear,
(int) st.wMonth,
(int) st.wDay,
(int) st.wHour,
(int) st.wMinute,
(int) st.wSecond,
(int) st.wMilliseconds);
#else
struct tm tm;
time_t sec;
struct timeval tv;
gettimeofday(&tv, NULL);
sec = (time_t) tv.tv_sec;
localtime_r(&sec, &tm);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%06lu",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
(long unsigned int) tv.tv_usec);
#endif
return ts;
}
// These functions are duplicates of the functions in FileSystem, but here they don't use logging obviously
#ifdef _WIN32
static bool Log_RenameFile(const char* src, const char* dst)
{
BOOL ret;
ret = MoveFileEx(src, dst, MOVEFILE_WRITE_THROUGH);
if (!ret)
return false;
return true;
}
static bool Log_DeleteFile(const char* filename)
{
BOOL ret;
ret = DeleteFile(filename);
if (!ret)
return false;
return true;
}
static int64_t Log_FileSize(const char* path)
{
WIN32_FILE_ATTRIBUTE_DATA attrData;
BOOL ret;
ret = GetFileAttributesEx(path, GetFileExInfoStandard, &attrData);
if (!ret)
return -1;
return ((int64_t) attrData.nFileSizeHigh) << 32 | attrData.nFileSizeLow;
}
#else
static bool Log_RenameFile(const char* src, const char* dst)
{
int ret;
ret = rename(src, dst);
if (ret < 0)
return false;
return true;
}
static bool Log_DeleteFile(const char* filename)
{
int ret;
ret = unlink(filename);
if (ret < 0)
return false;
return true;
}
int64_t FS_FileSize(const char* path)
{
int64_t ret;
struct stat buf;
ret = stat(path, &buf);
if (ret < 0)
return ret;
return buf.st_size;
}
#endif
static void Log_Append(char*& p, int& remaining, const char* s, int len)
{
if (len > remaining)
len = remaining;
if (len > 0)
memcpy(p, s, len);
p += len;
remaining -= len;
}
static void Log_Rotate()
{
char* filenameCopy;
char* oldFilename;
size_t oldFilenameSize;
char* oldOldFilename;
size_t oldOldFilenameSize;
size_t filenameLen;
size_t extLen;
fprintf(stderr, "Rotating...\n");
filenameCopy = strdup(logfilename);
filenameLen = strlen(logfilename);
extLen = sizeof(LOG_OLD_EXT) - 1;
oldFilenameSize = filenameLen + extLen + 1;
oldFilename = new char[oldFilenameSize];
snprintf(oldFilename, oldFilenameSize, "%s" LOG_OLD_EXT, logfilename);
oldOldFilenameSize = filenameLen + extLen + extLen + 1;
oldOldFilename = new char[oldOldFilenameSize];
snprintf(oldOldFilename, oldOldFilenameSize, "%s" LOG_OLD_EXT LOG_OLD_EXT, logfilename);
// delete any previously created temporary file
Log_DeleteFile(oldOldFilename);
// rename the old version to a temporary name
if (!Log_RenameFile(oldFilename, oldOldFilename))
{
Log_DeleteFile(oldFilename);
}
// close the current file
if (logfile)
{
fclose(logfile);
logfile = NULL;
}
// rename the current to old
if (!Log_RenameFile(logfilename, oldFilename))
{
// TODO:
}
// create a new file
Log_SetOutputFile(filenameCopy, true);
// delete any previously created temporary file
Log_DeleteFile(oldOldFilename);
// cleanup
free(filenameCopy);
delete[] oldFilename;
delete[] oldOldFilename;
}
static void Log_Write(const char* buf, int size, int flush)
{
if ((target & LOG_TARGET_STDOUT) == LOG_TARGET_STDOUT)
{
if (buf)
fputs(buf, stdout);
if (flush)
fflush(stdout);
}
if ((target & LOG_TARGET_STDERR) == LOG_TARGET_STDERR)
{
if (buf)
fputs(buf, stderr);
if (flush)
fflush(stderr);
}
if ((target & LOG_TARGET_FILE) == LOG_TARGET_FILE && logfile)
{
logFileMutex.Lock();
if (buf)
fputs(buf, logfile);
if (flush)
fflush(logfile);
if (maxSize > 0)
{
// we keep the previous logfile, hence the division by two
if (logFileSize + size > maxSize / 2)
{
// rotate the logfile
Log_Rotate();
}
else
{
logFileSize += size;
}
}
logFileMutex.Unlock();
}
}
void Log_SetTimestamping(bool ts)
{
timestamping = ts;
}
void Log_SetThreadedOutput(bool to)
{
threadedOutput = to;
}
bool Log_SetTrace(bool trace_)
{
bool prev = trace;
trace = trace_;
return prev;
}
bool Log_SetDebug(bool debug_)
{
bool prev = debug;
debug = debug_;
return prev;
}
bool Log_SetAutoFlush(bool autoFlush_)
{
bool prev = autoFlush;
autoFlush = autoFlush_;
return prev;
}
void Log_SetMaxLine(int maxLine_)
{
maxLine = maxLine_ > LOG_MSG_SIZE ? LOG_MSG_SIZE : maxLine_;
}
void Log_SetTarget(int target_)
{
target = target_;
}
int Log_GetTarget()
{
return target;
}
bool Log_SetOutputFile(const char* filename, bool truncate)
{
if (logfile)
{
fclose(logfile);
free(logfilename);
logfilename = NULL;
}
if (!filename)
return false;
if (truncate)
logfile = fopen(filename, "w");
else
logfile = fopen(filename, "a");
if (!logfile)
{
target &= ~LOG_TARGET_FILE;
return false;
}
logfilename = strdup(filename);
logFileSize = Log_FileSize(filename);
return true;
}
void Log_SetMaxSize(unsigned maxSizeMB)
{
maxSize = ((uint64_t)maxSizeMB) * 1000 * 1000;
}
void Log_Flush()
{
Log_Write(NULL, 0, true);
}
void Log_Shutdown()
{
if (logfilename)
{
free(logfilename);
logfilename = NULL;
}
if (logfile)
{
fclose(logfile);
logfile = NULL;
}
fflush(stdout);
fflush(stderr);
trace = false;
timestamping = false;
}
void Log(const char* file, int line, const char* func, int type, const char* fmt, ...)
{
char buf[LOG_MSG_SIZE];
int remaining;
char *p;
const char *sep;
int ret;
va_list ap;
uint64_t threadID;
// In debug mode enable ERRNO type messages
if ((type == LOG_TYPE_TRACE || type == LOG_TYPE_ERRNO) && !trace)
return;
if ((type == LOG_TYPE_DEBUG) && !debug)
return;
buf[maxLine - 1] = 0;
p = buf;
remaining = maxLine - 1;
// print timestamp
if (timestamping)
{
GetFullTimestamp(p);
p += sizeof(log_timestamp_t) - 1;
remaining -= sizeof(log_timestamp_t) - 1;
Log_Append(p, remaining, ": ", 2);
}
// print threadID
if (threadedOutput)
{
threadID = Log_GetThreadID();
ret = Writef(p, remaining, "[%U]: ", threadID);
if (ret < 0 || ret > remaining)
ret = remaining;
p += ret;
remaining -= ret;
}
// don't print filename and func in debug mode on ERRNO messages
if (file && func && (type == LOG_TYPE_TRACE || (type == LOG_TYPE_ERRNO && trace)))
{
#ifdef _WIN32
sep = strrchr(file, '/');
if (!sep)
sep = strrchr(file, '\\');
#else
sep = strrchr(file, '/');
#endif
if (sep)
file = sep + 1;
// print filename, number of line and function name
ret = snprintf(p, remaining + 1, "%s:%d:%s()", file, line, func);
if (ret < 0 || ret > remaining)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0' || type == LOG_TYPE_ERRNO)
Log_Append(p, remaining, ": ", 2);
}
// in case of error print the errno message otherwise print our message
if (type == LOG_TYPE_ERRNO)
{
#ifdef _GNU_SOURCE
// this is a workaround for g++ on Debian Lenny
// see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=485135
// _GNU_SOURCE is unconditionally defined so always the GNU style
// sterror_r() is used, which is broken
char* err = strerror_r(errno, p, remaining - 1);
if (err)
{
ret = strlen(err);
if (err != p)
{
memcpy(p, err, ret);
p[ret] = 0;
}
}
else
ret = -1;
#elif _WIN32
DWORD lastError = GetLastError();
ret = snprintf(p, remaining, "Error %u: ", lastError);
if (ret < 0 || ret >= remaining)
ret = remaining - 1;
p += ret;
remaining -= ret;
if (remaining > 2)
{
ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
(FORMAT_MESSAGE_MAX_WIDTH_MASK & remaining - 2),
NULL,
lastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) p,
remaining - 2,
NULL);
}
else
ret = 0;
#else
ret = strerror_r(errno, p, remaining - 1);
if (ret >= 0)
ret = (int) strlen(p);
#endif
if (ret < 0)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0')
Log_Append(p, remaining, ": ", 2);
}
// else
{
va_start(ap, fmt);
ret = VWritef(p, remaining, fmt, ap);
va_end(ap);
if (ret < 0 || ret >= remaining)
ret = remaining - 1;
p += ret;
remaining -= ret;
}
Log_Append(p, remaining, "\n", 2);
if (autoFlush)
Log_Write(buf, maxLine - remaining, type != LOG_TYPE_TRACE && type != LOG_TYPE_DEBUG);
else
Log_Write(buf, maxLine - remaining, false);
}
<|endoftext|> |
<commit_before>#include "Visit.h"
#include "Command.h"
#include "WebPage.h"
Visit::Visit(WebPage *page, QObject *parent) : Command(page, parent) {
connect(page, SIGNAL(pageFinished(bool)), this, SLOT(loadFinished(bool)));
}
void Visit::start(QStringList &arguments) {
QUrl requestedUrl = QUrl(arguments[0]);
page()->currentFrame()->load(QUrl(requestedUrl));
}
void Visit::loadFinished(bool success) {
QString message;
if (!success)
message = page()->failureString();
emit finished(new Response(success, message));
}
<commit_msg>Fix issue #39<commit_after>#include "Visit.h"
#include "Command.h"
#include "WebPage.h"
Visit::Visit(WebPage *page, QObject *parent) : Command(page, parent) {
connect(page, SIGNAL(pageFinished(bool)), this, SLOT(loadFinished(bool)));
}
void Visit::start(QStringList &arguments) {
QUrl requestedUrl = QUrl(arguments[0]);
page()->currentFrame()->load(QUrl(requestedUrl));
}
void Visit::loadFinished(bool success) {
QString message;
if (!success)
message = page()->failureString();
disconnect(page(), SIGNAL(pageFinished(bool)), this, SLOT(loadFinished(bool)));
emit finished(new Response(success, message));
}
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <librealsense/rs.hpp>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/distortion_models.h>
#include <std_msgs/Header.h>
#include <ros/ros.h>
#include <iostream>
#include <algorithm>
void rsIntrinsics2CameraInfo(const rs::intrinsics& intrinsics, sensor_msgs::CameraInfo& cam_info)
{
cam_info.width = intrinsics.width;
cam_info.height = intrinsics.height;
cam_info.distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;
cam_info.D.resize(5);
cam_info.D[0] = intrinsics.coeffs[0];
cam_info.D[1] = intrinsics.coeffs[1];
cam_info.D[2] = intrinsics.coeffs[2];
cam_info.D[3] = intrinsics.coeffs[3];
cam_info.D[4] = intrinsics.coeffs[4];
cam_info.K[0] = intrinsics.fx; cam_info.K[1] = 0; cam_info.K[2] = intrinsics.ppx;
cam_info.K[3] = 0; cam_info.K[4] = intrinsics.fy; cam_info.K[5] = intrinsics.ppy;
cam_info.K[6] = 0; cam_info.K[7] = 0; cam_info.K[8] = 1;
cam_info.binning_x = 1;
cam_info.binning_y = 1;
cam_info.roi.x_offset = 0;
cam_info.roi.y_offset = 0;
cam_info.roi.width = cam_info.width;
cam_info.roi.height = cam_info.height;
cam_info.roi.do_rectify = false;
}
int main(int argc, char * argv[]) try
{
ros::init(argc, argv, "kcf_tracker");
ros::NodeHandle nh;
int32_t skip_frame_num;
ros::param::param<int32_t>("~skip_frame_num", skip_frame_num, 5);
rs::context ctx;
if(ctx.get_device_count() == 0) throw std::runtime_error("No device detected. Is it plugged in?");
// Enumerate all devices
std::vector<rs::device *> devices;
std::vector<ros::Publisher> depth_pubs(ctx.get_device_count());
std::vector<ros::Publisher> rgb_pubs(ctx.get_device_count());
std::vector<ros::Publisher> depth_info_pubs(ctx.get_device_count());
std::vector<ros::Publisher> rgb_info_pubs(ctx.get_device_count());
std::vector<sensor_msgs::CameraInfo> depth_infos(ctx.get_device_count());
std::vector<sensor_msgs::CameraInfo> rgb_infos(ctx.get_device_count());
for(int i = 0; i < ctx.get_device_count(); ++i)
{
devices.push_back(ctx.get_device(i));
depth_pubs[i] = nh.advertise<sensor_msgs::Image>("camera" + std::to_string(i) +
"/depth/image_raw", 1, true);
rgb_pubs[i] = nh.advertise<sensor_msgs::Image>("camera" + std::to_string(i) +
"/rgb/image_raw", 1, true);
depth_info_pubs[i] = nh.advertise<sensor_msgs::CameraInfo>("camera" +
std::to_string(i) + "/depth/camera_info", 1, true);
rgb_info_pubs[i] = nh.advertise<sensor_msgs::CameraInfo>("camera" +
std::to_string(i) + "/rgb/camera_info", 1, true);
}
// Configure and start our devices
int i = 0;
for(auto dev : devices)
{
ROS_INFO("Starting %s...", dev->get_name());
dev->enable_stream(rs::stream::depth, 640, 480, rs::format::z16, 30);
dev->enable_stream(rs::stream::color, 1920, 1080, rs::format::bgr8, 30);
rs::intrinsics depth_intrinsics = dev->get_stream_intrinsics(rs::stream::depth);
rs::intrinsics color_intrinsics = dev->get_stream_intrinsics(rs::stream::color);
rsIntrinsics2CameraInfo(depth_intrinsics, depth_infos[i]);
rsIntrinsics2CameraInfo(color_intrinsics, rgb_infos[i]);
dev->start();
ROS_INFO("done.");
++i;
}
// Depth and color
cv::Mat depth_img(cv::Size(640, 480), CV_16UC1);
cv::Mat rgb_img(cv::Size(1920, 1080), CV_8UC3);
cv_bridge::CvImage cv_img;
std_msgs::Header header;
int skip_count = 0;
while (ros::ok())
{
int i = 0;
if (skip_count == skip_frame_num)
{
skip_count = 0;
}
else
{
++skip_count;
}
for (auto dev : devices)
{
header.stamp = ros::Time::now();
dev->wait_for_frames();
if (skip_count != skip_frame_num)
{
continue;
}
const uint16_t* depth_frame = reinterpret_cast<const uint16_t*>(
dev->get_frame_data(rs::stream::depth));
memcpy(depth_img.data, depth_frame, depth_img.cols*depth_img.rows*sizeof(uint16_t));
header.frame_id = "depth_frame";
cv_img.header = header;
cv_img.encoding = "mono16";
cv_img.image = depth_img;
depth_pubs[i].publish(cv_img.toImageMsg());
depth_infos[i].header = header;
depth_info_pubs[i].publish(depth_infos[i]);
const uint8_t* rgb_frame = reinterpret_cast<const uint8_t*>(
dev->get_frame_data(rs::stream::color));
memcpy(rgb_img.data, rgb_frame, rgb_img.cols*rgb_img.rows*sizeof(uint8_t)*rgb_img.channels());
header.frame_id = "rgb_frame";
cv_img.header = header;
cv_img.encoding = "bgr8";
cv_img.image = rgb_img;
rgb_pubs[i].publish(cv_img);
rgb_infos[i].header = header;
rgb_info_pubs[i].publish(rgb_infos[i]);
++i;
}
++header.seq;
}
return EXIT_SUCCESS;
}
catch(const rs::error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "("
<< e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(const std::exception & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
<commit_msg>realsense pointcloud publications<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <librealsense/rs.hpp>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/distortion_models.h>
#include <std_msgs/Header.h>
#include <ros/ros.h>
#include <iostream>
#include <algorithm>
void rsIntrinsics2CameraInfo(const rs::intrinsics& intrinsics, sensor_msgs::CameraInfo& cam_info)
{
cam_info.width = intrinsics.width;
cam_info.height = intrinsics.height;
cam_info.distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;
cam_info.D.resize(5);
cam_info.D[0] = intrinsics.coeffs[0];
cam_info.D[1] = intrinsics.coeffs[1];
cam_info.D[2] = intrinsics.coeffs[2];
cam_info.D[3] = intrinsics.coeffs[3];
cam_info.D[4] = intrinsics.coeffs[4];
cam_info.K[0] = intrinsics.fx; cam_info.K[1] = 0; cam_info.K[2] = intrinsics.ppx;
cam_info.K[3] = 0; cam_info.K[4] = intrinsics.fy; cam_info.K[5] = intrinsics.ppy;
cam_info.K[6] = 0; cam_info.K[7] = 0; cam_info.K[8] = 1;
cam_info.binning_x = 1;
cam_info.binning_y = 1;
cam_info.roi.x_offset = 0;
cam_info.roi.y_offset = 0;
cam_info.roi.width = cam_info.width;
cam_info.roi.height = cam_info.height;
cam_info.roi.do_rectify = false;
}
void publishPoints(const std_msgs::Header& header, const cv::Mat& depth_img,
const ros::Publisher& publisher, rs::intrinsics& depth_intrinsics)
{
sensor_msgs::PointCloud points_msg;
points_msg.header = header;
for(int dy = 0; dy < depth_intrinsics.height; ++dy)
{
for(int dx = 0; dx < depth_intrinsics.width; ++dx)
{
// Retrieve the 16-bit depth value and map it into a depth in meters
uint16_t depth_value = depth_img.at<uint16_t>(dy, dx);
float depth_in_meters = depth_value * 1000;
// Skip over pixels with a depth value of zero, which is used to indicate no data
if(depth_value == 0) continue;
// Map from pixel coordinates in the depth image to pixel coordinates in the color image
rs::float2 depth_pixel = {(float)dx, (float)dy};
rs::float3 depth_point = depth_intrinsics.deproject(depth_pixel, depth_in_meters);
geometry_msgs::Point32 point;
point.x = depth_point.x;
point.y = depth_point.y;
point.z = depth_point.z;
points_msg.points.push_back(point);
}
}
publisher.publish(points_msg);
}
int main(int argc, char * argv[]) try
{
ros::init(argc, argv, "realsense_multi_cam");
ros::NodeHandle nh;
int32_t skip_frame_num;
bool pub_points;
ros::param::param<int32_t>("~skip_frame_num", skip_frame_num, 5);
ros::param::param<bool>("~pub_points", pub_points, false);
int32_t rgb_width, rgb_height, depth_width, depth_height;
ros::param::param<int32_t>("~rgb_width", rgb_width, 1920);
ros::param::param<int32_t>("~rgb_height", rgb_height, 1080);
ros::param::param<int32_t>("~depth_width", depth_width, 640);
ros::param::param<int32_t>("~depth_height", depth_height, 480);
rs::context ctx;
if(ctx.get_device_count() == 0) throw std::runtime_error("No device detected. Is it plugged in?");
// Enumerate all devices
std::vector<rs::device *> devices;
std::vector<ros::Publisher> depth_pubs(ctx.get_device_count());
std::vector<ros::Publisher> rgb_pubs(ctx.get_device_count());
std::vector<ros::Publisher> depth_info_pubs(ctx.get_device_count());
std::vector<ros::Publisher> rgb_info_pubs(ctx.get_device_count());
std::vector<ros::Publisher> point_pubs(ctx.get_device_count());
std::vector<sensor_msgs::CameraInfo> depth_infos(ctx.get_device_count());
std::vector<sensor_msgs::CameraInfo> rgb_infos(ctx.get_device_count());
for(int i = 0; i < ctx.get_device_count(); ++i)
{
devices.push_back(ctx.get_device(i));
depth_pubs[i] = nh.advertise<sensor_msgs::Image>("camera" + std::to_string(i) +
"/depth/image_raw", 1, true);
rgb_pubs[i] = nh.advertise<sensor_msgs::Image>("camera" + std::to_string(i) +
"/rgb/image_raw", 1, true);
depth_info_pubs[i] = nh.advertise<sensor_msgs::CameraInfo>("camera" +
std::to_string(i) + "/depth/camera_info", 1, true);
rgb_info_pubs[i] = nh.advertise<sensor_msgs::CameraInfo>("camera" +
std::to_string(i) + "/rgb/camera_info", 1, true);
point_pubs[i] = nh.advertise<sensor_msgs::PointCloud>("camera" +
std::to_string(i) + "/depth/points", 1, true);
}
// Configure and start our devices
int i = 0;
for(auto dev : devices)
{
ROS_INFO("Starting %s...", dev->get_name());
dev->enable_stream(rs::stream::depth, depth_width, depth_height, rs::format::z16, 30);
dev->enable_stream(rs::stream::color, rgb_width, rgb_height, rs::format::bgr8, 30);
rs::intrinsics depth_intrinsics = dev->get_stream_intrinsics(rs::stream::depth);
rs::intrinsics color_intrinsics = dev->get_stream_intrinsics(rs::stream::color);
rsIntrinsics2CameraInfo(depth_intrinsics, depth_infos[i]);
rsIntrinsics2CameraInfo(color_intrinsics, rgb_infos[i]);
dev->start();
ROS_INFO("done.");
++i;
}
// Depth and color
cv::Mat depth_img(cv::Size(depth_width, depth_height), CV_16UC1);
cv::Mat rgb_img(cv::Size(rgb_width, rgb_height), CV_8UC3);
cv_bridge::CvImage cv_img;
std_msgs::Header header;
int skip_count = 0;
while (ros::ok())
{
int i = 0;
if (skip_count == skip_frame_num)
{
skip_count = 0;
}
else
{
++skip_count;
}
for (auto dev : devices)
{
header.stamp = ros::Time::now();
dev->wait_for_frames();
if (skip_count != skip_frame_num)
{
continue;
}
const uint16_t* depth_frame = reinterpret_cast<const uint16_t*>(
dev->get_frame_data(rs::stream::depth));
memcpy(depth_img.data, depth_frame, depth_img.cols*depth_img.rows*sizeof(uint16_t));
header.frame_id = "depth_frame" + std::to_string(i);
cv_img.header = header;
cv_img.encoding = "mono16";
cv_img.image = depth_img;
depth_pubs[i].publish(cv_img.toImageMsg());
depth_infos[i].header = header;
depth_info_pubs[i].publish(depth_infos[i]);
if (pub_points)
{
rs::intrinsics depth_intrinsics = dev->get_stream_intrinsics(rs::stream::depth);
publishPoints(header, depth_img, point_pubs[i], depth_intrinsics);
}
const uint8_t* rgb_frame = reinterpret_cast<const uint8_t*>(
dev->get_frame_data(rs::stream::color));
memcpy(rgb_img.data, rgb_frame, rgb_img.cols*rgb_img.rows*sizeof(uint8_t)*rgb_img.channels());
header.frame_id = "rgb_frame" + std::to_string(i);
cv_img.header = header;
cv_img.encoding = "bgr8";
cv_img.image = rgb_img;
rgb_pubs[i].publish(cv_img);
rgb_infos[i].header = header;
rgb_info_pubs[i].publish(rgb_infos[i]);
++i;
}
++header.seq;
}
return EXIT_SUCCESS;
}
catch(const rs::error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "("
<< e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(const std::exception & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include "TextureAtlas.h"
TextureAtlas::TextureAtlas(const std::string& textureFileName)
{
sf::Image i;
if (!i.loadFromFile("Res/Textures/" + textureFileName + ".png"))
{
throw std::runtime_error("Unable to open image: " + textureFileName);
}
loadFromImage(i);
m_imageSize = 256;
m_individualTextureSize = 16;
}
std::array<GLfloat, 8> TextureAtlas::getTexture(const sf::Vector2i& coords)
{
static const GLfloat TEX_PER_ROW = (GLfloat)m_imageSize / (GLfloat)m_individualTextureSize;
static const GLfloat INDV_TEX_SIZE = 1.0f / TEX_PER_ROW;
static const GLfloat PIXEL_SIZE = 1.0f / (float)m_imageSize;
GLfloat xMin = (coords.x * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat yMin = (coords.y * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat xMax = (xMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
GLfloat yMax = (yMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
return
{
xMax, yMax,
xMin, yMax,
xMin, yMin,
xMax, yMin
};
}
<commit_msg>Fix to compile on MacOSX<commit_after>#include "TextureAtlas.h"
#include <array>
TextureAtlas::TextureAtlas(const std::string& textureFileName)
{
sf::Image i;
if (!i.loadFromFile("Res/Textures/" + textureFileName + ".png"))
{
throw std::runtime_error("Unable to open image: " + textureFileName);
}
loadFromImage(i);
m_imageSize = 256;
m_individualTextureSize = 16;
}
std::array<GLfloat, 8> TextureAtlas::getTexture(const sf::Vector2i& coords)
{
static const GLfloat TEX_PER_ROW = (GLfloat)m_imageSize / (GLfloat)m_individualTextureSize;
static const GLfloat INDV_TEX_SIZE = 1.0f / TEX_PER_ROW;
static const GLfloat PIXEL_SIZE = 1.0f / (float)m_imageSize;
GLfloat xMin = (coords.x * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat yMin = (coords.y * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat xMax = (xMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
GLfloat yMax = (yMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
return
{
xMax, yMax,
xMin, yMax,
xMin, yMin,
xMax, yMin
};
}
<|endoftext|> |
<commit_before>#include "tocman.h"
#include <poppler-qt4.h>
TocManager::TocManager(const QString &path, QObject *parent)
: QObject(parent),
_path(path),
_coordinator(path, this) { }
TocManager::~TocManager() { }
void TocManager::refresh() {
Poppler::Document *doc = Poppler::Document::load(_path);
if (doc) {
QList<Choice> choices;
QDomDocument *toc = doc->toc();
if (toc) {
QDomNode child = toc->documentElement();
while (!child.isNull()) {
if (child.isElement()) {
QDomElement el = child.toElement();
QString destName = el.attribute("DestinationName", "");
Poppler::LinkDestination *dest = doc->linkDestination(destName);
QUrl url("file:" + _path + "#page:" + QString::number(dest->pageNumber()));
choices << Choice(el.nodeName(), url.toString());
delete dest;
}
child = child.nextSibling();
}
delete toc;
} else {
qDebug() << "NO TOC";
}
emit contentsChanged(choices);
}
delete doc;
}
void TocManager::activate(Choice c) {
_coordinator.openItem("runcible-view-pdf", QUrl(c.id()));
}
<commit_msg>PDF TOC is now hierarchical.<commit_after>#include "tocman.h"
#include <poppler-qt4.h>
TocManager::TocManager(const QString &path, QObject *parent)
: QObject(parent),
_path(path),
_coordinator(path, this) { }
TocManager::~TocManager() { }
static void copyToc(const QUrl &docUrl, Poppler::Document *doc, QDomNode node,
QList<Choice> &choices, int indent) {
while (!node.isNull()) {
if (node.isElement()) {
QDomElement el = node.toElement();
QString destName = el.attribute("DestinationName", QString());
if (!destName.isNull()) {
Poppler::LinkDestination *dest = doc->linkDestination(destName);
QUrl refUrl(docUrl);
refUrl.setFragment("page:" + QString::number(dest->pageNumber()));
delete dest;
QString displayName(QString(indent * 2, ' ') + el.nodeName());
choices << Choice(displayName, refUrl.toString());
}
}
if (node.hasChildNodes()) {
copyToc(docUrl, doc, node.firstChild(), choices, indent + 1);
}
node = node.nextSibling();
}
}
void TocManager::refresh() {
Poppler::Document *doc = Poppler::Document::load(_path);
if (doc) {
QList<Choice> choices;
QUrl docUrl("file:" + _path);
QDomDocument *toc = doc->toc();
if (toc) {
QDomNode child = toc->documentElement();
copyToc(docUrl, doc, child, choices, 0);
/*
while (!child.isNull()) {
if (child.isElement()) {
QDomElement el = child.toElement();
QString destName = el.attribute("DestinationName", "");
Poppler::LinkDestination *dest = doc->linkDestination(destName);
QUrl url("file:" + _path + "#page:" + QString::number(dest->pageNumber()));
choices << Choice(el.nodeName(), url.toString());
delete dest;
}
child = child.nextSibling();
}
*/
delete toc;
} else {
qDebug() << "NO TOC";
}
emit contentsChanged(choices);
}
delete doc;
}
void TocManager::activate(Choice c) {
qDebug() << c.id();
_coordinator.openItem("runcible-view-pdf", QUrl(c.id()));
}
<|endoftext|> |
<commit_before>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "infill.h"
#include "LayerPlan.h"
#include "TopSurface.h"
namespace cura
{
TopSurface::TopSurface()
{
//Do nothing. Areas stays empty.
}
TopSurface::TopSurface(SliceMeshStorage& mesh, size_t layer_number)
{
//The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.
Polygons mesh_above;
if (layer_number < mesh.layers.size() - 1)
{
mesh_above = mesh.layers[layer_number + 1].getOutlines();
} //If this is the top-most layer, mesh_above stays empty.
areas = mesh.layers[layer_number].getOutlines().difference(mesh_above);
}
bool TopSurface::ironing(const SliceMeshStorage& mesh, const GCodePathConfig& line_config, LayerPlan& layer)
{
if (areas.empty())
{
return false; //Nothing to do.
}
//Generate the lines to cover the surface.
const EFillMethod pattern = mesh.getSettingAsFillMethod("ironing_pattern");
const coord_t line_spacing = mesh.getSettingInMicrons("ironing_line_spacing");
const coord_t outline_offset = -mesh.getSettingInMicrons("ironing_inset");
const coord_t line_width = line_config.getLineWidth();
const double direction = mesh.skin_angles[layer.getLayerNr() % mesh.skin_angles.size()] + 90.0; //Always perpendicular to the skin lines.
constexpr coord_t infill_overlap = 0;
constexpr coord_t shift = 0;
Infill infill_generator(pattern, areas, outline_offset, line_width, line_spacing, infill_overlap, direction, layer.z - 10, shift);
Polygons ironing_polygons;
Polygons ironing_lines;
infill_generator.generate(ironing_polygons, ironing_lines);
//Add the lines as travel moves to the layer plan.
bool added = false;
const float ironing_flow = mesh.getSettingAsRatio("ironing_flow");
if (!ironing_polygons.empty())
{
layer.addPolygonsByOptimizer(ironing_polygons, &line_config, nullptr, EZSeamType::SHORTEST, Point(0, 0), 0, false, ironing_flow);
added = true;
}
if (!ironing_lines.empty())
{
layer.addLinesByOptimizer(ironing_lines, &line_config, SpaceFillType::PolyLines, 0, ironing_flow);
added = true;
}
return added;
}
}<commit_msg>Start ironing at corner perpendicular to ironing lines<commit_after>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "infill.h"
#include "LayerPlan.h"
#include "TopSurface.h"
namespace cura
{
TopSurface::TopSurface()
{
//Do nothing. Areas stays empty.
}
TopSurface::TopSurface(SliceMeshStorage& mesh, size_t layer_number)
{
//The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.
Polygons mesh_above;
if (layer_number < mesh.layers.size() - 1)
{
mesh_above = mesh.layers[layer_number + 1].getOutlines();
} //If this is the top-most layer, mesh_above stays empty.
areas = mesh.layers[layer_number].getOutlines().difference(mesh_above);
}
bool TopSurface::ironing(const SliceMeshStorage& mesh, const GCodePathConfig& line_config, LayerPlan& layer)
{
if (areas.empty())
{
return false; //Nothing to do.
}
//Generate the lines to cover the surface.
const EFillMethod pattern = mesh.getSettingAsFillMethod("ironing_pattern");
const coord_t line_spacing = mesh.getSettingInMicrons("ironing_line_spacing");
const coord_t outline_offset = -mesh.getSettingInMicrons("ironing_inset");
const coord_t line_width = line_config.getLineWidth();
const double direction = mesh.skin_angles[layer.getLayerNr() % mesh.skin_angles.size()] + 90.0; //Always perpendicular to the skin lines.
constexpr coord_t infill_overlap = 0;
constexpr coord_t shift = 0;
Infill infill_generator(pattern, areas, outline_offset, line_width, line_spacing, infill_overlap, direction, layer.z - 10, shift);
Polygons ironing_polygons;
Polygons ironing_lines;
infill_generator.generate(ironing_polygons, ironing_lines);
if (pattern == EFillMethod::LINES || pattern == EFillMethod::ZIG_ZAG)
{
//Move to a corner of the area that is perpendicular to the ironing lines, to reduce the number of seams.
const AABB bounding_box(areas);
PointMatrix rotate(-direction + 90);
const Point center = bounding_box.getMiddle();
const Point far_away = rotate.apply(Point(0, vSize(bounding_box.max - center) * 100)); //Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre.
//Two options to start, both perpendicular to the ironing lines. Which is closer?
const Point front_side = PolygonUtils::findNearestVert(center + far_away, areas).p();
const Point back_side = PolygonUtils::findNearestVert(center - far_away, areas).p();
if (vSize2(layer.getLastPosition() - front_side) < vSize2(layer.getLastPosition() - back_side))
{
layer.addTravel(front_side);
}
else
{
layer.addTravel(back_side);
}
}
//Add the lines as travel moves to the layer plan.
bool added = false;
const float ironing_flow = mesh.getSettingAsRatio("ironing_flow");
if (!ironing_polygons.empty())
{
layer.addPolygonsByOptimizer(ironing_polygons, &line_config, nullptr, EZSeamType::SHORTEST, Point(0, 0), 0, false, ironing_flow);
added = true;
}
if (!ironing_lines.empty())
{
layer.addLinesByOptimizer(ironing_lines, &line_config, SpaceFillType::PolyLines, 0, ironing_flow);
added = true;
}
return added;
}
}<|endoftext|> |
<commit_before>/*!
* @file Liepa.cpp
* @brief Implementation of Liepa's subdivision scheme
*/
#include <cmath>
#include "Liepa.h"
namespace psalm
{
/*!
* Sets default values for Liepa subdivision.
*/
Liepa::Liepa()
{
alpha = sqrt(2);
}
/*!
* Sets current value of density parameter for the algorithm.
*
* @param alpha New value for density parameter
*/
void Liepa::set_alpha(double alpha)
{
this->alpha = alpha;
}
/*!
* @returns Current value of density parameter for the algorithm.
*/
double Liepa::get_alpha()
{
return(alpha);
}
/*!
* Applies Liepa's subdivision scheme to the given mesh. The mesh will be
* irreversibly _changed_ by this function.
*
* @param input_mesh Mesh on which the algorithm is applied
* @return true on success, else false
*/
bool Liepa::apply_to(mesh& input_mesh)
{
/*
Compute scale attribute as the average length of the edges
adjacent to a vertex.
ASSUMPTION: Mesh consists of a single triangulated hole, i.e.
_all_ vertices are boundary vertices.
*/
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
vertex* v = input_mesh.get_vertex(i);
size_t n = v->valency();
double attribute = 0.0;
for(size_t i = 0; i < n; i++)
attribute += v->get_edge(i)->calc_length()/static_cast<double>(n);
v->set_scale_attribute(attribute);
}
bool created_new_triangle;
do
{
// if no new triangle has been created, the algorithm
// terminates
created_new_triangle = false;
// Need to store the number of faces here because new faces
// might be created within the for-loop below. These must _not_
// be considered in the same iteration.
size_t num_faces = input_mesh.num_faces();
// Compute scale attribute for each face of the mesh
for(size_t i = 0; i < num_faces; i++)
{
face* f = input_mesh.get_face(i);
if(f->num_edges() != 3)
{
std::cerr << "psalm: Input mesh contains non-triangular face. Liepa's subdivision scheme is not applicable.\n";
return(false);
}
vertex* vertices[3];
vertices[0] = f->get_vertex(0);
vertices[1] = f->get_vertex(1);
vertices[2] = f->get_vertex(2);
// Compute centroid and scale attribute. If the scale
// attribute test fails, replace the triangle.
v3ctor centroid_pos;
double centroid_scale_attribute = 0.0;
for(size_t j = 0; j < 3; j++)
{
centroid_pos += vertices[j]->get_position()/3.0;
centroid_scale_attribute += vertices[j]->get_scale_attribute()/3.0;
}
size_t tests_failed = 0;
for(size_t j = 0; j < 3; j++)
{
double scaled_distance = alpha*(centroid_pos - vertices[j]->get_position()).length();
if( scaled_distance > centroid_scale_attribute &&
scaled_distance > vertices[j]->get_scale_attribute())
{
// We will replace the triangle only if
// _all_ three tests failed
tests_failed++;
}
}
// Replace old triangle with three smaller triangles
if(tests_failed == 3)
{
created_new_triangle = true;
vertex* centroid_vertex = input_mesh.add_vertex(centroid_pos);
centroid_vertex->set_scale_attribute(centroid_scale_attribute);
// Remove old face and replace it by three new
// faces. Calling remove_face() will ensure
// that the edges are updated correctly.
input_mesh.remove_face(f);
delete f;
face* new_face1 = input_mesh.add_face(vertices[0], vertices[1], centroid_vertex);
face* new_face2 = input_mesh.add_face(centroid_vertex, vertices[1], vertices[2]);
face* new_face3 = input_mesh.add_face(vertices[0], centroid_vertex, vertices[2]);
if(!new_face1 || !new_face2 || !new_face3)
{
std::cerr << "psalm: Error: Liepa::apply_to(): Unable to add new face\n";
return(false);
}
num_faces--;
i--;
// Relax edges afterwards to maintain
// Delaunay-like mesh
input_mesh.relax_edge(new_face1->get_edge(0).e);
input_mesh.relax_edge(new_face2->get_edge(1).e);
input_mesh.relax_edge(new_face3->get_edge(2).e);
}
}
if(!created_new_triangle)
return(true);
// Relax interior edges
bool relaxed_edge;
do
{
relaxed_edge = false;
for(size_t i = 0; i < input_mesh.num_edges(); i++)
{
if(input_mesh.relax_edge(input_mesh.get_edge(i)))
relaxed_edge = true;
}
}
while(relaxed_edge);
/*
XXX: This might lead to wrong results...
// Calculate new scaling attributes. TODO: This should become a
// function.
for(std::vector<vertex*>::iterator v_it = V.begin(); v_it < V.end(); v_it++)
{
vertex* v = *v_it;
size_t n = v->valency();
if(!v->is_on_boundary())
continue;
double attribute = 0.0;
for(size_t i = 0; i < n; i++)
attribute += v->get_edge(i)->calc_length()/static_cast<double>(n);
v->set_scale_attribute(attribute);
}
*/
if(!relaxed_edge)
continue;
}
while(created_new_triangle);
return(true);
}
} // end of namespace "psalm"
<commit_msg>Temporary change in `Liepa` subdivision algorithm<commit_after>/*!
* @file Liepa.cpp
* @brief Implementation of Liepa's subdivision scheme
*/
#include <cmath>
#include "Liepa.h"
namespace psalm
{
/*!
* Sets default values for Liepa subdivision.
*/
Liepa::Liepa()
{
alpha = sqrt(2);
}
/*!
* Sets current value of density parameter for the algorithm.
*
* @param alpha New value for density parameter
*/
void Liepa::set_alpha(double alpha)
{
this->alpha = alpha;
}
/*!
* @returns Current value of density parameter for the algorithm.
*/
double Liepa::get_alpha()
{
return(alpha);
}
/*!
* Applies Liepa's subdivision scheme to the given mesh. The mesh will be
* irreversibly _changed_ by this function.
*
* @param input_mesh Mesh on which the algorithm is applied
* @return true on success, else false
*/
bool Liepa::apply_to(mesh& input_mesh)
{
/*
Compute scale attribute as the average length of the edges
adjacent to a vertex.
ASSUMPTION: Mesh consists of a single triangulated hole, i.e.
_all_ vertices are boundary vertices.
*/
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
vertex* v = input_mesh.get_vertex(i);
size_t n = v->valency();
double attribute = 0.0;
for(size_t i = 0; i < n; i++)
attribute += v->get_edge(i)->calc_length()/static_cast<double>(n);
v->set_scale_attribute(attribute);
}
bool created_new_triangle;
do
{
// if no new triangle has been created, the algorithm
// terminates
created_new_triangle = false;
// Need to store the number of faces here because new faces
// might be created within the for-loop below. These must _not_
// be considered in the same iteration.
size_t num_faces = input_mesh.num_faces();
// Compute scale attribute for each face of the mesh
for(size_t i = 0; i < num_faces; i++)
{
face* f = input_mesh.get_face(i);
if(f->num_edges() != 3)
{
std::cerr << "psalm: Input mesh contains non-triangular face. Liepa's subdivision scheme is not applicable.\n";
return(false);
}
vertex* vertices[3];
vertices[0] = f->get_vertex(0);
vertices[1] = f->get_vertex(1);
vertices[2] = f->get_vertex(2);
// Compute centroid and scale attribute. If the scale
// attribute test fails, replace the triangle.
v3ctor centroid_pos;
double centroid_scale_attribute = 0.0;
for(size_t j = 0; j < 3; j++)
{
centroid_pos += vertices[j]->get_position()/3.0;
centroid_scale_attribute += vertices[j]->get_scale_attribute()/3.0;
}
size_t tests_failed = 0;
for(size_t j = 0; j < 3; j++)
{
double scaled_distance = alpha*(centroid_pos - vertices[j]->get_position()).length();
if( scaled_distance > centroid_scale_attribute &&
scaled_distance > vertices[j]->get_scale_attribute())
{
// We will replace the triangle only if
// _all_ three tests failed
tests_failed++;
}
}
// Replace old triangle with three smaller triangles
if(tests_failed == 3)
{
created_new_triangle = true;
vertex* centroid_vertex = input_mesh.add_vertex(centroid_pos);
centroid_vertex->set_scale_attribute(centroid_scale_attribute);
// Remove old face and replace it by three new
// faces. Calling remove_face() will ensure
// that the edges are updated correctly.
input_mesh.remove_face(f);
delete f;
face* new_face1 = input_mesh.add_face(vertices[0], vertices[1], centroid_vertex);
face* new_face2 = input_mesh.add_face(centroid_vertex, vertices[1], vertices[2]);
face* new_face3 = input_mesh.add_face(vertices[0], centroid_vertex, vertices[2]);
if(!new_face1 || !new_face2 || !new_face3)
{
std::cerr << "psalm: Error: Liepa::apply_to(): Unable to add new face\n";
return(false);
}
num_faces--;
i--;
// Relax edges afterwards to maintain
// Delaunay-like mesh
input_mesh.relax_edge(new_face1->get_edge(0).e);
input_mesh.relax_edge(new_face2->get_edge(1).e);
input_mesh.relax_edge(new_face3->get_edge(2).e);
}
}
if(!created_new_triangle)
return(true);
// Relax interior edges
bool relaxed_edge;
do
{
relaxed_edge = false;
for(size_t i = 0; i < input_mesh.num_edges(); i++)
{
if(input_mesh.relax_edge(input_mesh.get_edge(i)))
relaxed_edge = true;
}
}
while(relaxed_edge);
/*
XXX: This might lead to wrong results...
// Calculate new scaling attributes. TODO: This should become a
// function.
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
vertex* v = input_mesh.get_vertex(i);
size_t n = v->valency();
if(!v->is_on_boundary())
continue;
double attribute = 0.0;
for(size_t i = 0; i < n; i++)
attribute += v->get_edge(i)->calc_length()/static_cast<double>(n);
v->set_scale_attribute(attribute);
}
*/
if(!relaxed_edge)
continue;
}
while(created_new_triangle);
return(true);
}
} // end of namespace "psalm"
<|endoftext|> |
<commit_before>#include "Crown.h"
#include "Terrain.h"
#include "FPSSystem.h"
#include "Game.h"
using namespace crown;
class WndCtrl: public KeyboardListener
{
public:
WndCtrl()
{
device()->input_manager()->register_keyboard_listener(this);
}
void key_released(const KeyboardEvent& event)
{
if (event.key == KC_ESCAPE)
{
device()->stop();
}
}
};
class MainScene: public KeyboardListener, public MouseListener
{
public:
MainScene() :
optShowSkybox(true),
optShowCrate(true),
optShowTerrain(true),
camera_active(true)
{
device()->input_manager()->register_keyboard_listener(this);
device()->input_manager()->register_mouse_listener(this);
mouseRightPressed = false;
mouseLeftPressed = false;
}
~MainScene()
{
}
void key_released(const KeyboardEvent& event)
{
if (event.key == '1')
{
terrain.PlotCircle(2, 2, 2, 2);
}
if (event.key == '2')
{
terrain.PlotCircle(4, 4, 4, 2);
}
if (event.key == '3')
{
terrain.PlotCircle(8, 8, 8, 2);
}
if (event.key == KC_F5)
{
device()->reload(grass);
}
if (event.key == KC_SPACE)
{
camera_active = !camera_active;
}
}
void button_pressed(const MouseEvent& event)
{
if (event.button == MB_LEFT)
{
mouseLeftPressed = true;
//GLint view[4];
//GLdouble proj[16], model[16];
//glGetDoublev(GL_MODELVIEW_MATRIX, model);
//glGetDoublev(GL_PROJECTION_MATRIX, proj);
//glGetIntegerv(GL_VIEWPORT, view);
//int x = event.x;
//int y = event.y;
// Adjust y wndCoord
//y = (625 - y);
//double sX, sY, sZ;
//double eX, eY, eZ;
//gluUnProject(x, y, 0.0f, model, proj, view, &sX, &sY, &sZ);
//gluUnProject(x, y, 1.0f, model, proj, view, &eX, &eY, &eZ);
//Vec3 dir = Vec3(eX, eY, eZ) - Vec3(sX, sY, sZ);
//dir.normalize();
//ray.direction = dir;
}
else if (event.button == MB_RIGHT)
{
mouseRightPressed = true;
}
wheel += event.wheel * 0.25;
}
void button_released(const MouseEvent& event)
{
if (event.button == MB_LEFT)
{
mouseLeftPressed = false;
}
else if (event.button == MB_RIGHT)
{
mouseRightPressed = false;
}
wheel -= event.wheel * 0.25;
}
void on_load()
{
crown::Renderer* renderer = crown::device()->renderer();
Vec3 start = Vec3(0.0f, 10.0f, 0.0f);
// Add a movable camera
cam = new Camera(start, 90.0f, 1.6f);
system = new FPSSystem(cam, 10.0f, 2.5f);
// Add a skybox
skybox = new Skybox(Vec3::ZERO, true);
terrain.CreateTerrain(64, 64, 1, 0.0f);
terrain.PlotCircle(4, 4, 4, 2);
terrain.UpdateVertexBuffer(true);
red_north = device()->load("textures/red_north.tga");
red_south = device()->load("textures/red_south.tga");
red_east = device()->load("textures/red_east.tga");
red_west = device()->load("textures/red_west.tga");
red_up = device()->load("textures/red_up.tga");
red_down = device()->load("textures/red_down.tga");
grass = device()->load("textures/grass.tga");
device()->resource_manager()->flush();
TextureResource* grass_texture = (TextureResource*)device()->data(grass);
grass_id = device()->renderer()->load_texture(grass_texture);
}
void on_unload()
{
device()->unload(grass);
device()->unload(red_north);
device()->unload(red_south);
device()->unload(red_east);
device()->unload(red_west);
device()->unload(red_up);
device()->unload(red_down);
}
void render(float dt)
{
Renderer* renderer = device()->renderer();
renderer->set_clear_color(Color4::LIGHTBLUE);
if (camera_active)
{
system->set_view_by_cursor();
}
system->update(dt);
renderer->set_lighting(false);
renderer->set_texturing(0, false);
if (skybox)
{
skybox->Render();
}
ray.set_origin(cam->position());
ray.set_direction(cam->look_at());
/* Render the terrain */
renderer->set_ambient_light(Color4(0.5f, 0.5f, 0.5f, 1.0f));
renderer->set_lighting(true);
renderer->set_light(0, true);
renderer->set_light_params(0, LT_DIRECTION, Vec3(0.6, 0.5f, -2.0f));
renderer->set_light_color(0, Color4::WHITE, Color4::WHITE, Color4(0.6f, 0.6f, 0.6f));
renderer->set_light_attenuation(0, 1, 0, 0);
renderer->set_material_params(Color4(0.3f, 0.3f, 0.3f), Color4(0.8f, 0.8f, 0.8f), Color4::BLACK, Color4::BLACK, 0);
renderer->set_matrix(MT_MODEL, Mat4::IDENTITY);
if (device()->is_loaded(grass))
{
renderer->set_texturing(0, true);
renderer->set_texture(0, grass_id);
}
//glColor3f(1, 1, 1);
terrain.Render();
/* Test for intersection */
Triangle tri, tri2;
real dist;
if (terrain.TraceRay(ray, tri, tri2, dist))
{
renderer->set_depth_test(false);
Vec3 intersectionPoint = ray.origin() + (ray.direction() * dist);
if (mouseLeftPressed)
{
terrain.ApplyBrush(intersectionPoint, 0.09f);
terrain.UpdateVertexBuffer(true);
}
if (mouseRightPressed)
{
terrain.ApplyBrush(intersectionPoint, -0.09f);
terrain.UpdateVertexBuffer(true);
}
renderer->set_depth_test(true);
}
}
private:
FPSSystem* system;
Camera* cam;
Skybox* skybox;
Mat4 ortho;
Terrain terrain;
// Resources
ResourceId grass;
ResourceId red_north;
ResourceId red_south;
ResourceId red_east;
ResourceId red_west;
ResourceId red_up;
ResourceId red_down;
TextureId grass_id;
bool optShowSkybox;
bool optShowCrate;
bool optShowTerrain;
bool mouseLeftPressed;
bool mouseRightPressed;
float wheel;
bool camera_active;
Ray ray;
};
class TerrainGame : public Game
{
public:
void init()
{
m_scene.on_load();
}
void shutdown()
{
m_scene.on_unload();
}
void update(float dt)
{
m_scene.render(dt);
}
private:
MainScene m_scene;
WndCtrl m_ctrl;
};
extern "C" Game* create_game()
{
return new TerrainGame;
}
extern "C" void destroy_game(Game* game)
{
delete game;
}
<commit_msg>Update terrain sample<commit_after>#include "Crown.h"
#include "Terrain.h"
#include "FPSSystem.h"
#include "Game.h"
using namespace crown;
class WndCtrl: public KeyboardListener
{
public:
WndCtrl()
{
device()->input_manager()->register_keyboard_listener(this);
}
void key_released(const KeyboardEvent& event)
{
if (event.key == KC_ESCAPE)
{
device()->stop();
}
}
};
class MainScene: public KeyboardListener, public MouseListener
{
public:
MainScene() :
optShowSkybox(true),
optShowCrate(true),
optShowTerrain(true),
camera_active(true)
{
device()->input_manager()->register_keyboard_listener(this);
device()->input_manager()->register_mouse_listener(this);
mouseRightPressed = false;
mouseLeftPressed = false;
}
~MainScene()
{
}
void key_released(const KeyboardEvent& event)
{
if (event.key == '1')
{
terrain.PlotCircle(2, 2, 2, 2);
}
if (event.key == '2')
{
terrain.PlotCircle(4, 4, 4, 2);
}
if (event.key == '3')
{
terrain.PlotCircle(8, 8, 8, 2);
}
if (event.key == KC_F5)
{
device()->reload(grass);
}
if (event.key == KC_SPACE)
{
camera_active = !camera_active;
}
}
void button_pressed(const MouseEvent& event)
{
if (event.button == MB_LEFT)
{
mouseLeftPressed = true;
//GLint view[4];
//GLdouble proj[16], model[16];
//glGetDoublev(GL_MODELVIEW_MATRIX, model);
//glGetDoublev(GL_PROJECTION_MATRIX, proj);
//glGetIntegerv(GL_VIEWPORT, view);
//int x = event.x;
//int y = event.y;
// Adjust y wndCoord
//y = (625 - y);
//double sX, sY, sZ;
//double eX, eY, eZ;
//gluUnProject(x, y, 0.0f, model, proj, view, &sX, &sY, &sZ);
//gluUnProject(x, y, 1.0f, model, proj, view, &eX, &eY, &eZ);
//Vec3 dir = Vec3(eX, eY, eZ) - Vec3(sX, sY, sZ);
//dir.normalize();
//ray.direction = dir;
}
else if (event.button == MB_RIGHT)
{
mouseRightPressed = true;
}
wheel += event.wheel * 0.25;
}
void button_released(const MouseEvent& event)
{
if (event.button == MB_LEFT)
{
mouseLeftPressed = false;
}
else if (event.button == MB_RIGHT)
{
mouseRightPressed = false;
}
wheel -= event.wheel * 0.25;
}
void on_load()
{
crown::Renderer* renderer = crown::device()->renderer();
Vec3 start = Vec3(0.0f, 10.0f, 0.0f);
// Add a movable camera
cam = new Camera(start, 90.0f, 1.6f);
system = new FPSSystem(cam, 10.0f, 2.5f);
// Add a skybox
skybox = new Skybox(Vec3::ZERO, true);
terrain.CreateTerrain(64, 64, 1, 0.0f);
terrain.PlotCircle(4, 4, 4, 2);
terrain.UpdateVertexBuffer(true);
red_north = device()->load("textures/red_north.tga");
red_south = device()->load("textures/red_south.tga");
red_east = device()->load("textures/red_east.tga");
red_west = device()->load("textures/red_west.tga");
red_up = device()->load("textures/red_up.tga");
red_down = device()->load("textures/red_down.tga");
grass = device()->load("textures/grass.tga");
device()->resource_manager()->flush();
TextureResource* grass_texture = (TextureResource*)device()->data(grass);
grass_id = device()->renderer()->load_texture(grass_texture);
}
void on_unload()
{
device()->unload(grass);
device()->unload(red_north);
device()->unload(red_south);
device()->unload(red_east);
device()->unload(red_west);
device()->unload(red_up);
device()->unload(red_down);
}
void render(float dt)
{
Renderer* renderer = device()->renderer();
renderer->set_clear_color(Color4::LIGHTBLUE);
if (camera_active)
{
system->set_view_by_cursor();
}
system->update(dt);
renderer->set_lighting(false);
renderer->set_texturing(0, false);
if (skybox)
{
skybox->Render();
}
ray.set_origin(cam->position());
ray.set_direction(cam->look_at());
/* Render the terrain */
renderer->set_ambient_light(Color4(0.5f, 0.5f, 0.5f, 1.0f));
renderer->set_lighting(true);
renderer->set_light(0, true);
renderer->set_light_params(0, LT_DIRECTION, Vec3(0.6, 0.5f, -2.0f));
renderer->set_light_color(0, Color4::WHITE, Color4::WHITE, Color4(0.6f, 0.6f, 0.6f));
renderer->set_light_attenuation(0, 1, 0, 0);
renderer->set_material_params(Color4(0.3f, 0.3f, 0.3f), Color4(0.8f, 0.8f, 0.8f), Color4::BLACK, Color4::BLACK, 0);
renderer->set_matrix(MT_MODEL, Mat4::IDENTITY);
if (device()->is_loaded(grass))
{
renderer->set_texturing(0, true);
renderer->set_texture(0, grass_id);
}
//glColor3f(1, 1, 1);
terrain.Render();
/* Test for intersection */
Triangle tri, tri2;
real dist;
if (terrain.TraceRay(ray, tri, tri2, dist))
{
renderer->set_depth_test(false);
Vec3 intersectionPoint = ray.origin() + (ray.direction() * dist);
if (mouseLeftPressed)
{
terrain.ApplyBrush(intersectionPoint, 0.09f);
terrain.UpdateVertexBuffer(true);
}
if (mouseRightPressed)
{
terrain.ApplyBrush(intersectionPoint, -0.09f);
terrain.UpdateVertexBuffer(true);
}
renderer->set_depth_test(true);
}
}
private:
FPSSystem* system;
Camera* cam;
Skybox* skybox;
Mat4 ortho;
Terrain terrain;
// Resources
ResourceId grass;
ResourceId red_north;
ResourceId red_south;
ResourceId red_east;
ResourceId red_west;
ResourceId red_up;
ResourceId red_down;
TextureId grass_id;
bool optShowSkybox;
bool optShowCrate;
bool optShowTerrain;
bool mouseLeftPressed;
bool mouseRightPressed;
float wheel;
bool camera_active;
Ray ray;
};
MainScene m_scene;
WndCtrl m_ctrl;
extern "C"
{
void init()
{
m_scene.on_load();
}
void shutdown()
{
m_scene.on_unload();
}
void frame(float dt)
{
m_scene.render(dt);
}
}
<|endoftext|> |
<commit_before>#include <boost/python.hpp>
#include <boost/cstdint.hpp>
#include <Magick++/Blob.h>
using namespace boost::python;
namespace {
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(Magick_Blob_updateNoCopy_overloads_2_3, updateNoCopy, 2, 3)
}
static void update_wrapper(Magick::Blob& blob, const std::string& data) {
blob.update(data.c_str(),data.size());
}
static std::string get_blob_data(const Magick::Blob& blob) {
const char* data = static_cast<const char*>(blob.data());
size_t length = blob.length();
return std::string(data,data+length);
}
void __Blob()
{
scope* Magick_Blob_scope = new scope(
class_< Magick::Blob >("Blob", init< >())
.def(init< const void*, size_t >())
.def(init< const Magick::Blob& >())
.def("base64", (void (Magick::Blob::*)(const std::string) )&Magick::Blob::base64)
.def("base64", (std::string (Magick::Blob::*)() )&Magick::Blob::base64)
.def("update", &update_wrapper)
.def("updateNoCopy", &Magick::Blob::updateNoCopy, Magick_Blob_updateNoCopy_overloads_2_3())
.def("length", &Magick::Blob::length)
);
enum_< Magick::Blob::Allocator >("Allocator")
.value("NewAllocator", Magick::Blob::NewAllocator)
.value("MallocAllocator", Magick::Blob::MallocAllocator)
;
delete Magick_Blob_scope;
def("get_blob_data", &get_blob_data);
}
<commit_msg>fix to avoid build error with boost-python 1.60<commit_after>#include <boost/python.hpp>
#include <boost/cstdint.hpp>
#include <Magick++/Blob.h>
using namespace boost::python;
static void updateNoCopy_wrapper(Magick::Blob& blob, std::string& data) {
// NOTE: this is valid?
std::string str;
char* w = new char[data.size() + 1];
std::copy(str.begin(), str.end(), w);
w[str.size()] = '\0';
blob.updateNoCopy(w,data.size(),Magick::Blob::NewAllocator);
}
static void update_wrapper(Magick::Blob& blob, const std::string& data) {
blob.update(data.c_str(),data.size());
}
static std::string get_blob_data(const Magick::Blob& blob) {
const char* data = static_cast<const char*>(blob.data());
size_t length = blob.length();
return std::string(data,data+length);
}
void __Blob()
{
scope* Magick_Blob_scope = new scope(
class_< Magick::Blob >("Blob", init< >())
.def("__init__", &update_wrapper) // NOTE: valid?
.def(init< const Magick::Blob& >())
.def("base64", (void (Magick::Blob::*)(const std::string) )&Magick::Blob::base64)
.def("base64", (std::string (Magick::Blob::*)() )&Magick::Blob::base64)
.def("update", &update_wrapper)
.def("updateNoCopy", &updateNoCopy_wrapper)
.def("length", &Magick::Blob::length)
);
enum_< Magick::Blob::Allocator >("Allocator")
.value("NewAllocator", Magick::Blob::NewAllocator)
.value("MallocAllocator", Magick::Blob::MallocAllocator)
;
delete Magick_Blob_scope;
def("get_blob_data", &get_blob_data);
}
<|endoftext|> |
<commit_before>#include "WebProfile.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QTimer>
#include <QDesktopServices>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "Hearthstone.h"
#include "Settings.h"
#define DEFAULT_WEBSERVICE_URL "https://trackobot.com"
WebProfile::WebProfile( QObject *parent )
: QObject( parent )
{
connect( &mNetworkManager, &QNetworkAccessManager::sslErrors, this, &WebProfile::SSLErrors );
}
bool JsonFromReply( QNetworkReply *reply, QJsonObject *object ) {
QByteArray jsonData = reply->readAll();
QJsonParseError error;
*object = QJsonDocument::fromJson( jsonData, &error ).object();
if( error.error != QJsonParseError::NoError ) {
ERR( "Couldn't parse response %s", qt2cstr( error.errorString() ) );
return false;
}
DBG( "Received %s", qt2cstr( QString( jsonData ) ) );
return true;
}
void WebProfile::EnsureAccountIsSetUp() {
if( !Settings::Instance()->HasAccount() ) {
LOG( "No account setup. Creating one for you." );
CreateAndStoreAccount();
} else {
LOG( "Account %s found", qt2cstr( Settings::Instance()->AccountUsername() ) );
}
}
void WebProfile::UploadResult( const QJsonObject& result )
{
QJsonObject params;
params[ "result" ] = result;
// Optional upload metadata to find out room for improvements
if( Settings::Instance()->DebugEnabled() ) {
METADATA( "GAME_WIDTH", Hearthstone::Instance()->Width() );
METADATA( "GAME_HEIGHT", Hearthstone::Instance()->Height() );
METADATA( "TOB_VERSION", VERSION );
METADATA( "PLATFORM", PLATFORM );
QJsonObject meta;
for( auto it : Metadata::Instance()->Map().toStdMap() ) {
const QString& key = it.first;
const QString& value = it.second;
meta[ key ] = value;
}
params[ "_meta" ] = meta;
}
Metadata::Instance()->Clear();
QByteArray data = QJsonDocument( params ).toJson();
QNetworkReply *reply = AuthPostJson( "/profile/results.json", data );
connect( reply, &QNetworkReply::finished, [&, reply, result]() {
int replyCode = reply->error();
if( replyCode == QNetworkReply::NoError ) {
QJsonObject response;
if( JsonFromReply( reply, &response) ) {
emit UploadResultSucceeded( response );
}
} else {
int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
emit UploadResultFailed( result, replyCode, statusCode );
}
reply->deleteLater();
});
}
QNetworkReply* WebProfile::AuthPostJson( const QString& path, const QByteArray& data ) {
QString credentials = "Basic " +
( Settings::Instance()->AccountUsername() +
":" +
Settings::Instance()->AccountPassword()
).toLatin1().toBase64();
QNetworkRequest request = CreateWebProfileRequest( path );
request.setRawHeader( "Authorization", credentials.toLatin1() );
request.setHeader( QNetworkRequest::ContentTypeHeader, "application/json" );
return mNetworkManager.post( request, data );
}
QNetworkRequest WebProfile::CreateWebProfileRequest( const QString& path ) {
QUrl url( WebserviceURL( path ) );
QNetworkRequest request( url );
request.setRawHeader( "User-Agent", "Track-o-Bot/" VERSION PLATFORM );
return request;
}
void WebProfile::CreateAndStoreAccount() {
QNetworkRequest request = CreateWebProfileRequest( "/users.json" );
QNetworkReply *reply = mNetworkManager.post( request, "" );
connect( reply, &QNetworkReply::finished, this, &WebProfile::CreateAndStoreAccountHandleReply );
}
void WebProfile::CreateAndStoreAccountHandleReply() {
QNetworkReply *reply = static_cast< QNetworkReply* >( sender() );
if( reply->error() == QNetworkReply::NoError ) {
LOG( "Account creation was successful!" );
QJsonObject user;
if( JsonFromReply( reply, &user ) ) {
LOG( "Welcome %s", qt2cstr( user[ "username" ].toString() ) );
Settings::Instance()->SetAccount(
user["username"].toString(),
user["password"].toString() );
}
} else {
int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
ERR( "There was a problem creating an account. Error: %i HTTP Status Code: %i", reply->error(), statusCode );
}
reply->deleteLater();
}
void WebProfile::OpenProfile() {
QNetworkReply *reply = AuthPostJson( "/one_time_auth.json", "" );
connect( reply, &QNetworkReply::finished, this, &WebProfile::OpenProfileHandleReply );
}
void WebProfile::OpenProfileHandleReply() {
QNetworkReply *reply = static_cast< QNetworkReply* >( sender() );
if( reply->error() == QNetworkReply::NoError ) {
QJsonObject response;
if( JsonFromReply( reply, &response ) ) {
QString url = response[ "url" ].toString();
QDesktopServices::openUrl( QUrl( url ) );
}
} else {
int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
ERR( "There was a problem creating an auth token. Error: %i HTTP Status Code: %i", reply->error(), statusCode );
}
reply->deleteLater();
}
QString WebProfile::WebserviceURL( const QString& path ) {
if( Settings::Instance()->WebserviceURL().isEmpty() ) {
Settings::Instance()->SetWebserviceURL( DEFAULT_WEBSERVICE_URL );
}
return Settings::Instance()->WebserviceURL() + path;
}
// Allow self-signed certificates because Qt might report
// "There root certificate of the certificate chain is self-signed, and untrusted"
// The root cert might not be trusted yet (only after we browse to the website)
// So allow allow self-signed certificates, just in case
void WebProfile::SSLErrors(QNetworkReply *reply, const QList<QSslError>& errors) {
QList<QSslError> errorsToIgnore;
for( const QSslError& err : errors ) {
if( err.error() == QSslError::SelfSignedCertificate ||
err.error() == QSslError::SelfSignedCertificateInChain )
{
errorsToIgnore << err;
} else {
ERR( "SSL Error %d", err.error() );
}
}
reply->ignoreSslErrors( errorsToIgnore );
}
<commit_msg>Mac: Throw error when Qt is built with bearer management. Fixes #111<commit_after>#include "WebProfile.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QTimer>
#include <QDesktopServices>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "Hearthstone.h"
#include "Settings.h"
#define DEFAULT_WEBSERVICE_URL "https://trackobot.com"
#if defined(Q_OS_MAC) && !defined(QT_NO_BEARERMANAGEMENT)
#error Qt must be built without bearer management (-no-feature-bearermanagement) on Mac (until https://bugreports.qt.io/browse/QTBUG-50181 is fixed)
#endif
WebProfile::WebProfile( QObject *parent )
: QObject( parent )
{
connect( &mNetworkManager, &QNetworkAccessManager::sslErrors, this, &WebProfile::SSLErrors );
}
bool JsonFromReply( QNetworkReply *reply, QJsonObject *object ) {
QByteArray jsonData = reply->readAll();
QJsonParseError error;
*object = QJsonDocument::fromJson( jsonData, &error ).object();
if( error.error != QJsonParseError::NoError ) {
ERR( "Couldn't parse response %s", qt2cstr( error.errorString() ) );
return false;
}
DBG( "Received %s", qt2cstr( QString( jsonData ) ) );
return true;
}
void WebProfile::EnsureAccountIsSetUp() {
if( !Settings::Instance()->HasAccount() ) {
LOG( "No account setup. Creating one for you." );
CreateAndStoreAccount();
} else {
LOG( "Account %s found", qt2cstr( Settings::Instance()->AccountUsername() ) );
}
}
void WebProfile::UploadResult( const QJsonObject& result )
{
QJsonObject params;
params[ "result" ] = result;
// Optional upload metadata to find out room for improvements
if( Settings::Instance()->DebugEnabled() ) {
METADATA( "GAME_WIDTH", Hearthstone::Instance()->Width() );
METADATA( "GAME_HEIGHT", Hearthstone::Instance()->Height() );
METADATA( "TOB_VERSION", VERSION );
METADATA( "PLATFORM", PLATFORM );
QJsonObject meta;
for( auto it : Metadata::Instance()->Map().toStdMap() ) {
const QString& key = it.first;
const QString& value = it.second;
meta[ key ] = value;
}
params[ "_meta" ] = meta;
}
Metadata::Instance()->Clear();
QByteArray data = QJsonDocument( params ).toJson();
QNetworkReply *reply = AuthPostJson( "/profile/results.json", data );
connect( reply, &QNetworkReply::finished, [&, reply, result]() {
int replyCode = reply->error();
if( replyCode == QNetworkReply::NoError ) {
QJsonObject response;
if( JsonFromReply( reply, &response) ) {
emit UploadResultSucceeded( response );
}
} else {
int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
emit UploadResultFailed( result, replyCode, statusCode );
}
reply->deleteLater();
});
}
QNetworkReply* WebProfile::AuthPostJson( const QString& path, const QByteArray& data ) {
QString credentials = "Basic " +
( Settings::Instance()->AccountUsername() +
":" +
Settings::Instance()->AccountPassword()
).toLatin1().toBase64();
QNetworkRequest request = CreateWebProfileRequest( path );
request.setRawHeader( "Authorization", credentials.toLatin1() );
request.setHeader( QNetworkRequest::ContentTypeHeader, "application/json" );
return mNetworkManager.post( request, data );
}
QNetworkRequest WebProfile::CreateWebProfileRequest( const QString& path ) {
QUrl url( WebserviceURL( path ) );
QNetworkRequest request( url );
request.setRawHeader( "User-Agent", "Track-o-Bot/" VERSION PLATFORM );
return request;
}
void WebProfile::CreateAndStoreAccount() {
QNetworkRequest request = CreateWebProfileRequest( "/users.json" );
QNetworkReply *reply = mNetworkManager.post( request, "" );
connect( reply, &QNetworkReply::finished, this, &WebProfile::CreateAndStoreAccountHandleReply );
}
void WebProfile::CreateAndStoreAccountHandleReply() {
QNetworkReply *reply = static_cast< QNetworkReply* >( sender() );
if( reply->error() == QNetworkReply::NoError ) {
LOG( "Account creation was successful!" );
QJsonObject user;
if( JsonFromReply( reply, &user ) ) {
LOG( "Welcome %s", qt2cstr( user[ "username" ].toString() ) );
Settings::Instance()->SetAccount(
user["username"].toString(),
user["password"].toString() );
}
} else {
int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
ERR( "There was a problem creating an account. Error: %i HTTP Status Code: %i", reply->error(), statusCode );
}
reply->deleteLater();
}
void WebProfile::OpenProfile() {
QNetworkReply *reply = AuthPostJson( "/one_time_auth.json", "" );
connect( reply, &QNetworkReply::finished, this, &WebProfile::OpenProfileHandleReply );
}
void WebProfile::OpenProfileHandleReply() {
QNetworkReply *reply = static_cast< QNetworkReply* >( sender() );
if( reply->error() == QNetworkReply::NoError ) {
QJsonObject response;
if( JsonFromReply( reply, &response ) ) {
QString url = response[ "url" ].toString();
QDesktopServices::openUrl( QUrl( url ) );
}
} else {
int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
ERR( "There was a problem creating an auth token. Error: %i HTTP Status Code: %i", reply->error(), statusCode );
}
reply->deleteLater();
}
QString WebProfile::WebserviceURL( const QString& path ) {
if( Settings::Instance()->WebserviceURL().isEmpty() ) {
Settings::Instance()->SetWebserviceURL( DEFAULT_WEBSERVICE_URL );
}
return Settings::Instance()->WebserviceURL() + path;
}
// Allow self-signed certificates because Qt might report
// "There root certificate of the certificate chain is self-signed, and untrusted"
// The root cert might not be trusted yet (only after we browse to the website)
// So allow allow self-signed certificates, just in case
void WebProfile::SSLErrors(QNetworkReply *reply, const QList<QSslError>& errors) {
QList<QSslError> errorsToIgnore;
for( const QSslError& err : errors ) {
if( err.error() == QSslError::SelfSignedCertificate ||
err.error() == QSslError::SelfSignedCertificateInChain )
{
errorsToIgnore << err;
} else {
ERR( "SSL Error %d", err.error() );
}
}
reply->ignoreSslErrors( errorsToIgnore );
}
<|endoftext|> |
<commit_before>/*
* BackwardChainer.cc
*
* Copyright (C) 2014-2017 OpenCog Foundation
*
* Authors: Misgana Bayetta <[email protected]> October 2014
* William Ma <https://github.com/williampma>
* Nil Geisweiller 2016-2017
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <random>
#include <boost/range/algorithm/lower_bound.hpp>
#include <opencog/util/random.h>
#include <opencog/atomutils/FindUtils.h>
#include <opencog/atomutils/Substitutor.h>
#include <opencog/atomutils/Unify.h>
#include <opencog/atomutils/TypeUtils.h>
#include <opencog/atoms/pattern/PatternLink.h>
#include <opencog/atoms/pattern/BindLink.h>
#include <opencog/query/BindLinkAPI.h>
#include "BackwardChainer.h"
#include "BackwardChainerPMCB.h"
#include "UnifyPMCB.h"
#include "BCLogger.h"
using namespace opencog;
BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs,
const Handle& target,
const Handle& vardecl,
const Handle& focus_set, // TODO:
// support
// focus_set
const BITNodeFitness& fitness)
: _fcs_maximum_size(2000),
_as(as), _configReader(as, rbs),
_bit(as, target, vardecl, fitness),
_iteration(0), _last_expansion_andbit(nullptr),
_rules(_configReader.get_rules()) {
}
UREConfigReader& BackwardChainer::get_config()
{
return _configReader;
}
const UREConfigReader& BackwardChainer::get_config() const
{
return _configReader;
}
void BackwardChainer::do_chain()
{
while (not termination())
{
do_step();
}
}
void BackwardChainer::do_step()
{
bc_logger().debug("Iteration %d", _iteration);
_iteration++;
expand_bit();
fulfill_bit();
reduce_bit();
}
bool BackwardChainer::termination()
{
return _configReader.get_maximum_iterations() <= _iteration;
}
Handle BackwardChainer::get_results() const
{
HandleSeq results(_results.begin(), _results.end());
return _as.add_link(SET_LINK, results);
}
void BackwardChainer::expand_bit()
{
// This is kinda of hack before meta rules are fully supported by
// the Rule class.
size_t rules_size = _rules.size();
_rules.expand_meta_rules(_as);
// If the rule set has changed we need to reset the exhausted
// flags.
if (rules_size != _rules.size()) {
_bit.reset_exhausted_flags();
bc_logger().debug() << "The rule set has gone from "
<< rules_size << " rules to " << _rules.size()
<< ". All exhausted flags have been reset.";
}
// Reset _last_expansion_fcs
_last_expansion_andbit = nullptr;
if (_bit.empty()) {
_last_expansion_andbit = _bit.init();
} else {
// Select an FCS (i.e. and-BIT) and expand it
AndBIT* andbit = select_expansion_andbit();
LAZY_BC_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl
<< andbit->to_string();
expand_bit(*andbit);
}
}
void BackwardChainer::expand_bit(AndBIT& andbit)
{
// Select leaf
BITNode* bitleaf = andbit.select_leaf();
if (bitleaf) {
LAZY_BC_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl
<< bitleaf->to_string();
} else {
bc_logger().debug() << "All BIT-nodes of this and-BIT are exhausted "
<< "(or possibly fulfilled). Abort expansion.";
andbit.exhausted = true;
return;
}
// Get the leaf vardecl from fcs. We don't want to filter it
// because otherwise the typed substitution obtained may miss some
// variables in the FCS declaration that needs to be substituted
// during expension.
Handle vardecl = BindLinkCast(andbit.fcs)->get_vardecl();
// Select a valid rule
RuleTypedSubstitutionPair rule_ts = select_rule(*bitleaf, vardecl);
Rule rule(rule_ts.first);
Unify::TypedSubstitution ts(rule_ts.second);
// Add the rule in the _bit.bit_as to make comparing atoms easier
// as well as logging more consistent.
rule.add(_bit.bit_as);
if (not rule.is_valid()) {
bc_logger().debug("No valid rule for the selected BIT-node, abort expansion");
return;
}
LAZY_BC_LOG_DEBUG << "Selected rule for BIT expansion:" << std::endl
<< rule.to_string();
_last_expansion_andbit = _bit.expand(andbit, *bitleaf, {rule, ts});
}
void BackwardChainer::fulfill_bit()
{
if (_bit.empty()) {
bc_logger().warn("Cannot fulfill an empty BIT!");
return;
}
// Select an and-BIT for fulfillment
const AndBIT* andbit = select_fulfillment_andbit();
if (andbit == nullptr) {
bc_logger().debug() << "Cannot fulfill an empty and-BIT. "
<< "Abort BIT fulfillment";
return;
}
LAZY_BC_LOG_DEBUG << "Selected and-BIT for fulfillment:"
<< andbit->fcs->idToString();
fulfill_fcs(andbit->fcs);
}
void BackwardChainer::fulfill_fcs(const Handle& fcs)
{
// Temporary atomspace to not pollute _as with intermediary
// results
AtomSpace tmp_as(&_as);
// Run the FCS and add the results in _as
Handle hresult = bindlink(&tmp_as, fcs);
HandleSeq results;
for (const Handle& result : hresult->getOutgoingSet())
results.push_back(_as.add_atom(result));
LAZY_BC_LOG_DEBUG << "Results:" << std::endl << results;
_results.insert(results.begin(), results.end());
}
AndBIT* BackwardChainer::select_expansion_andbit()
{
// Calculate distribution based on a (poor) estimate of the
// probablity of a and-BIT being within the path of the solution.
std::vector<double> weights;
for (const AndBIT& andbit : _bit.andbits)
weights.push_back(operator()(andbit));
// Debug log
if (bc_logger().is_debug_enabled()) {
OC_ASSERT(weights.size() == _bit.andbits.size());
std::stringstream ss;
ss << "Weighted and-BITs:";
for (size_t i = 0; i < weights.size(); i++)
ss << std::endl << weights[i] << " "
<< _bit.andbits[i].fcs->idToString();
bc_logger().debug() << ss.str();
}
// Sample andbits according to this distribution
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
return &rand_element(_bit.andbits, dist);
}
const AndBIT* BackwardChainer::select_fulfillment_andbit() const
{
return _last_expansion_andbit;
}
void BackwardChainer::reduce_bit()
{
// TODO: reset exhausted flags related to the removed and-BITs.
// TODO: remove least likely and-BITs
// // Remove and-BITs above a certain size.
// auto complex_lt = [&](const AndBIT& andbit, size_t max_size) {
// return andbit.fcs->size() < max_size; };
// auto it = boost::lower_bound(_bit.andbits, _fcs_maximum_size, complex_lt);
// size_t previous_size = _bit.andbits.size();
// _bit.erase(it, _bit.andbits.end());
// if (size_t removed_andbits = previous_size - _bit.andbits.size()) {
// LAZY_BC_LOG_DEBUG << "Removed " << removed_andbits
// << " overly complex and-BITs from the BIT";
// }
}
RuleTypedSubstitutionPair BackwardChainer::select_rule(BITNode& target,
const Handle& vardecl)
{
// The rule is randomly selected amongst the valid ones, with
// probability of selection being proportional to its weight.
const RuleTypedSubstitutionMap valid_rules = get_valid_rules(target, vardecl);
if (valid_rules.empty()) {
target.exhausted = true;
return {Rule(), Unify::TypedSubstitution()};;
}
// Log all valid rules and their weights
if (bc_logger().is_debug_enabled()) {
std::stringstream ss;
ss << "The following weighted rules are valid:";
for (const auto& r : valid_rules)
ss << std::endl << r.first.get_weight() << " " << r.first.get_name();
LAZY_BC_LOG_DEBUG << ss.str();
}
return select_rule(valid_rules);
}
RuleTypedSubstitutionPair BackwardChainer::select_rule(const RuleTypedSubstitutionMap& rules)
{
// Build weight vector to do weighted random selection
std::vector<double> weights;
for (const auto& rule : rules)
weights.push_back(rule.first.get_weight());
// No rule exhaustion, sample one according to the distribution
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
return rand_element(rules, dist);
}
RuleTypedSubstitutionMap BackwardChainer::get_valid_rules(const BITNode& target,
const Handle& vardecl)
{
// Generate all valid rules
RuleTypedSubstitutionMap valid_rules;
for (const Rule& rule : _rules) {
// For now ignore meta rules as they are forwardly applied in
// expand_bit()
if (rule.is_meta())
continue;
RuleTypedSubstitutionMap unified_rules
= rule.unify_target(target.body, vardecl);
// Insert only rules with positive probability of success
RuleTypedSubstitutionMap pos_rules;
for (const auto& rule : unified_rules) {
double p = (_bit.is_in(rule, target) ? 0.0 : 1.0)
* rule.first.get_weight();
if (p > 0) pos_rules.insert(rule);
}
valid_rules.insert(pos_rules.begin(), pos_rules.end());
}
return valid_rules;
}
double BackwardChainer::complexity_factor(const AndBIT& andbit) const
{
return exp(-_configReader.get_complexity_penalty() * andbit.complexity);
}
double BackwardChainer::operator()(const AndBIT& andbit) const
{
return (andbit.exhausted ? 0.0 : 1.0) * complexity_factor(andbit);
}
<commit_msg>Improve and-BIT fulfillment log<commit_after>/*
* BackwardChainer.cc
*
* Copyright (C) 2014-2017 OpenCog Foundation
*
* Authors: Misgana Bayetta <[email protected]> October 2014
* William Ma <https://github.com/williampma>
* Nil Geisweiller 2016-2017
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <random>
#include <boost/range/algorithm/lower_bound.hpp>
#include <opencog/util/random.h>
#include <opencog/atomutils/FindUtils.h>
#include <opencog/atomutils/Substitutor.h>
#include <opencog/atomutils/Unify.h>
#include <opencog/atomutils/TypeUtils.h>
#include <opencog/atoms/pattern/PatternLink.h>
#include <opencog/atoms/pattern/BindLink.h>
#include <opencog/query/BindLinkAPI.h>
#include "BackwardChainer.h"
#include "BackwardChainerPMCB.h"
#include "UnifyPMCB.h"
#include "BCLogger.h"
using namespace opencog;
BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs,
const Handle& target,
const Handle& vardecl,
const Handle& focus_set, // TODO:
// support
// focus_set
const BITNodeFitness& fitness)
: _fcs_maximum_size(2000),
_as(as), _configReader(as, rbs),
_bit(as, target, vardecl, fitness),
_iteration(0), _last_expansion_andbit(nullptr),
_rules(_configReader.get_rules()) {
}
UREConfigReader& BackwardChainer::get_config()
{
return _configReader;
}
const UREConfigReader& BackwardChainer::get_config() const
{
return _configReader;
}
void BackwardChainer::do_chain()
{
while (not termination())
{
do_step();
}
}
void BackwardChainer::do_step()
{
bc_logger().debug("Iteration %d", _iteration);
_iteration++;
expand_bit();
fulfill_bit();
reduce_bit();
}
bool BackwardChainer::termination()
{
return _configReader.get_maximum_iterations() <= _iteration;
}
Handle BackwardChainer::get_results() const
{
HandleSeq results(_results.begin(), _results.end());
return _as.add_link(SET_LINK, results);
}
void BackwardChainer::expand_bit()
{
// This is kinda of hack before meta rules are fully supported by
// the Rule class.
size_t rules_size = _rules.size();
_rules.expand_meta_rules(_as);
// If the rule set has changed we need to reset the exhausted
// flags.
if (rules_size != _rules.size()) {
_bit.reset_exhausted_flags();
bc_logger().debug() << "The rule set has gone from "
<< rules_size << " rules to " << _rules.size()
<< ". All exhausted flags have been reset.";
}
// Reset _last_expansion_fcs
_last_expansion_andbit = nullptr;
if (_bit.empty()) {
_last_expansion_andbit = _bit.init();
} else {
// Select an FCS (i.e. and-BIT) and expand it
AndBIT* andbit = select_expansion_andbit();
LAZY_BC_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl
<< andbit->to_string();
expand_bit(*andbit);
}
}
void BackwardChainer::expand_bit(AndBIT& andbit)
{
// Select leaf
BITNode* bitleaf = andbit.select_leaf();
if (bitleaf) {
LAZY_BC_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl
<< bitleaf->to_string();
} else {
bc_logger().debug() << "All BIT-nodes of this and-BIT are exhausted "
<< "(or possibly fulfilled). Abort expansion.";
andbit.exhausted = true;
return;
}
// Get the leaf vardecl from fcs. We don't want to filter it
// because otherwise the typed substitution obtained may miss some
// variables in the FCS declaration that needs to be substituted
// during expension.
Handle vardecl = BindLinkCast(andbit.fcs)->get_vardecl();
// Select a valid rule
RuleTypedSubstitutionPair rule_ts = select_rule(*bitleaf, vardecl);
Rule rule(rule_ts.first);
Unify::TypedSubstitution ts(rule_ts.second);
// Add the rule in the _bit.bit_as to make comparing atoms easier
// as well as logging more consistent.
rule.add(_bit.bit_as);
if (not rule.is_valid()) {
bc_logger().debug("No valid rule for the selected BIT-node, abort expansion");
return;
}
LAZY_BC_LOG_DEBUG << "Selected rule for BIT expansion:" << std::endl
<< rule.to_string();
_last_expansion_andbit = _bit.expand(andbit, *bitleaf, {rule, ts});
}
void BackwardChainer::fulfill_bit()
{
if (_bit.empty()) {
bc_logger().warn("Cannot fulfill an empty BIT!");
return;
}
// Select an and-BIT for fulfillment
const AndBIT* andbit = select_fulfillment_andbit();
if (andbit == nullptr) {
bc_logger().debug() << "Cannot fulfill an empty and-BIT. "
<< "Abort BIT fulfillment";
return;
}
LAZY_BC_LOG_DEBUG << "Selected and-BIT for fulfillment (fcs value):"
<< std::endl << andbit->fcs->idToString();
fulfill_fcs(andbit->fcs);
}
void BackwardChainer::fulfill_fcs(const Handle& fcs)
{
// Temporary atomspace to not pollute _as with intermediary
// results
AtomSpace tmp_as(&_as);
// Run the FCS and add the results in _as
Handle hresult = bindlink(&tmp_as, fcs);
HandleSeq results;
for (const Handle& result : hresult->getOutgoingSet())
results.push_back(_as.add_atom(result));
LAZY_BC_LOG_DEBUG << "Results:" << std::endl << results;
_results.insert(results.begin(), results.end());
}
AndBIT* BackwardChainer::select_expansion_andbit()
{
// Calculate distribution based on a (poor) estimate of the
// probablity of a and-BIT being within the path of the solution.
std::vector<double> weights;
for (const AndBIT& andbit : _bit.andbits)
weights.push_back(operator()(andbit));
// Debug log
if (bc_logger().is_debug_enabled()) {
OC_ASSERT(weights.size() == _bit.andbits.size());
std::stringstream ss;
ss << "Weighted and-BITs:";
for (size_t i = 0; i < weights.size(); i++)
ss << std::endl << weights[i] << " "
<< _bit.andbits[i].fcs->idToString();
bc_logger().debug() << ss.str();
}
// Sample andbits according to this distribution
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
return &rand_element(_bit.andbits, dist);
}
const AndBIT* BackwardChainer::select_fulfillment_andbit() const
{
return _last_expansion_andbit;
}
void BackwardChainer::reduce_bit()
{
// TODO: reset exhausted flags related to the removed and-BITs.
// TODO: remove least likely and-BITs
// // Remove and-BITs above a certain size.
// auto complex_lt = [&](const AndBIT& andbit, size_t max_size) {
// return andbit.fcs->size() < max_size; };
// auto it = boost::lower_bound(_bit.andbits, _fcs_maximum_size, complex_lt);
// size_t previous_size = _bit.andbits.size();
// _bit.erase(it, _bit.andbits.end());
// if (size_t removed_andbits = previous_size - _bit.andbits.size()) {
// LAZY_BC_LOG_DEBUG << "Removed " << removed_andbits
// << " overly complex and-BITs from the BIT";
// }
}
RuleTypedSubstitutionPair BackwardChainer::select_rule(BITNode& target,
const Handle& vardecl)
{
// The rule is randomly selected amongst the valid ones, with
// probability of selection being proportional to its weight.
const RuleTypedSubstitutionMap valid_rules = get_valid_rules(target, vardecl);
if (valid_rules.empty()) {
target.exhausted = true;
return {Rule(), Unify::TypedSubstitution()};;
}
// Log all valid rules and their weights
if (bc_logger().is_debug_enabled()) {
std::stringstream ss;
ss << "The following weighted rules are valid:";
for (const auto& r : valid_rules)
ss << std::endl << r.first.get_weight() << " " << r.first.get_name();
LAZY_BC_LOG_DEBUG << ss.str();
}
return select_rule(valid_rules);
}
RuleTypedSubstitutionPair BackwardChainer::select_rule(const RuleTypedSubstitutionMap& rules)
{
// Build weight vector to do weighted random selection
std::vector<double> weights;
for (const auto& rule : rules)
weights.push_back(rule.first.get_weight());
// No rule exhaustion, sample one according to the distribution
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
return rand_element(rules, dist);
}
RuleTypedSubstitutionMap BackwardChainer::get_valid_rules(const BITNode& target,
const Handle& vardecl)
{
// Generate all valid rules
RuleTypedSubstitutionMap valid_rules;
for (const Rule& rule : _rules) {
// For now ignore meta rules as they are forwardly applied in
// expand_bit()
if (rule.is_meta())
continue;
RuleTypedSubstitutionMap unified_rules
= rule.unify_target(target.body, vardecl);
// Insert only rules with positive probability of success
RuleTypedSubstitutionMap pos_rules;
for (const auto& rule : unified_rules) {
double p = (_bit.is_in(rule, target) ? 0.0 : 1.0)
* rule.first.get_weight();
if (p > 0) pos_rules.insert(rule);
}
valid_rules.insert(pos_rules.begin(), pos_rules.end());
}
return valid_rules;
}
double BackwardChainer::complexity_factor(const AndBIT& andbit) const
{
return exp(-_configReader.get_complexity_penalty() * andbit.complexity);
}
double BackwardChainer::operator()(const AndBIT& andbit) const
{
return (andbit.exhausted ? 0.0 : 1.0) * complexity_factor(andbit);
}
<|endoftext|> |
<commit_before>#include "XmlElement.hpp"
#ifdef APP_DEBUG
#include <algorithm>
#endif
namespace Xml
{
Element::Element(std::string const & name, Node * parent):
Node(parent),
mParent(parent),
mchildren(),
mComments(),
mPI()
{
}
Element::~Element()
{
}
NodeList const &
Element::elements() const
{
return mChildren;
}
Element const *
Element::parentElement() const
{
Node * parent = mParent;
do
{
if(parent->isElement()) break;
}
while((parent = mParent->parent()) != nullptr);
return parent;
}
std::string
Element::text() const
{
std::string content = "";
for(auto const & c : mChildren)
{
content += contentText();
}
return content;
}
void
Element::setContent(std::string const & content)
{
this->clearContent();
this->appendText(content);
}
void
Element::clearContent()
{
for(auto & c : mChildren)
{
if(c->isElement())
{
c->clearContent();
}
delete c;
}
}
void
Element::append(Node * node)
{
#ifdef APP_DEBUG
assert(node != this);
assert(
std::find(std::begin(mChildren), std::end(mChildren), node)
!= std::end(mChildren)
);
#endif
mChildren.append(node);
}
void
Element::appendText(std::string const & text)
{
this->appendNode(new Text(content));
}
void
Element::appendComment(std::string const & comment)
{
this->appendNode(new Comment(content));
}
void
Element::appendPI(std::string const & pi)
{
this->appendNode(new PI(content));
}
std::string const &
Element::name() const
{
return mName;
}
void
Element::setName(std::string const & name)
{
mName = name;
}
std::string const &
Element::attribute(std::string const & name) const
{
static std::string const notFound = "";
auto it = mAttributes.find(name);
return it != std::end(mAttributes) ? *it : notFound;
}
void
Element::setAttribute(std::string const & name, std::string const & value)
{
m_attributes[name] = value;
}
//TODO
void
Element::exportToStream(std::ostream & stream, std::string const & indent) const
{
for(auto const & c : mChildren)
{
stream << indent << c->contentText();
}
}
bool
Element::isElement() const
{
return true;
}
}
<commit_msg>Added resource freeing in XmlElement<commit_after>#include "XmlElement.hpp"
#ifdef APP_DEBUG
#include <algorithm>
#endif
namespace Xml
{
Element::Element(std::string const & name, Node * parent):
Node(parent),
mParent(parent),
mchildren(),
mComments(),
mPI()
{
}
Element::~Element()
{
// Free memory
this->clearContent();
}
NodeList const &
Element::elements() const
{
return mChildren;
}
Element const *
Element::parentElement() const
{
Node * parent = mParent;
do
{
if(parent->isElement()) break;
}
while((parent = mParent->parent()) != nullptr);
return parent;
}
std::string
Element::text() const
{
std::string content = "";
for(auto const & c : mChildren)
{
content += contentText();
}
return content;
}
void
Element::setContent(std::string const & content)
{
this->clearContent();
this->appendText(content);
}
void
Element::clearContent()
{
for(auto & c : mChildren)
{
if(c->isElement())
{
c->clearContent();
}
delete c;
}
}
void
Element::append(Node * node)
{
#ifdef APP_DEBUG
assert(node != this);
assert(
std::find(std::begin(mChildren), std::end(mChildren), node)
!= std::end(mChildren)
);
#endif
mChildren.append(node);
}
void
Element::appendText(std::string const & text)
{
this->appendNode(new Text(content));
}
void
Element::appendComment(std::string const & comment)
{
this->appendNode(new Comment(content));
}
void
Element::appendPI(std::string const & pi)
{
this->appendNode(new PI(content));
}
std::string const &
Element::name() const
{
return mName;
}
void
Element::setName(std::string const & name)
{
mName = name;
}
std::string const &
Element::attribute(std::string const & name) const
{
static std::string const notFound = "";
auto it = mAttributes.find(name);
return it != std::end(mAttributes) ? *it : notFound;
}
void
Element::setAttribute(std::string const & name, std::string const & value)
{
m_attributes[name] = value;
}
//TODO
void
Element::exportToStream(std::ostream & stream, std::string const & indent) const
{
for(auto const & c : mChildren)
{
stream << indent << c->contentText();
}
}
bool
Element::isElement() const
{
return true;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdint.h>
#include <QtConcurrent>
#include <QException>
#include <QFileDialog>
#include <QFuture>
#include <QGraphicsRectItem>
#include "viewer.h"
#include "ui_viewer.h"
Viewer::Viewer(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Viewer),
enabled(false),
highlight(NULL),
fingerprint(NULL)
{
ui->setupUi(this);
connect(&scanner_watcher, SIGNAL(finished()), this, SLOT(scannerFinished()));
on_timeoutSlider_valueChanged(ui->timeoutSlider->value());
ScannersList &scanners_list = ScannersList::getScannersList();
for (std::vector<const char *>::iterator name = scanners_list.begin();
name != scanners_list.end(); name++) {
ui->scannersList->addItem(QString(*name));
}
}
Viewer::~Viewer()
{
delete ui;
delete fingerprint;
}
void Viewer::highlightMinutia(int view, int minutia)
{
if (highlight) {
scene.removeItem(highlight);
highlight = NULL;
}
if (view == 0 && minutia >= 0) {
std::list<FingerprintMinutia>::iterator m = fingerprint->minutiaeRecord->minutiae.begin();
std::advance(m, minutia);
highlight = scene.addRect(m->x - 12, m->y - 12, 23, 23, QPen(QColor(0, 0xff, 0, 0xb0), 4), QBrush());
}
}
void Viewer::scrollToMinutia(int view, int minutia)
{
ui->templateText->scrollToAnchor(QString("view%1minutia%2").arg(view).arg(minutia));
}
void Viewer::message(QString message)
{
ui->statusLabel->setText(message);
ui->statusLabel->setStyleSheet("color: black; font-weight: normal;");
}
void Viewer::error(const char *message, int error)
{
if (error)
ui->statusLabel->setText(QString("%1 (%2)").arg(message).arg(error));
else
ui->statusLabel->setText(QString(message));
ui->statusLabel->setStyleSheet("color: red; font-weight: bold;");
}
class ViewerScannerException : public QException
{
const char *message;
int error;
public:
void raise() const { throw *this; }
ViewerScannerException *clone() const { return new ViewerScannerException(*this); }
int code() { return error; }
const char* what() { return message; }
ViewerScannerException(const char *message, int error = 0) : message(message), error(error) {}
};
Fingerprint *Viewer::scanStart(int timeout)
{
Fingerprint *fingerprint = NULL;
try {
fingerprint = scanner->getFingerprint(timeout);
} catch (ScannerException &e) {
throw ViewerScannerException(e.what(), e.code());
}
return fingerprint;
}
class MinutiaGraphicsItem : public QGraphicsItem
{
private:
Viewer *viewer;
int view, minutia;
int x, y, angle;
public:
MinutiaGraphicsItem(Viewer *viewer, int view, int minutia, int x, int y, int angle) :
viewer(viewer), view(view), minutia(minutia), x(x), y(y), angle(angle) {}
QRectF boundingRect() const
{
return QRectF(x - 10, y - 10, 20, 20);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
QPen pen(QColor(0xff, 0, 0, 0xb0), 2);
painter->setPen(pen);
painter->drawEllipse(x - 3, y - 3, 6, 6);
QLineF line;
line.setP1(QPointF(x, y));
line.setAngle(1.0 * angle / 100000);
line.setLength(10);
painter->drawLine(line);
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
viewer->highlightMinutia(view, minutia);
viewer->scrollToMinutia(view, minutia);
QGraphicsItem::mousePressEvent(event);
}
};
void Viewer::scannerFinished()
{
try {
fingerprint = scanner_watcher.result();
} catch (ViewerScannerException &e) {
error(e.what(), e.code());
}
if (fingerprint && fingerprint->image) {
QImage *image = fingerprint->image->getImage();
pixmap = QPixmap::fromImage(*image);
scene.addPixmap(pixmap);
scene.setSceneRect(pixmap.rect());
scene.addRect(pixmap.rect(), QPen(Qt::blue), QBrush());
message(QString("Obtained %1x%2 pixels large image").arg(image->width()).arg(image->height()));
delete image;
ui->saveImageButton->setEnabled(true);
}
if (fingerprint && fingerprint->minutiaeRecord) {
ui->templateText->setHtml(fingerprint->minutiaeRecord->getHtml());
if (fingerprint->image) {
for (std::list<FingerprintMinutia>::iterator m = fingerprint->minutiaeRecord->minutiae.begin();
m != fingerprint->minutiaeRecord->minutiae.end(); m++) {
int index = std::distance(fingerprint->minutiaeRecord->minutiae.begin(), m);
MinutiaGraphicsItem *minutae = new MinutiaGraphicsItem(this, 0, index, m->x, m->y, m->angle);
minutae->setToolTip(QString("Minutia %1").arg(index));
scene.addItem(minutae);
}
}
ui->saveFMRButton->setEnabled(true);
}
ui->imageView->setScene(&scene);
ui->scanButton->setEnabled(true);
ui->onOffButton->setEnabled(true);
ui->timeoutSlider->setEnabled(true);
}
void Viewer::on_scanButton_clicked()
{
int timeout = ui->timeoutSlider->value();
if (timeout == ui->timeoutSlider->maximum())
timeout = -1;
else
timeout *= 1000;
scene.clear();
ui->templateText->clear();
ui->saveImageButton->setEnabled(false);
ui->saveFMRButton->setEnabled(false);
ui->onOffButton->setEnabled(false);
ui->timeoutSlider->setEnabled(false);
ui->scanButton->setEnabled(false);
delete fingerprint;
fingerprint = NULL;
QFuture<Fingerprint *> future = QtConcurrent::run(this, &Viewer::scanStart, timeout);
scanner_watcher.setFuture(future);
message("Scanning...");
}
void Viewer::on_onOffButton_clicked()
{
if (!enabled) {
try {
ScannersList &scanners_list = ScannersList::getScannersList();
scanner = new Scanner(scanners_list[ui->scannersList->currentIndex()]);
message(QString("Turned on scanner '%1'").arg(scanner->getName()));
enabled = true;
} catch (ScannerException &e) {
error(e.what(), e.code());
}
} else {
message(QString("Turned off scanner '%1'").arg(scanner->getName()));
delete scanner;
ui->templateText->clear();
scene.clear();
ui->saveImageButton->setEnabled(false);
ui->saveFMRButton->setEnabled(false);
enabled = false;
}
ui->scannersList->setEnabled(!enabled);
ui->scanButton->setEnabled(enabled);
ui->timeoutSlider->setEnabled(enabled);
ui->onOffButton->setText(enabled ? "Turn off" : "Turn on");
}
void Viewer::on_timeoutSlider_valueChanged(int value)
{
QString timeout;
if (value == ui->timeoutSlider->maximum())
timeout = QString("infinite");
else if (value == 0)
timeout = QString("none");
else if (value == 1)
timeout = QString("1 second");
else
timeout = QString("%1 seconds").arg(value);
ui->timeoutLabel->setText(QString("Timeout: %1").arg(timeout));
}
void Viewer::on_saveFMRButton_clicked()
{
QString filter;
QString name = QFileDialog::getSaveFileName(this, tr("Save FMR as..."), "", tr("Fingerprint Minutiae Records (*.fmr);;All Files (*)"), &filter);
if (!name.isEmpty()) {
if (filter.contains("fmr") && !name.endsWith(".fmr", Qt::CaseInsensitive))
name += ".fmr";
QFile file(name);
file.open(QIODevice::WriteOnly);
file.write((const char *)fingerprint->minutiaeRecord->getBinary(), fingerprint->minutiaeRecord->getSize());
file.close();
message(QString("%1 saved").arg(name));
}
}
void Viewer::on_saveImageButton_clicked()
{
QString filter;
QString name = QFileDialog::getSaveFileName(this, tr("Save FMR as..."), "", tr("PNG Images (*.png);;JPEG Images (*.jpg);;BMP Images (*.bmp);;All Files (*)"), &filter);
if (!name.isEmpty()) {
if (filter.contains("png") && !name.endsWith(".png", Qt::CaseInsensitive))
name += ".png";
else if (filter.contains("jpg") && !name.endsWith(".jpg", Qt::CaseInsensitive) && !name.endsWith(".jpeg", Qt::CaseInsensitive))
name += ".jpg";
else if (filter.contains("bmp") && !name.endsWith(".bmp", Qt::CaseInsensitive))
name += ".bmp";
QFile file(name);
file.open(QIODevice::WriteOnly);
pixmap.save(&file);
file.close();
message(QString("%1 saved").arg(name));
}
}
<commit_msg>viewer: Fix missing save dialog label<commit_after>#include <iostream>
#include <stdint.h>
#include <QtConcurrent>
#include <QException>
#include <QFileDialog>
#include <QFuture>
#include <QGraphicsRectItem>
#include "viewer.h"
#include "ui_viewer.h"
Viewer::Viewer(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Viewer),
enabled(false),
highlight(NULL),
fingerprint(NULL)
{
ui->setupUi(this);
connect(&scanner_watcher, SIGNAL(finished()), this, SLOT(scannerFinished()));
on_timeoutSlider_valueChanged(ui->timeoutSlider->value());
ScannersList &scanners_list = ScannersList::getScannersList();
for (std::vector<const char *>::iterator name = scanners_list.begin();
name != scanners_list.end(); name++) {
ui->scannersList->addItem(QString(*name));
}
}
Viewer::~Viewer()
{
delete ui;
delete fingerprint;
}
void Viewer::highlightMinutia(int view, int minutia)
{
if (highlight) {
scene.removeItem(highlight);
highlight = NULL;
}
if (view == 0 && minutia >= 0) {
std::list<FingerprintMinutia>::iterator m = fingerprint->minutiaeRecord->minutiae.begin();
std::advance(m, minutia);
highlight = scene.addRect(m->x - 12, m->y - 12, 23, 23, QPen(QColor(0, 0xff, 0, 0xb0), 4), QBrush());
}
}
void Viewer::scrollToMinutia(int view, int minutia)
{
ui->templateText->scrollToAnchor(QString("view%1minutia%2").arg(view).arg(minutia));
}
void Viewer::message(QString message)
{
ui->statusLabel->setText(message);
ui->statusLabel->setStyleSheet("color: black; font-weight: normal;");
}
void Viewer::error(const char *message, int error)
{
if (error)
ui->statusLabel->setText(QString("%1 (%2)").arg(message).arg(error));
else
ui->statusLabel->setText(QString(message));
ui->statusLabel->setStyleSheet("color: red; font-weight: bold;");
}
class ViewerScannerException : public QException
{
const char *message;
int error;
public:
void raise() const { throw *this; }
ViewerScannerException *clone() const { return new ViewerScannerException(*this); }
int code() { return error; }
const char* what() { return message; }
ViewerScannerException(const char *message, int error = 0) : message(message), error(error) {}
};
Fingerprint *Viewer::scanStart(int timeout)
{
Fingerprint *fingerprint = NULL;
try {
fingerprint = scanner->getFingerprint(timeout);
} catch (ScannerException &e) {
throw ViewerScannerException(e.what(), e.code());
}
return fingerprint;
}
class MinutiaGraphicsItem : public QGraphicsItem
{
private:
Viewer *viewer;
int view, minutia;
int x, y, angle;
public:
MinutiaGraphicsItem(Viewer *viewer, int view, int minutia, int x, int y, int angle) :
viewer(viewer), view(view), minutia(minutia), x(x), y(y), angle(angle) {}
QRectF boundingRect() const
{
return QRectF(x - 10, y - 10, 20, 20);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
QPen pen(QColor(0xff, 0, 0, 0xb0), 2);
painter->setPen(pen);
painter->drawEllipse(x - 3, y - 3, 6, 6);
QLineF line;
line.setP1(QPointF(x, y));
line.setAngle(1.0 * angle / 100000);
line.setLength(10);
painter->drawLine(line);
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
viewer->highlightMinutia(view, minutia);
viewer->scrollToMinutia(view, minutia);
QGraphicsItem::mousePressEvent(event);
}
};
void Viewer::scannerFinished()
{
try {
fingerprint = scanner_watcher.result();
} catch (ViewerScannerException &e) {
error(e.what(), e.code());
}
if (fingerprint && fingerprint->image) {
QImage *image = fingerprint->image->getImage();
pixmap = QPixmap::fromImage(*image);
scene.addPixmap(pixmap);
scene.setSceneRect(pixmap.rect());
scene.addRect(pixmap.rect(), QPen(Qt::blue), QBrush());
message(QString("Obtained %1x%2 pixels large image").arg(image->width()).arg(image->height()));
delete image;
ui->saveImageButton->setEnabled(true);
}
if (fingerprint && fingerprint->minutiaeRecord) {
ui->templateText->setHtml(fingerprint->minutiaeRecord->getHtml());
if (fingerprint->image) {
for (std::list<FingerprintMinutia>::iterator m = fingerprint->minutiaeRecord->minutiae.begin();
m != fingerprint->minutiaeRecord->minutiae.end(); m++) {
int index = std::distance(fingerprint->minutiaeRecord->minutiae.begin(), m);
MinutiaGraphicsItem *minutae = new MinutiaGraphicsItem(this, 0, index, m->x, m->y, m->angle);
minutae->setToolTip(QString("Minutia %1").arg(index));
scene.addItem(minutae);
}
}
ui->saveFMRButton->setEnabled(true);
}
ui->imageView->setScene(&scene);
ui->scanButton->setEnabled(true);
ui->onOffButton->setEnabled(true);
ui->timeoutSlider->setEnabled(true);
}
void Viewer::on_scanButton_clicked()
{
int timeout = ui->timeoutSlider->value();
if (timeout == ui->timeoutSlider->maximum())
timeout = -1;
else
timeout *= 1000;
scene.clear();
ui->templateText->clear();
ui->saveImageButton->setEnabled(false);
ui->saveFMRButton->setEnabled(false);
ui->onOffButton->setEnabled(false);
ui->timeoutSlider->setEnabled(false);
ui->scanButton->setEnabled(false);
delete fingerprint;
fingerprint = NULL;
QFuture<Fingerprint *> future = QtConcurrent::run(this, &Viewer::scanStart, timeout);
scanner_watcher.setFuture(future);
message("Scanning...");
}
void Viewer::on_onOffButton_clicked()
{
if (!enabled) {
try {
ScannersList &scanners_list = ScannersList::getScannersList();
scanner = new Scanner(scanners_list[ui->scannersList->currentIndex()]);
message(QString("Turned on scanner '%1'").arg(scanner->getName()));
enabled = true;
} catch (ScannerException &e) {
error(e.what(), e.code());
}
} else {
message(QString("Turned off scanner '%1'").arg(scanner->getName()));
delete scanner;
ui->templateText->clear();
scene.clear();
ui->saveImageButton->setEnabled(false);
ui->saveFMRButton->setEnabled(false);
enabled = false;
}
ui->scannersList->setEnabled(!enabled);
ui->scanButton->setEnabled(enabled);
ui->timeoutSlider->setEnabled(enabled);
ui->onOffButton->setText(enabled ? "Turn off" : "Turn on");
}
void Viewer::on_timeoutSlider_valueChanged(int value)
{
QString timeout;
if (value == ui->timeoutSlider->maximum())
timeout = QString("infinite");
else if (value == 0)
timeout = QString("none");
else if (value == 1)
timeout = QString("1 second");
else
timeout = QString("%1 seconds").arg(value);
ui->timeoutLabel->setText(QString("Timeout: %1").arg(timeout));
}
void Viewer::on_saveFMRButton_clicked()
{
QString filter;
QString name = QFileDialog::getSaveFileName(this, tr("Save FMR as..."), "", tr("Fingerprint Minutiae Records (*.fmr);;All Files (*)"), &filter);
if (!name.isEmpty()) {
if (filter.contains("fmr") && !name.endsWith(".fmr", Qt::CaseInsensitive))
name += ".fmr";
QFile file(name);
file.open(QIODevice::WriteOnly);
file.write((const char *)fingerprint->minutiaeRecord->getBinary(), fingerprint->minutiaeRecord->getSize());
file.close();
message(QString("%1 saved").arg(name));
}
}
void Viewer::on_saveImageButton_clicked()
{
QString filter;
QString name = QFileDialog::getSaveFileName(this, tr("Save Image as..."), "", tr("PNG Images (*.png);;JPEG Images (*.jpg);;BMP Images (*.bmp);;All Files (*)"), &filter);
if (!name.isEmpty()) {
if (filter.contains("png") && !name.endsWith(".png", Qt::CaseInsensitive))
name += ".png";
else if (filter.contains("jpg") && !name.endsWith(".jpg", Qt::CaseInsensitive) && !name.endsWith(".jpeg", Qt::CaseInsensitive))
name += ".jpg";
else if (filter.contains("bmp") && !name.endsWith(".bmp", Qt::CaseInsensitive))
name += ".bmp";
QFile file(name);
file.open(QIODevice::WriteOnly);
pixmap.save(&file);
file.close();
message(QString("%1 saved").arg(name));
}
}
<|endoftext|> |
<commit_before><commit_msg>Pass Chrome's UA with chromeframe appended at the end in the user agent passed in ChromeFrame requests initiated in IE.<commit_after><|endoftext|> |
<commit_before>// RUN: cat %s | %cling 2>&1 | FileCheck %s
// Test Interpreter::lookupFunctionProto()
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/Decl.h"
#include <cstdio>
using namespace std;
//
// We need to fetch the global scope declaration,
// otherwise known as the translation unit decl.
//
const clang::Decl* G = gCling->lookupScope("");
printf("G: 0x%lx\n", (unsigned long) G);
//CHECK: G: 0x{{[1-9a-f][0-9a-f]*$}}
//
// Test finding a global function taking no args.
//
.rawInput 1
void f() { int x = 1; }
.rawInput 0
const clang::FunctionDecl* F = gCling->lookupFunctionProto(G, "f", "");
printf("F: 0x%lx\n", (unsigned long) F);
//CHECK-NEXT: F: 0x{{[1-9a-f][0-9a-f]*$}}
F->print(llvm::outs());
//CHECK-NEXT: void f() {
//CHECK-NEXT: int x = 1;
//CHECK-NEXT: }
//
// Test finding a global function taking a single int argument.
//
.rawInput 1
void a(int v) { int x = v; }
.rawInput 0
const clang::FunctionDecl* A = gCling->lookupFunctionProto(G, "a", "int");
printf("A: 0x%lx\n", (unsigned long) A);
//CHECK: A: 0x{{[1-9a-f][0-9a-f]*$}}
A->print(llvm::outs());
//CHECK-NEXT: void a(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
//
// Test finding a global function taking an int and a double argument.
//
.rawInput 1
void b(int vi, double vd) { int x = vi; double y = vd; }
.rawInput 0
const clang::FunctionDecl* B = gCling->lookupFunctionProto(G, "b", "int,double");
printf("B: 0x%lx\n", (unsigned long) B);
//CHECK: B: 0x{{[1-9a-f][0-9a-f]*$}}
B->print(llvm::outs());
//CHECK-NEXT: void b(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding a global overloaded function.
//
.rawInput 1
void c(int vi, int vj) { int x = vi; int y = vj; }
void c(int vi, double vd) { int x = vi; double y = vd; }
.rawInput 0
const clang::FunctionDecl* C1 = gCling->lookupFunctionProto(G, "c", "int,int");
printf("C1: 0x%lx\n", (unsigned long) C1);
//CHECK: C1: 0x{{[1-9a-f][0-9a-f]*$}}
C1->print(llvm::outs());
//CHECK-NEXT: void c(int vi, int vj) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: int y = vj;
//CHECK-NEXT: }
const clang::FunctionDecl* C2 = gCling->lookupFunctionProto(G, "c", "int,double");
printf("C2: 0x%lx\n", (unsigned long) C2);
//CHECK: C2: 0x{{[1-9a-f][0-9a-f]*$}}
C2->print(llvm::outs());
//CHECK-NEXT: void c(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding simple global template instantiations.
//
.rawInput 1
template <class T> void d(T v) { T x = v; }
// Note: In CINT, looking up a class template specialization causes
// instantiation, but looking up a function template specialization
// does not.
template void d(int);
template void d(double);
.rawInput 0
const clang::FunctionDecl* D1 = gCling->lookupFunctionProto(G, "d<int>", "int");
printf("D1: 0x%lx\n", (unsigned long) D1);
//CHECK: D1: 0x{{[1-9a-f][0-9a-f]*$}}
D1->print(llvm::outs());
//CHECK-NEXT: void d(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
const clang::FunctionDecl* D2 = gCling->lookupFunctionProto(G, "d<double>", "double");
printf("D2: 0x%lx\n", (unsigned long) D2);
//CHECK: D2: 0x{{[1-9a-f][0-9a-f]*$}}
D2->print(llvm::outs());
//CHECK-NEXT: void d(double v) {
//CHECK-NEXT: double x = v;
//CHECK-NEXT: }
//
// Test finding a member function taking no args.
//
.rawInput 1
class A {
void A_f() { int x = 1; }
};
.rawInput 0
const clang::Decl* class_A = gCling->lookupScope("A");
printf("class_A: 0x%lx\n", (unsigned long) class_A);
//CHECK: class_A: 0x{{[1-9a-f][0-9a-f]*$}}
const clang::FunctionDecl* class_A_F = gCling->lookupFunctionProto(class_A, "A_f", "");
printf("class_A_F: 0x%lx\n", (unsigned long) class_A_F);
//CHECK-NEXT: class_A_F: 0x{{[1-9a-f][0-9a-f]*$}}
class_A_F->print(llvm::outs());
//CHECK-NEXT: void A_f() {
//CHECK-NEXT: int x = 1;
//CHECK-NEXT: }
//
// Test finding a member function taking an int arg.
//
.rawInput 1
class B {
void B_f(int v) { int x = v; }
};
.rawInput 0
const clang::Decl* class_B = gCling->lookupScope("B");
printf("class_B: 0x%lx\n", (unsigned long) class_B);
//CHECK: class_B: 0x{{[1-9a-f][0-9a-f]*$}}
const clang::FunctionDecl* class_B_F = gCling->lookupFunctionProto(class_B, "B_f", "int");
printf("class_B_F: 0x%lx\n", (unsigned long) class_B_F);
//CHECK-NEXT: class_B_F: 0x{{[1-9a-f][0-9a-f]*$}}
class_B_F->print(llvm::outs());
//CHECK-NEXT: void B_f(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
//
// Test finding a member function taking no args in a base class.
//
.rawInput 1
class C {
void C_f() { int x = 1; }
};
class D : public C {
};
.rawInput 0
const clang::Decl* class_D = gCling->lookupScope("D");
printf("class_D: 0x%lx\n", (unsigned long) class_D);
//CHECK: class_D: 0x{{[1-9a-f][0-9a-f]*$}}
const clang::FunctionDecl* class_D_F = gCling->lookupFunctionProto(class_D, "C_f", "");
printf("class_D_F: 0x%lx\n", (unsigned long) class_D_F);
//CHECK-NEXT: class_D_F: 0x{{[1-9a-f][0-9a-f]*$}}
class_D_F->print(llvm::outs());
//CHECK-NEXT: void C_f() {
//CHECK-NEXT: int x = 1;
//CHECK-NEXT: }
//
// Test finding a member function taking an int arg in a base class.
//
.rawInput 1
class E {
void E_f(int v) { int x = v; }
};
class F : public E {
};
.rawInput 0
const clang::Decl* class_F = gCling->lookupScope("F");
printf("class_F: 0x%lx\n", (unsigned long) class_F);
//CHECK: class_F: 0x{{[1-9a-f][0-9a-f]*$}}
const clang::FunctionDecl* class_F_F = gCling->lookupFunctionProto(class_F, "E_f", "int");
printf("class_F_F: 0x%lx\n", (unsigned long) class_F_F);
//CHECK-NEXT: class_F_F: 0x{{[1-9a-f][0-9a-f]*$}}
class_F_F->print(llvm::outs());
//CHECK-NEXT: void E_f(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
//
// One final check to make sure we are at the right line in the output.
//
"abc"
//CHECK: (const char [4]) @0x{{[0-9a-f]+}}
<commit_msg>Use same tests and test classes as funcargs.C.<commit_after>// RUN: cat %s | %cling 2>&1 | FileCheck %s
// Test Interpreter::lookupFunctionProto()
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/Decl.h"
#include <cstdio>
using namespace std;
//
// We need to fetch the global scope declaration,
// otherwise known as the translation unit decl.
//
const clang::Decl* G = gCling->lookupScope("");
printf("G: 0x%lx\n", (unsigned long) G);
//CHECK: G: 0x{{[1-9a-f][0-9a-f]*$}}
//
// Test finding a global function taking no args.
//
.rawInput 1
void f() { int x = 1; }
void a(int v) { int x = v; }
void b(int vi, double vd) { int x = vi; double y = vd; }
void c(int vi, int vj) { int x = vi; int y = vj; }
void c(int vi, double vd) { int x = vi; double y = vd; }
template <class T> void d(T v) { T x = v; }
// Note: In CINT, looking up a class template specialization causes
// instantiation, but looking up a function template specialization
// does not, so we explicitly request the instantiations we are
// going to lookup so they will be there to find.
template void d(int);
template void d(double);
.rawInput 0
const clang::FunctionDecl* F = gCling->lookupFunctionProto(G, "f", "");
printf("F: 0x%lx\n", (unsigned long) F);
//CHECK-NEXT: F: 0x{{[1-9a-f][0-9a-f]*$}}
F->print(llvm::outs());
//CHECK-NEXT: void f() {
//CHECK-NEXT: int x = 1;
//CHECK-NEXT: }
//
// Test finding a global function taking a single int argument.
//
const clang::FunctionDecl* A = gCling->lookupFunctionProto(G, "a", "int");
printf("A: 0x%lx\n", (unsigned long) A);
//CHECK: A: 0x{{[1-9a-f][0-9a-f]*$}}
A->print(llvm::outs());
//CHECK-NEXT: void a(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
//
// Test finding a global function taking an int and a double argument.
//
const clang::FunctionDecl* B = gCling->lookupFunctionProto(G, "b", "int,double");
printf("B: 0x%lx\n", (unsigned long) B);
//CHECK: B: 0x{{[1-9a-f][0-9a-f]*$}}
B->print(llvm::outs());
//CHECK-NEXT: void b(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding a global overloaded function.
//
const clang::FunctionDecl* C1 = gCling->lookupFunctionProto(G, "c", "int,int");
printf("C1: 0x%lx\n", (unsigned long) C1);
//CHECK: C1: 0x{{[1-9a-f][0-9a-f]*$}}
C1->print(llvm::outs());
//CHECK-NEXT: void c(int vi, int vj) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: int y = vj;
//CHECK-NEXT: }
const clang::FunctionDecl* C2 = gCling->lookupFunctionProto(G, "c", "int,double");
printf("C2: 0x%lx\n", (unsigned long) C2);
//CHECK: C2: 0x{{[1-9a-f][0-9a-f]*$}}
C2->print(llvm::outs());
//CHECK-NEXT: void c(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding simple global template instantiations.
//
const clang::FunctionDecl* D1 = gCling->lookupFunctionProto(G, "d<int>", "int");
printf("D1: 0x%lx\n", (unsigned long) D1);
//CHECK: D1: 0x{{[1-9a-f][0-9a-f]*$}}
D1->print(llvm::outs());
//CHECK-NEXT: void d(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
const clang::FunctionDecl* D2 = gCling->lookupFunctionProto(G, "d<double>", "double");
printf("D2: 0x%lx\n", (unsigned long) D2);
//CHECK: D2: 0x{{[1-9a-f][0-9a-f]*$}}
D2->print(llvm::outs());
//CHECK-NEXT: void d(double v) {
//CHECK-NEXT: double x = v;
//CHECK-NEXT: }
.rawInput 1
class B {
void B_f() { int x = 1; }
void B_g(int v) { int x = v; }
void B_h(int vi, double vd) { int x = vi; double y = vd; }
void B_j(int vi, int vj) { int x = vi; int y = vj; }
void B_j(int vi, double vd) { int x = vi; double y = vd; }
template <class T> void B_k(T v) { T x = v; }
};
class A : public B {
void A_f() { int x = 1; }
void A_g(int v) { int x = v; }
void A_h(int vi, double vd) { int x = vi; double y = vd; }
void A_j(int vi, int vj) { int x = vi; int y = vj; }
void A_j(int vi, double vd) { int x = vi; double y = vd; }
template <class T> void A_k(T v) { T x = v; }
};
// Note: In CINT, looking up a class template specialization causes
// instantiation, but looking up a function template specialization
// does not, so we explicitly request the instantiations we are
// going to lookup so they will be there to find.
template void A::A_k(int);
template void A::A_k(double);
template void A::B_k(int);
template void A::B_k(double);
.rawInput 0
const clang::Decl* class_A = gCling->lookupScope("A");
printf("class_A: 0x%lx\n", (unsigned long) class_A);
//CHECK: class_A: 0x{{[1-9a-f][0-9a-f]*$}}
const clang::Decl* class_B = gCling->lookupScope("B");
printf("class_B: 0x%lx\n", (unsigned long) class_B);
//CHECK-NEXT: class_B: 0x{{[1-9a-f][0-9a-f]*$}}
//
// Test finding a member function taking no args.
//
const clang::FunctionDecl* class_A_F = gCling->lookupFunctionProto(class_A, "A_f", "");
printf("class_A_F: 0x%lx\n", (unsigned long) class_A_F);
//CHECK-NEXT: class_A_F: 0x{{[1-9a-f][0-9a-f]*$}}
class_A_F->print(llvm::outs());
//CHECK-NEXT: void A_f() {
//CHECK-NEXT: int x = 1;
//CHECK-NEXT: }
//
// Test finding a member function taking an int arg.
//
const clang::FunctionDecl* func_A_g = gCling->lookupFunctionProto(class_A, "A_g", "int");
printf("func_A_g: 0x%lx\n", (unsigned long) func_A_g);
//CHECK: func_A_g: 0x{{[1-9a-f][0-9a-f]*$}}
func_A_g->print(llvm::outs());
//CHECK-NEXT: void A_g(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
//
// Test finding a member function taking an int and a double argument.
//
const clang::FunctionDecl* func_A_h = gCling->lookupFunctionProto(class_A, "A_h", "int,double");
printf("func_A_h: 0x%lx\n", (unsigned long) func_A_h);
//CHECK: func_A_h: 0x{{[1-9a-f][0-9a-f]*$}}
func_A_h->print(llvm::outs());
//CHECK-NEXT: void A_h(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding an overloaded member function.
//
const clang::FunctionDecl* func_A_j1 = gCling->lookupFunctionProto(class_A, "A_j", "int,int");
printf("func_A_j1: 0x%lx\n", (unsigned long) func_A_j1);
//CHECK: func_A_j1: 0x{{[1-9a-f][0-9a-f]*$}}
func_A_j1->print(llvm::outs());
//CHECK-NEXT: void A_j(int vi, int vj) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: int y = vj;
//CHECK-NEXT: }
const clang::FunctionDecl* func_A_j2 = gCling->lookupFunctionProto(class_A, "A_j", "int,double");
printf("func_A_j2: 0x%lx\n", (unsigned long) func_A_j2);
//CHECK: func_A_j2: 0x{{[1-9a-f][0-9a-f]*$}}
func_A_j2->print(llvm::outs());
//CHECK-NEXT: void A_j(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding simple member function template instantiations.
//
const clang::FunctionDecl* func_A_k1 = gCling->lookupFunctionProto(class_A, "A_k<int>", "int");
printf("func_A_k1: 0x%lx\n", (unsigned long) func_A_k1);
//CHECK: func_A_k1: 0x{{[1-9a-f][0-9a-f]*$}}
func_A_k1->print(llvm::outs());
//CHECK-NEXT: void A_k(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
const clang::FunctionDecl* func_A_k2 = gCling->lookupFunctionProto(class_A, "A_k<double>", "double");
printf("func_A_k2: 0x%lx\n", (unsigned long) func_A_k2);
//CHECK: func_A_k2: 0x{{[1-9a-f][0-9a-f]*$}}
func_A_k2->print(llvm::outs());
//CHECK-NEXT: void A_k(double v) {
//CHECK-NEXT: double x = v;
//CHECK-NEXT: }
//
// Test finding a member function taking no args in a base class.
//
const clang::FunctionDecl* func_B_F = gCling->lookupFunctionProto(class_A, "B_f", "");
printf("func_B_F: 0x%lx\n", (unsigned long) func_B_F);
//CHECK: func_B_F: 0x{{[1-9a-f][0-9a-f]*$}}
func_B_F->print(llvm::outs());
//CHECK-NEXT: void B_f() {
//CHECK-NEXT: int x = 1;
//CHECK-NEXT: }
//
// Test finding a member function taking an int arg in a base class.
//
const clang::FunctionDecl* func_B_G = gCling->lookupFunctionProto(class_A, "B_g", "int");
printf("func_B_G: 0x%lx\n", (unsigned long) func_B_G);
//CHECK: func_B_G: 0x{{[1-9a-f][0-9a-f]*$}}
func_B_G->print(llvm::outs());
//CHECK-NEXT: void B_g(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
//
// Test finding a member function taking an int and a double argument
// in a base class.
//
const clang::FunctionDecl* func_B_h = gCling->lookupFunctionProto(class_A, "B_h", "int,double");
printf("func_B_h: 0x%lx\n", (unsigned long) func_B_h);
//CHECK: func_B_h: 0x{{[1-9a-f][0-9a-f]*$}}
func_B_h->print(llvm::outs());
//CHECK-NEXT: void B_h(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding an overloaded member function in a base class.
//
const clang::FunctionDecl* func_B_j1 = gCling->lookupFunctionProto(class_A, "B_j", "int,int");
printf("func_B_j1: 0x%lx\n", (unsigned long) func_B_j1);
//CHECK: func_B_j1: 0x{{[1-9a-f][0-9a-f]*$}}
func_B_j1->print(llvm::outs());
//CHECK-NEXT: void B_j(int vi, int vj) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: int y = vj;
//CHECK-NEXT: }
const clang::FunctionDecl* func_B_j2 = gCling->lookupFunctionProto(class_A, "B_j", "int,double");
printf("func_B_j2: 0x%lx\n", (unsigned long) func_B_j2);
//CHECK: func_B_j2: 0x{{[1-9a-f][0-9a-f]*$}}
func_B_j2->print(llvm::outs());
//CHECK-NEXT: void B_j(int vi, double vd) {
//CHECK-NEXT: int x = vi;
//CHECK-NEXT: double y = vd;
//CHECK-NEXT: }
//
// Test finding simple member function template instantiations in a base class.
//
const clang::FunctionDecl* func_B_k1 = gCling->lookupFunctionProto(class_A, "B_k<int>", "int");
printf("func_B_k1: 0x%lx\n", (unsigned long) func_B_k1);
//CHECK: func_B_k1: 0x{{[1-9a-f][0-9a-f]*$}}
func_B_k1->print(llvm::outs());
//CHECK-NEXT: void B_k(int v) {
//CHECK-NEXT: int x = v;
//CHECK-NEXT: }
const clang::FunctionDecl* func_B_k2 = gCling->lookupFunctionProto(class_A, "B_k<double>", "double");
printf("func_B_k2: 0x%lx\n", (unsigned long) func_B_k2);
//CHECK: func_B_k2: 0x{{[1-9a-f][0-9a-f]*$}}
func_B_k2->print(llvm::outs());
//CHECK-NEXT: void B_k(double v) {
//CHECK-NEXT: double x = v;
//CHECK-NEXT: }
//
// One final check to make sure we are at the right line in the output.
//
"abc"
//CHECK: (const char [4]) @0x{{[0-9a-f]+}}
<|endoftext|> |
<commit_before>// Created by filipecn on 3/3/18.
#include <circe/circe.h>
#define WIDTH 800
#define HEIGHT 800
const char *fs = "#version 440 core\n"
"out vec4 outColor;"
"in vec2 texCoord;"
"uniform sampler2D tex;"
"void main() {"
"ivec2 texel = ivec2(gl_FragCoord.xy);"
"outColor = (texelFetchOffset(tex, texel, 0, ivec2(0, 0)) +"
"texelFetchOffset(tex, texel, 0, ivec2(1, 1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(0, 1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(-1, 1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(-1, 0)) +"
"texelFetchOffset(tex, texel, 0, ivec2(1, 0)) +"
"texelFetchOffset(tex, texel, 0, ivec2(-1, -1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(1, -1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(0, -1))) / 9.0;"
"}";
int main() {
circe::gl::SceneApp<> app(WIDTH, HEIGHT, "Post Effects Example");
app.init();
app.viewports[0].renderer->addEffect(new circe::gl::GammaCorrection());
// app.viewports[0].renderer->addEffect(new circe::FXAA());
// app.viewports[0].renderer->addEffect(new circe::PostEffect(
// new circe::Shader(circe_NO_VAO_VS, nullptr, fs)));
std::shared_ptr<circe::gl::CartesianGrid> grid(
app.scene.add<circe::gl::CartesianGrid>(new circe::gl::CartesianGrid(5)));
app.run();
return 0;
}<commit_msg>fix circe example<commit_after>// Created by filipecn on 3/3/18.
#include <circe/circe.h>
#define WIDTH 800
#define HEIGHT 800
const char *fs = "#version 440 core\n"
"out vec4 outColor;"
"in vec2 texCoord;"
"uniform sampler2D tex;"
"void main() {"
"ivec2 texel = ivec2(gl_FragCoord.xy);"
"outColor = (texelFetchOffset(tex, texel, 0, ivec2(0, 0)) +"
"texelFetchOffset(tex, texel, 0, ivec2(1, 1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(0, 1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(-1, 1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(-1, 0)) +"
"texelFetchOffset(tex, texel, 0, ivec2(1, 0)) +"
"texelFetchOffset(tex, texel, 0, ivec2(-1, -1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(1, -1)) +"
"texelFetchOffset(tex, texel, 0, ivec2(0, -1))) / 9.0;"
"}";
int main() {
circe::gl::SceneApp<> app(WIDTH, HEIGHT, "Post Effects Example");
app.init();
app.viewports[0].renderer->addEffect(new circe::gl::GammaCorrection());
// app.viewports[0].renderer->addEffect(new circe::FXAA());
// app.viewports[0].renderer->addEffect(new circe::PostEffect(
// new circe::Shader(circe_NO_VAO_VS, nullptr, fs)));
app.scene.add(new circe::gl::CartesianGrid(5));
app.run();
return 0;
}<|endoftext|> |
<commit_before>//===-- sdbcoreC.cpp ----------------------------------------------------------------*- C++ -*-===//
//
// S E R I A L B O X
//
// This file is distributed under terms of BSD license.
// See LICENSE.txt for more information
//
//===------------------------------------------------------------------------------------------===//
//
/// \file
/// This file contains utility functions for the sdb core library
///
//===------------------------------------------------------------------------------------------===//
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#include <vector>
#include <iostream>
#include <cmath>
namespace {
template <class T>
class NumpyArray {
public:
NumpyArray(PyArrayObject* array)
: data_((T*)PyArray_DATA(array)), size_(PyArray_SIZE(array)),
shape_(PyArray_DIMS(array), PyArray_DIMS(array) + PyArray_NDIM(array)) {}
/// \brief Access data pointer
const T* data() const noexcept { return data_; }
T* data() noexcept { return data_; }
/// \brief Shape of the numpy array
const std::vector<npy_intp>& shape() const noexcept { return shape_; }
/// \brief Size of the array
npy_intp size() const noexcept { return size_; }
/// \brief Convert to string
friend std::ostream& operator<<(std::ostream& stream, const NumpyArray& array) {
stream << "shape = [ ";
for(const auto& s : array.shape())
stream << s << " ";
stream << "], size = " << array.size() << ", data = " << array.data();
return stream;
}
private:
T* data_;
npy_intp size_;
std::vector<npy_intp> shape_;
};
template <class T>
struct ErrorList {
std::vector<int> index;
T input_value;
T reference_value;
};
/// \brief Compute positions of errors of input and reference fields
///
/// The error_position field is set to True if
///
/// absolute(input - reference) <= (atol + rtol * absolute(reference))
///
/// evaluates to False.
template <class T>
inline int compute_error_positions(const NumpyArray<T>& input, const NumpyArray<T>& reference,
NumpyArray<bool>& error_positions, const double& atol,
const double& rtol) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
bool* error_positions_ptr = error_positions.data();
int num_errors = 0;
for(int i = 0; i < size; ++i) {
const T a = input_ptr[i];
const T b = reference_ptr[i];
const bool res = !(std::abs(a - b) <= (atol + rtol * std::abs(b)));
num_errors += res;
error_positions_ptr[i] = res;
}
return num_errors;
}
inline void increment_index(std::vector<int>& index, const std::vector<npy_intp>& shape) noexcept {
const int size = index.size();
for(int i = 0; i < size; ++i)
if(++index[i] < shape[i])
break;
else
index[i] = 0;
}
/// \brief Compute list of errors with elements (index, input_value, reference_value)
template <class T>
inline void compute_error_list(const NumpyArray<T>& input, const NumpyArray<T>& reference,
const NumpyArray<bool>& error_positions,
std::vector<ErrorList<T>>& error_list) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
const bool* error_positions_ptr = error_positions.data();
const std::vector<npy_intp>& shape = input.shape();
std::vector<int> index(input.shape().size(), 0);
int error_list_idx = 0;
for(int i = 0; i < size; ++i, increment_index(index, shape)) {
if(error_positions_ptr[i]) {
error_list[error_list_idx].index = index;
error_list[error_list_idx].input_value = input_ptr[i];
error_list[error_list_idx].reference_value = reference_ptr[i];
error_list_idx++;
}
}
}
} // anonymous namespace
/// \brief Compute the list of errors and positions
static PyObject* sdbcoreC_make_error_list_c(PyObject* self, PyObject* args) {
PyObject* input_field;
PyArrayObject* input_array;
PyObject* reference_field;
PyArrayObject* reference_array;
PyArrayObject* error_positions_array = NULL;
PyObject* error_list_object = NULL;
double atol;
double rtol;
//
// Parse arguments
//
if(!PyArg_ParseTuple(args, "OOdd", &input_field, &reference_field, &atol, &rtol))
return NULL;
try {
//
// Extract numpy arrays
//
if(!(input_array =
(PyArrayObject*)PyArray_FROM_OTF(input_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract input array");
if(!(reference_array =
(PyArrayObject*)PyArray_FROM_OTF(reference_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract reference array");
NumpyArray<double> input(input_array);
NumpyArray<double> reference(reference_array);
if(input.shape() != reference.shape())
throw std::runtime_error("internal error: dimension mismatch");
//
// Allocate error positions array (boolean array)
//
error_positions_array = (PyArrayObject*)PyArray_SimpleNew(PyArray_NDIM(input_array),
PyArray_DIMS(input_array), NPY_BOOL);
NumpyArray<bool> error_positions(error_positions_array);
//
// Compute error positions
//
int num_errors = compute_error_positions(input, reference, error_positions, atol, rtol);
//
// Allocate list of errors
//
std::vector<ErrorList<double>> error_list(num_errors);
error_list_object = PyList_New(error_list.size());
//
// Compute list of errors
//
compute_error_list(input, reference, error_positions, error_list);
//
// Prepare return
//
for(int i = 0; i < error_list.size(); ++i) {
PyObject* list_element = PyList_New(3);
PyObject* index_list = PyList_New(error_list[i].index.size());
const int index_size = error_list[i].index.size();
for(int ii = 0; ii < error_list[i].index.size(); ++ii)
PyList_SetItem(index_list, ii, PyLong_FromLong(error_list[i].index[index_size - 1 - ii]));
PyList_SetItem(list_element, 0, index_list);
PyList_SetItem(list_element, 1, PyFloat_FromDouble(error_list[i].input_value));
PyList_SetItem(list_element, 2, PyFloat_FromDouble(error_list[i].reference_value));
PyList_SetItem(error_list_object, i, list_element);
}
} catch(std::runtime_error& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
Py_XDECREF(input_array);
Py_XDECREF(reference_array);
if(error_list_object)
Py_XDECREF(error_list_object);
if(error_positions_array)
Py_XDECREF(error_positions_array);
return NULL;
}
return Py_BuildValue("OO", error_list_object, error_positions_array);
}
//===------------------------------------------------------------------------------------------===//
// Module definitions
//===------------------------------------------------------------------------------------------===//
// Method specification
static PyMethodDef module_methods[] = {
{"make_error_list_c", sdbcoreC_make_error_list_c, METH_VARARGS, ""}, {NULL, NULL, 0, NULL}};
// Module specification
static struct PyModuleDef sdbcoreC_module_definition = {
PyModuleDef_HEAD_INIT, "sdbcoreC", "This module provides C extensions to the sdbcore module.",
-1, module_methods};
// Initialize the sdbcoreC module
PyMODINIT_FUNC PyInit_sdbcoreC(void) {
Py_Initialize();
import_array();
return PyModule_Create(&sdbcoreC_module_definition);
}
<commit_msg>clang format<commit_after>//===-- sdbcoreC.cpp ----------------------------------------------------------------*- C++ -*-===//
//
// S E R I A L B O X
//
// This file is distributed under terms of BSD license.
// See LICENSE.txt for more information
//
//===------------------------------------------------------------------------------------------===//
//
/// \file
/// This file contains utility functions for the sdb core library
///
//===------------------------------------------------------------------------------------------===//
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#include <cmath>
#include <iostream>
#include <vector>
namespace {
template <class T>
class NumpyArray {
public:
NumpyArray(PyArrayObject* array)
: data_((T*)PyArray_DATA(array)), size_(PyArray_SIZE(array)),
shape_(PyArray_DIMS(array), PyArray_DIMS(array) + PyArray_NDIM(array)) {}
/// \brief Access data pointer
const T* data() const noexcept { return data_; }
T* data() noexcept { return data_; }
/// \brief Shape of the numpy array
const std::vector<npy_intp>& shape() const noexcept { return shape_; }
/// \brief Size of the array
npy_intp size() const noexcept { return size_; }
/// \brief Convert to string
friend std::ostream& operator<<(std::ostream& stream, const NumpyArray& array) {
stream << "shape = [ ";
for(const auto& s : array.shape())
stream << s << " ";
stream << "], size = " << array.size() << ", data = " << array.data();
return stream;
}
private:
T* data_;
npy_intp size_;
std::vector<npy_intp> shape_;
};
template <class T>
struct ErrorList {
std::vector<int> index;
T input_value;
T reference_value;
};
/// \brief Compute positions of errors of input and reference fields
///
/// The error_position field is set to True if
///
/// absolute(input - reference) <= (atol + rtol * absolute(reference))
///
/// evaluates to False.
template <class T>
inline int compute_error_positions(const NumpyArray<T>& input, const NumpyArray<T>& reference,
NumpyArray<bool>& error_positions, const double& atol,
const double& rtol) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
bool* error_positions_ptr = error_positions.data();
int num_errors = 0;
for(int i = 0; i < size; ++i) {
const T a = input_ptr[i];
const T b = reference_ptr[i];
const bool res = !(std::abs(a - b) <= (atol + rtol * std::abs(b)));
num_errors += res;
error_positions_ptr[i] = res;
}
return num_errors;
}
inline void increment_index(std::vector<int>& index, const std::vector<npy_intp>& shape) noexcept {
const int size = index.size();
for(int i = 0; i < size; ++i)
if(++index[i] < shape[i])
break;
else
index[i] = 0;
}
/// \brief Compute list of errors with elements (index, input_value, reference_value)
template <class T>
inline void compute_error_list(const NumpyArray<T>& input, const NumpyArray<T>& reference,
const NumpyArray<bool>& error_positions,
std::vector<ErrorList<T>>& error_list) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
const bool* error_positions_ptr = error_positions.data();
const std::vector<npy_intp>& shape = input.shape();
std::vector<int> index(input.shape().size(), 0);
int error_list_idx = 0;
for(int i = 0; i < size; ++i, increment_index(index, shape)) {
if(error_positions_ptr[i]) {
error_list[error_list_idx].index = index;
error_list[error_list_idx].input_value = input_ptr[i];
error_list[error_list_idx].reference_value = reference_ptr[i];
error_list_idx++;
}
}
}
} // anonymous namespace
/// \brief Compute the list of errors and positions
static PyObject* sdbcoreC_make_error_list_c(PyObject* self, PyObject* args) {
PyObject* input_field;
PyArrayObject* input_array;
PyObject* reference_field;
PyArrayObject* reference_array;
PyArrayObject* error_positions_array = NULL;
PyObject* error_list_object = NULL;
double atol;
double rtol;
//
// Parse arguments
//
if(!PyArg_ParseTuple(args, "OOdd", &input_field, &reference_field, &atol, &rtol))
return NULL;
try {
//
// Extract numpy arrays
//
if(!(input_array =
(PyArrayObject*)PyArray_FROM_OTF(input_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract input array");
if(!(reference_array =
(PyArrayObject*)PyArray_FROM_OTF(reference_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract reference array");
NumpyArray<double> input(input_array);
NumpyArray<double> reference(reference_array);
if(input.shape() != reference.shape())
throw std::runtime_error("internal error: dimension mismatch");
//
// Allocate error positions array (boolean array)
//
error_positions_array = (PyArrayObject*)PyArray_SimpleNew(PyArray_NDIM(input_array),
PyArray_DIMS(input_array), NPY_BOOL);
NumpyArray<bool> error_positions(error_positions_array);
//
// Compute error positions
//
int num_errors = compute_error_positions(input, reference, error_positions, atol, rtol);
//
// Allocate list of errors
//
std::vector<ErrorList<double>> error_list(num_errors);
error_list_object = PyList_New(error_list.size());
//
// Compute list of errors
//
compute_error_list(input, reference, error_positions, error_list);
//
// Prepare return
//
for(int i = 0; i < error_list.size(); ++i) {
PyObject* list_element = PyList_New(3);
PyObject* index_list = PyList_New(error_list[i].index.size());
const int index_size = error_list[i].index.size();
for(int ii = 0; ii < error_list[i].index.size(); ++ii)
PyList_SetItem(index_list, ii, PyLong_FromLong(error_list[i].index[index_size - 1 - ii]));
PyList_SetItem(list_element, 0, index_list);
PyList_SetItem(list_element, 1, PyFloat_FromDouble(error_list[i].input_value));
PyList_SetItem(list_element, 2, PyFloat_FromDouble(error_list[i].reference_value));
PyList_SetItem(error_list_object, i, list_element);
}
} catch(std::runtime_error& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
Py_XDECREF(input_array);
Py_XDECREF(reference_array);
if(error_list_object)
Py_XDECREF(error_list_object);
if(error_positions_array)
Py_XDECREF(error_positions_array);
return NULL;
}
return Py_BuildValue("OO", error_list_object, error_positions_array);
}
//===------------------------------------------------------------------------------------------===//
// Module definitions
//===------------------------------------------------------------------------------------------===//
// Method specification
static PyMethodDef module_methods[] = {
{"make_error_list_c", sdbcoreC_make_error_list_c, METH_VARARGS, ""}, {NULL, NULL, 0, NULL}};
// Module specification
static struct PyModuleDef sdbcoreC_module_definition = {
PyModuleDef_HEAD_INIT, "sdbcoreC", "This module provides C extensions to the sdbcore module.",
-1, module_methods};
// Initialize the sdbcoreC module
PyMODINIT_FUNC PyInit_sdbcoreC(void) {
Py_Initialize();
import_array();
return PyModule_Create(&sdbcoreC_module_definition);
}
<|endoftext|> |
<commit_before>#include "net/RawSocket.h"
#include "common/RhodesApp.h"
#include <algorithm>
#if !defined(OS_WINDOWS) && !defined(OS_WINCE)
#include <arpa/inet.h>
#endif
#if !defined(OS_WINCE)
#include <common/stat.h>
#ifdef EAGAIN
#undef EAGAIN
#endif
#define EAGAIN EWOULDBLOCK
#else
#include "CompatWince.h"
#if defined(OS_WINDOWS) || defined(OS_WINCE)
typedef unsigned __int16 uint16_t;
# ifndef S_ISDIR
# define S_ISDIR(m) ((_S_IFDIR & m) == _S_IFDIR)
# endif
# ifndef S_ISREG
# define S_ISREG(m) ((_S_IFREG & m) == _S_IFREG)
# endif
# ifndef EAGAIN
# define EAGAIN WSAEWOULDBLOCK
# endif
#endif
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "RawSocket"
namespace rho
{
namespace net
{
bool RawSocket::init()
{
RAWTRACE("Init raw socket");
m_isInit = create();
return m_isInit;
}
bool RawSocket::create()
{
RAWTRACE("Start create raw socket");
cleanup();
int iResult;
addrinfo *addrInfo = NULL, hints;
memset( &hints, 0, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
RAWTRACE("Get host adress");
// Resolve the server address and port
iResult = getaddrinfo(m_hostName.c_str(), m_hostPort.c_str(), &hints, &addrInfo);
if (iResult != 0) {
RAWTRACE2("Unable to get addres info for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
return false;
}
RAWTRACE("Create socket");
// Create a SOCKET for connecting to server
m_clientSocket = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);
if (m_clientSocket == INVALID_SOCKET) {
RAWTRACE2("Socket can`t create for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
freeaddrinfo(addrInfo);
return false;
}
// Connect to server.
RAWTRACE("Connect to server");
iResult = connect(m_clientSocket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen);
if (iResult == SOCKET_ERROR) {
RAWTRACE2("Can`t connect to host %s, port %s ", m_hostName.c_str(), m_hostPort.c_str());
cleanup();
return false;
}
freeaddrinfo(addrInfo);
RAWTRACE("End of socket creating");
return true;
}
bool RawSocket::send(const String& sendData)
{
int iResult = 0;
// Send an initial buffer
iResult = ::send(m_clientSocket, sendData.c_str(), (int) sendData.size(), 0);
if (iResult == SOCKET_ERROR)
{
RAWTRACE2("Data not send for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
cleanup();
return false;
}
return true;
}
void RawSocket::cleanup()
{
m_isInit = false;
closesocket(m_clientSocket);
m_clientSocket = INVALID_SOCKET;
}
} // namespace net
} // namespace rho
#endif<commit_msg>fix raw socket<commit_after>#include "net/RawSocket.h"
#include "common/RhodesApp.h"
#include <algorithm>
#if !defined(OS_WINDOWS) && !defined(OS_WINCE)
#include <arpa/inet.h>
#endif
#if !defined(OS_WINCE)
#include <common/stat.h>
#ifdef EAGAIN
#undef EAGAIN
#endif
#define EAGAIN EWOULDBLOCK
#else
#include "CompatWince.h"
#if defined(OS_WINDOWS) || defined(OS_WINCE)
typedef unsigned __int16 uint16_t;
# ifndef S_ISDIR
# define S_ISDIR(m) ((_S_IFDIR & m) == _S_IFDIR)
# endif
# ifndef S_ISREG
# define S_ISREG(m) ((_S_IFREG & m) == _S_IFREG)
# endif
# ifndef EAGAIN
# define EAGAIN WSAEWOULDBLOCK
# endif
#endif
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "RawSocket"
namespace rho
{
namespace net
{
bool RawSocket::init()
{
//RAWTRACE("Init raw socket");
m_isInit = create();
return m_isInit;
}
bool RawSocket::create()
{
//RAWTRACE("Start create raw socket");
cleanup();
int iResult;
addrinfo *addrInfo = NULL, hints;
memset( &hints, 0, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
//RAWTRACE("Get host adress");
// Resolve the server address and port
iResult = getaddrinfo(m_hostName.c_str(), m_hostPort.c_str(), &hints, &addrInfo);
if (iResult != 0) {
//RAWTRACE2("Unable to get addres info for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
return false;
}
//RAWTRACE("Create socket");
// Create a SOCKET for connecting to server
m_clientSocket = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);
if (m_clientSocket == INVALID_SOCKET) {
//RAWTRACE2("Socket can`t create for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
freeaddrinfo(addrInfo);
return false;
}
// Connect to server.
//RAWTRACE("Connect to server");
iResult = connect(m_clientSocket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen);
if (iResult == SOCKET_ERROR) {
//RAWTRACE2("Can`t connect to host %s, port %s ", m_hostName.c_str(), m_hostPort.c_str());
cleanup();
return false;
}
freeaddrinfo(addrInfo);
//RAWTRACE("End of socket creating");
return true;
}
bool RawSocket::send(const String& sendData)
{
int iResult = 0;
// Send an initial buffer
iResult = ::send(m_clientSocket, sendData.c_str(), (int) sendData.size(), 0);
if (iResult == SOCKET_ERROR)
{
//RAWTRACE2("Data not send for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
cleanup();
return false;
}
return true;
}
void RawSocket::cleanup()
{
m_isInit = false;
closesocket(m_clientSocket);
m_clientSocket = INVALID_SOCKET;
}
} // namespace net
} // namespace rho
#endif<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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 "SurgSim/Graphics/OsgManager.h"
#include <vector>
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Graphics/OsgRepresentation.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgScreenSpacePass.h"
#include <osgViewer/Scene>
#include <osgDB/WriteFile>
using SurgSim::Graphics::OsgRepresentation;
using SurgSim::Graphics::OsgCamera;
using SurgSim::Graphics::OsgGroup;
using SurgSim::Graphics::OsgManager;
namespace SurgSim
{
namespace Graphics
{
OsgManager::OsgManager() : SurgSim::Graphics::Manager(),
m_viewer(new osgViewer::CompositeViewer())
{
}
OsgManager::~OsgManager()
{
}
std::shared_ptr<Group> OsgManager::getOrCreateGroup(const std::string& name)
{
std::shared_ptr<Group> result;
auto groups = getGroups();
auto group = groups.find(name);
if (group == std::end(groups))
{
auto newGroup = std::make_shared<OsgGroup>(name);
addGroup(newGroup);
result = newGroup;
}
else
{
result = group->second;
}
return result;
}
bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation)
{
std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation);
bool result;
if (osgRepresentation)
{
result = Manager::addRepresentation(osgRepresentation);
}
else
{
SURGSIM_LOG_INFO(getLogger())
<< __FUNCTION__ << " Representation is not a subclass of OsgRepresentation "
<< representation->getName();
result = false;
}
return result;
}
bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view)
{
std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
bool result = true;
if (osgView == nullptr)
{
SURGSIM_LOG_WARNING(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName();
result = false;
}
else
{
SURGSIM_ASSERT(view->getCamera() != nullptr) << "View should have a camera when added to the manager.";
if (Manager::addView(view))
{
m_viewer->addView(osgView->getOsgView());
}
}
return result;
}
bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view)
{
std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
if (osgView)
{
m_viewer->removeView(osgView->getOsgView());
}
return Manager::removeView(view);
}
bool OsgManager::doInitialize()
{
m_hudElement = std::make_shared<OsgScreenSpacePass>(Representation::DefaultHudGroupName);
return true;
}
bool OsgManager::doStartUp()
{
return true;
}
bool OsgManager::doUpdate(double dt)
{
// There is a bug in the scene initialisation where addSceneElement() will not be correctly executed if
// performed inside of doInitialize(), this needs to be fixed
// HS-2014-dec-12
// #workaround
if (!m_hudElement->isInitialized())
{
getRuntime()->getScene()->addSceneElement(m_hudElement);
}
if (Manager::doUpdate(dt))
{
m_viewer->frame();
// \note HS-2013-dec-12 This will work as long as we deal with one view, when we move to stereoscopic
// we might have to revise things. Or just assume that most views have the same size
if (m_viewer->getNumViews() > 0)
{
auto dimensions = getViews()[0]->getDimensions();
m_hudElement->setViewPort(dimensions[0], dimensions[1]);
}
return true;
}
else
{
return false;
}
}
void OsgManager::doBeforeStop()
{
dumpDebugInfo();
// Delete the viewer so that the graphics context will be released in the manager's thread
m_viewer = nullptr;
}
osg::ref_ptr<osgViewer::CompositeViewer> OsgManager::getOsgCompositeViewer() const
{
return m_viewer;
}
void SurgSim::Graphics::OsgManager::dumpDebugInfo() const
{
osgDB::writeNodeFile(*m_viewer->getView(0)->getCamera(), "viewer_zero_camera.osgt");
}
}
}
<commit_msg>Prevent OsgManager from dumping out its scenegraph automatically when not in debug<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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 "SurgSim/Graphics/OsgManager.h"
#include <vector>
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Graphics/OsgRepresentation.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgScreenSpacePass.h"
#include <osgViewer/Scene>
#include <osgDB/WriteFile>
using SurgSim::Graphics::OsgRepresentation;
using SurgSim::Graphics::OsgCamera;
using SurgSim::Graphics::OsgGroup;
using SurgSim::Graphics::OsgManager;
namespace SurgSim
{
namespace Graphics
{
OsgManager::OsgManager() : SurgSim::Graphics::Manager(),
m_viewer(new osgViewer::CompositeViewer())
{
}
OsgManager::~OsgManager()
{
}
std::shared_ptr<Group> OsgManager::getOrCreateGroup(const std::string& name)
{
std::shared_ptr<Group> result;
auto groups = getGroups();
auto group = groups.find(name);
if (group == std::end(groups))
{
auto newGroup = std::make_shared<OsgGroup>(name);
addGroup(newGroup);
result = newGroup;
}
else
{
result = group->second;
}
return result;
}
bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation)
{
std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation);
bool result;
if (osgRepresentation)
{
result = Manager::addRepresentation(osgRepresentation);
}
else
{
SURGSIM_LOG_INFO(getLogger())
<< __FUNCTION__ << " Representation is not a subclass of OsgRepresentation "
<< representation->getName();
result = false;
}
return result;
}
bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view)
{
std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
bool result = true;
if (osgView == nullptr)
{
SURGSIM_LOG_WARNING(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName();
result = false;
}
else
{
SURGSIM_ASSERT(view->getCamera() != nullptr) << "View should have a camera when added to the manager.";
if (Manager::addView(view))
{
m_viewer->addView(osgView->getOsgView());
}
}
return result;
}
bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view)
{
std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
if (osgView)
{
m_viewer->removeView(osgView->getOsgView());
}
return Manager::removeView(view);
}
bool OsgManager::doInitialize()
{
m_hudElement = std::make_shared<OsgScreenSpacePass>(Representation::DefaultHudGroupName);
return true;
}
bool OsgManager::doStartUp()
{
return true;
}
bool OsgManager::doUpdate(double dt)
{
// There is a bug in the scene initialisation where addSceneElement() will not be correctly executed if
// performed inside of doInitialize(), this needs to be fixed
// HS-2014-dec-12
// #workaround
if (!m_hudElement->isInitialized())
{
getRuntime()->getScene()->addSceneElement(m_hudElement);
}
if (Manager::doUpdate(dt))
{
m_viewer->frame();
// \note HS-2013-dec-12 This will work as long as we deal with one view, when we move to stereoscopic
// we might have to revise things. Or just assume that most views have the same size
if (m_viewer->getNumViews() > 0)
{
auto dimensions = getViews()[0]->getDimensions();
m_hudElement->setViewPort(dimensions[0], dimensions[1]);
}
return true;
}
else
{
return false;
}
}
void OsgManager::doBeforeStop()
{
#ifdef OSS_DEBUG
dumpDebugInfo();
#endif
// Delete the viewer so that the graphics context will be released in the manager's thread
m_viewer = nullptr;
}
osg::ref_ptr<osgViewer::CompositeViewer> OsgManager::getOsgCompositeViewer() const
{
return m_viewer;
}
void SurgSim::Graphics::OsgManager::dumpDebugInfo() const
{
osgDB::writeNodeFile(*m_viewer->getView(0)->getCamera(), "viewer_zero_camera.osgt");
}
}
}
<|endoftext|> |
<commit_before>#ifndef ITERTOOLS_HPP
#define ITERTOOLS_HPP
#include "chain.hpp"
#include "combinations.hpp"
#include "combinations_with_replacement.hpp"
#include "compress.hpp"
#include "count.hpp"
#include "cycle.hpp"
#include "dropwhile.hpp"
#include "enumerate.hpp"
#include "filter.hpp"
#include "filterfalse.hpp"
#include "groupby.hpp"
#include "grouper.hpp"
#include "imap.hpp"
#include "iterator_range.hpp"
#include "sliding_window.hpp"
#include "permutations.hpp"
#include "powerset.hpp"
#include "product.hpp"
#include "range.hpp"
#include "repeat.hpp"
#include "reverse.hpp"
#include "slice.hpp"
#include "sorted.hpp"
#include "takewhile.hpp"
#include "unique_everseen.hpp"
#include "unique_justseen.hpp"
#include "wrap_iter.hpp"
#include "zip.hpp"
#include "zip_longest.hpp"
//not sure if should include "iterator_range.hpp"
//since it's already in everything
#endif
<commit_msg>Renames reverse to reversed in itertools.hpp<commit_after>#ifndef ITERTOOLS_HPP
#define ITERTOOLS_HPP
#include "chain.hpp"
#include "combinations.hpp"
#include "combinations_with_replacement.hpp"
#include "compress.hpp"
#include "count.hpp"
#include "cycle.hpp"
#include "dropwhile.hpp"
#include "enumerate.hpp"
#include "filter.hpp"
#include "filterfalse.hpp"
#include "groupby.hpp"
#include "grouper.hpp"
#include "imap.hpp"
#include "iterator_range.hpp"
#include "sliding_window.hpp"
#include "permutations.hpp"
#include "powerset.hpp"
#include "product.hpp"
#include "range.hpp"
#include "repeat.hpp"
#include "reversed.hpp"
#include "slice.hpp"
#include "sorted.hpp"
#include "takewhile.hpp"
#include "unique_everseen.hpp"
#include "unique_justseen.hpp"
#include "wrap_iter.hpp"
#include "zip.hpp"
#include "zip_longest.hpp"
//not sure if should include "iterator_range.hpp"
//since it's already in everything
#endif
<|endoftext|> |
<commit_before>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "accessible.h"
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include <QAccessibleValueInterface>
#include "adaptor.h"
#include "bridge.h"
#include "cache.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
#define ACCESSIBLE_CREATION_DEBUG
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QString QSpiAccessible::pathForObject(QObject *object)
{
Q_ASSERT(object);
return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}
QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
QString path;
QAccessibleInterface* interfaceWithObject = interface;
while(!interfaceWithObject->object()) {
QAccessibleInterface* parentInterface;
interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
Q_ASSERT(parentInterface->isValid());
int index = parentInterface->indexOfChild(interfaceWithObject);
//Q_ASSERT(index >= 0);
// FIXME: This should never happen!
if (index < 0) {
index = 999;
path.prepend("/BROKEN_OBJECT_HIERARCHY");
qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();
qDebug() << "Original interface: " << interface->object() << index;
qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
QObject* p = parentInterface->object();
qDebug() << p->children();
QAccessibleInterface* tttt;
int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
qDebug() << "Nav child: " << id << tttt->object();
}
path.prepend('/' + QString::number(index));
interfaceWithObject = parentInterface;
}
path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));
if (childIndex > 0) {
path.append('/' + QString::number(childIndex));
}
return path;
}
QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
QStringList parts = dbusPath.split('/');
Q_ASSERT(parts.size() > 5);
// ignore the first /org/a11y/atspi/accessible/
QString objectString = parts.at(5);
quintptr uintptr = objectString.toULongLong();
if (!uintptr)
return QPair<QAccessibleInterface*, int>(0, 0);
QObject* object = reinterpret_cast<QObject*>(uintptr);
qDebug() << object;
QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
QAccessibleInterface* childInter;
int index = 0;
for (int i = 6; i < parts.size(); ++i) {
index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
if (index == 0) {
delete inter;
inter = childInter;
}
}
return QPair<QAccessibleInterface*, int>(inter, index);
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
QString path = pathForInterface(interface, index);
QDBusObjectPath dbusPath = QDBusObjectPath(path);
reference = QSpiObjectReference(spiBridge->dBusConnection(),
dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index);
#endif
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ( (!interface->rect(index).isEmpty()) ||
(interface->object() && interface->object()->isWidgetType()) ||
(interface->role(index) == QAccessible::ListItem) ||
(interface->role(index) == QAccessible::Cell) ||
(interface->role(index) == QAccessible::TreeItem) ||
(interface->role(index) == QAccessible::Row) ||
(interface->object() && interface->object()->inherits("QSGItem"))
) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << " IS a window";
#endif
}
}
}
#ifdef ACCESSIBLE_CREATION_DEBUG
else {
qDebug() << " IS NOT a component";
}
#endif
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->table2Interface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(childIndex());
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface) {
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
delete parentInterface;
if (parent)
return parent->getReference();
}
}
qWarning() << "Invalid parent: " << interface << interface->object();
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface);
if (!interface->isValid()) {
spiBridge->removeAdaptor(this);
return;
}
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
qDebug() << "Focus: " << getReference().path.path() << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
case QAccessible::TextUpdated: {
Q_ASSERT(interface->textInterface());
// at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
qDebug() << "Text changed: " << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(oldText));
emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());
QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
data.setVariant(QVariant::fromValue(text));
emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
oldText = text;
QDBusVariant cursorData;
int pos = interface->textInterface()->cursorPosition();
cursorData.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
break;
}
case QAccessible::TextCaretMoved: {
Q_ASSERT(interface->textInterface());
qDebug() << "Text caret moved: " << interface->object();
QDBusVariant data;
int pos = interface->textInterface()->cursorPosition();
data.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
break;
}
#endif
case QAccessible::ValueChanged: {
Q_ASSERT(interface->valueInterface());
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:
break;
case QAccessible::ObjectHide:
// TODO - send status changed
// qWarning() << "Object hide";
break;
case QAccessible::ObjectDestroyed:
// TODO - maybe send children-changed and cache Removed
// qWarning() << "Object destroyed";
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(childIndex());
// qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
if ((state^newState) & QAccessible::Checked) {
int checked = (newState & QAccessible::Checked) ? 1 : 0;
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
}
state = newState;
break;
}
case QAccessible::TableModelChanged: {
// FIXME: react to table layout changes - added rows etc
// QAccessible2::TableModelChange change = interface->table2Interface()->modelChange();
// QDBusVariant data;
// data.setVariant(QVariant::fromValue(getReference()));
// signalChildrenChanged("add", interface->childCount(), 0, data);
// // model-changed
// emit ChildrenChanged(type, detail1, detail2, data, spiBridge->getRootReference());
break;
}
case QAccessible::ParentChanged:
// TODO - send parent changed
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<commit_msg>Improve tables adding cells slightly.<commit_after>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "accessible.h"
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include <QAccessibleValueInterface>
#include "adaptor.h"
#include "bridge.h"
#include "cache.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
#define ACCESSIBLE_CREATION_DEBUG
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QString QSpiAccessible::pathForObject(QObject *object)
{
Q_ASSERT(object);
return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}
QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
QString path;
QAccessibleInterface* interfaceWithObject = interface;
while(!interfaceWithObject->object()) {
QAccessibleInterface* parentInterface;
interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
Q_ASSERT(parentInterface->isValid());
int index = parentInterface->indexOfChild(interfaceWithObject);
//Q_ASSERT(index >= 0);
// FIXME: This should never happen!
if (index < 0) {
index = 999;
path.prepend("/BROKEN_OBJECT_HIERARCHY");
qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();
qDebug() << "Original interface: " << interface->object() << index;
qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
QObject* p = parentInterface->object();
qDebug() << p->children();
QAccessibleInterface* tttt;
int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
qDebug() << "Nav child: " << id << tttt->object();
}
path.prepend('/' + QString::number(index));
interfaceWithObject = parentInterface;
}
path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));
if (childIndex > 0) {
path.append('/' + QString::number(childIndex));
}
return path;
}
QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
QStringList parts = dbusPath.split('/');
Q_ASSERT(parts.size() > 5);
// ignore the first /org/a11y/atspi/accessible/
QString objectString = parts.at(5);
quintptr uintptr = objectString.toULongLong();
if (!uintptr)
return QPair<QAccessibleInterface*, int>(0, 0);
QObject* object = reinterpret_cast<QObject*>(uintptr);
qDebug() << object;
QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
QAccessibleInterface* childInter;
int index = 0;
for (int i = 6; i < parts.size(); ++i) {
index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
if (index == 0) {
delete inter;
inter = childInter;
}
}
return QPair<QAccessibleInterface*, int>(inter, index);
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
QString path = pathForInterface(interface, index);
QDBusObjectPath dbusPath = QDBusObjectPath(path);
reference = QSpiObjectReference(spiBridge->dBusConnection(),
dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index);
#endif
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ( (!interface->rect(index).isEmpty()) ||
(interface->object() && interface->object()->isWidgetType()) ||
(interface->role(index) == QAccessible::ListItem) ||
(interface->role(index) == QAccessible::Cell) ||
(interface->role(index) == QAccessible::TreeItem) ||
(interface->role(index) == QAccessible::Row) ||
(interface->object() && interface->object()->inherits("QSGItem"))
) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << " IS a window";
#endif
}
}
}
#ifdef ACCESSIBLE_CREATION_DEBUG
else {
qDebug() << " IS NOT a component";
}
#endif
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->table2Interface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(childIndex());
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface) {
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
delete parentInterface;
if (parent)
return parent->getReference();
}
}
qWarning() << "Invalid parent: " << interface << interface->object();
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface);
if (!interface->isValid()) {
spiBridge->removeAdaptor(this);
return;
}
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
qDebug() << "Focus: " << getReference().path.path() << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
case QAccessible::TextUpdated: {
Q_ASSERT(interface->textInterface());
// at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
qDebug() << "Text changed: " << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(oldText));
emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());
QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
data.setVariant(QVariant::fromValue(text));
emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
oldText = text;
QDBusVariant cursorData;
int pos = interface->textInterface()->cursorPosition();
cursorData.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
break;
}
case QAccessible::TextCaretMoved: {
Q_ASSERT(interface->textInterface());
qDebug() << "Text caret moved: " << interface->object();
QDBusVariant data;
int pos = interface->textInterface()->cursorPosition();
data.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
break;
}
#endif
case QAccessible::ValueChanged: {
Q_ASSERT(interface->valueInterface());
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:
break;
case QAccessible::ObjectHide:
// TODO - send status changed
// qWarning() << "Object hide";
break;
case QAccessible::ObjectDestroyed:
// TODO - maybe send children-changed and cache Removed
// qWarning() << "Object destroyed";
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(childIndex());
// qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
if ((state^newState) & QAccessible::Checked) {
int checked = (newState & QAccessible::Checked) ? 1 : 0;
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
}
state = newState;
break;
}
case QAccessible::TableModelChanged: {
// This is rather evil. We don't send data and hope that at-spi fetches the right child.
// This hack fails when a row gets removed and a different one added in its place.
QDBusVariant data;
emit ChildrenChanged("add", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ParentChanged:
// TODO - send parent changed
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<|endoftext|> |
<commit_before>#include "..\header\Game.h"
#include "..\header\Border.h"
Border::Border(game_state* GameState){
LogManager& log = LogManager::getInstance();
log.writeLog("[Border] Initializing Border.");
GraphicsManager& g = GraphicsManager::getInstance();
WorldManager& world = WorldManager::getInstance();
ResourceManager& resource = ResourceManager::getInstance();
if (!resource.isStarted() || !g.isStarted() || !world.isStarted()){
log.writeLog("[Border] Something is wrong with manager startups. Order: %s %s %s", BoolToString(resource.isStarted()), BoolToString(g.isStarted()), BoolToString(world.isStarted()));
world.markForDelete(this);
return;
}
Sprite* tempSprite = resource.getSprite("border");
if (tempSprite){
log.writeLog("[Border] Successfully loaded Border sprite.");
setSprite(tempSprite);
setSpriteSlowdown(5);
setTransparency();
setSolidness(Solidness::HARD);
setType(TYPE_BORDER);
registerInterest(DF_STEP_EVENT);
setVisible(true);
int w = g.getHorizontal() / 2;
int h = g.getVertical() / 2;
Position pos(w, h);
setPosition(pos);
this->width = tempSprite->getWidth();
this->height = tempSprite->getHeight();
GameState->PlayerState.minX = w - (tempSprite->getWidth() / 2);
GameState->PlayerState.minX = h - (tempSprite->getHeight() / 2);
GameState->PlayerState.maxX = w + (tempSprite->getWidth() / 2);
GameState->PlayerState.maxY = h + (tempSprite->getHeight() / 2);
}
else {
log.writeLog("[Border] Something is wrong with loading the sprite. Aborting.");
}
return;
}
int Border::eventHandler(Event* e){
if (e->getType() == DF_STEP_EVENT){
return 1;
}
return 0;
}
void Border::draw(){
Object::draw();
}
int Border::getWidth(){
return this->width;
}
int Border::getHeight(){
return this->height;
}<commit_msg>Adding notes about borders and layouts.<commit_after>#include "..\header\Game.h"
#include "..\header\Border.h"
Border::Border(game_state* GameState){
LogManager& log = LogManager::getInstance();
log.writeLog("[Border] Initializing Border.");
GraphicsManager& g = GraphicsManager::getInstance();
WorldManager& world = WorldManager::getInstance();
ResourceManager& resource = ResourceManager::getInstance();
if (!resource.isStarted() || !g.isStarted() || !world.isStarted()){
log.writeLog("[Border] Something is wrong with manager startups. Order: %s %s %s", BoolToString(resource.isStarted()), BoolToString(g.isStarted()), BoolToString(world.isStarted()));
world.markForDelete(this);
return;
}
Sprite* tempSprite = resource.getSprite("border");
if (tempSprite){
log.writeLog("[Border] Successfully loaded Border sprite.");
setSprite(tempSprite);
setSpriteSlowdown(5);
setTransparency();
setSolidness(Solidness::HARD);
setType(TYPE_BORDER);
registerInterest(DF_STEP_EVENT);
setVisible(true);
int w = g.getHorizontal() / 2;
int h = g.getVertical() / 2;
Position pos(w, h);
setPosition(pos);
this->width = tempSprite->getWidth();
this->height = tempSprite->getHeight();
//Border is 15x15.
//Layout is 13x13.
GameState->PlayerState.minX = w - (tempSprite->getWidth() / 2);
GameState->PlayerState.minX = h - (tempSprite->getHeight() / 2);
GameState->PlayerState.maxX = w + (tempSprite->getWidth() / 2);
GameState->PlayerState.maxY = h + (tempSprite->getHeight() / 2);
}
else {
log.writeLog("[Border] Something is wrong with loading the sprite. Aborting.");
}
return;
}
int Border::eventHandler(Event* e){
if (e->getType() == DF_STEP_EVENT){
return 1;
}
return 0;
}
void Border::draw(){
Object::draw();
}
int Border::getWidth(){
return this->width;
}
int Border::getHeight(){
return this->height;
}<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/common/time_trigger.h>
#include <pcl/common/time.h>
#include <iostream>
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval, const callback_type& callback)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
registerCallback (callback);
}
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
}
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::~TimeTrigger ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
quit_ = true;
condition_.notify_all ();
lock.unlock ();
timer_thread_.join ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::TimeTrigger::registerCallback (const callback_type& callback)
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
return (callbacks_.connect (callback));
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::setInterval (double interval_seconds)
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
interval_ = interval_seconds;
// notify, since we could switch from a large interval to a shorter one -> interrupt waiting for timeout!
condition_.notify_all ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::start ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (!running_)
{
running_ = true;
condition_.notify_all ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::stop ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (running_)
{
running_ = false;
condition_.notify_all ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::thread_function ()
{
double time = 0;
while (!quit_)
{
time = getTime ();
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (!running_)
condition_.wait (lock); // wait util start is called or destructor is called
else
{
callbacks_();
double rest = interval_ + time - getTime ();
if (rest > 0.0) // without a deadlock is possible, until notify() is called
condition_.timed_wait (lock, boost::posix_time::microseconds (static_cast<int64_t> ((rest * 1000000))));
}
}
}
<commit_msg>boost::signals2::connect is thread safe, so the lock is unnecessary<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/common/time_trigger.h>
#include <pcl/common/time.h>
#include <iostream>
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval, const callback_type& callback)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
registerCallback (callback);
}
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
}
//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::~TimeTrigger ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
quit_ = true;
condition_.notify_all ();
lock.unlock ();
timer_thread_.join ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::TimeTrigger::registerCallback (const callback_type& callback)
{
return (callbacks_.connect (callback));
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::setInterval (double interval_seconds)
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
interval_ = interval_seconds;
// notify, since we could switch from a large interval to a shorter one -> interrupt waiting for timeout!
condition_.notify_all ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::start ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (!running_)
{
running_ = true;
condition_.notify_all ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::stop ()
{
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (running_)
{
running_ = false;
condition_.notify_all ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::thread_function ()
{
double time = 0;
while (!quit_)
{
time = getTime ();
boost::unique_lock<boost::mutex> lock (condition_mutex_);
if (!running_)
condition_.wait (lock); // wait util start is called or destructor is called
else
{
callbacks_();
double rest = interval_ + time - getTime ();
if (rest > 0.0) // without a deadlock is possible, until notify() is called
condition_.timed_wait (lock, boost::posix_time::microseconds (static_cast<int64_t> ((rest * 1000000))));
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: functiondescription.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:32:18 $
*
* 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_stoc.hxx"
#include "functiondescription.hxx"
#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
namespace css = com::sun::star;
using stoc::registry_tdprovider::FunctionDescription;
FunctionDescription::FunctionDescription(
css::uno::Reference< css::container::XHierarchicalNameAccess > const &
manager,
com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
sal_uInt16 index):
m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}
FunctionDescription::~FunctionDescription() {}
css::uno::Sequence<
css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
{
osl::MutexGuard guard(m_mutex);
if (m_exceptionsInit) {
return m_exceptions;
}
}
typereg::Reader reader(getReader());
sal_uInt16 n = reader.getMethodExceptionCount(m_index);
css::uno::Sequence<
css::uno::Reference< css::reflection::XCompoundTypeDescription > >
exceptions(n);
for (sal_uInt16 i = 0; i < n; ++i) {
rtl::OUString name(
reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
css::uno::Any any;
try {
any = m_manager->getByHierarchicalName(name);
} catch (css::container::NoSuchElementException & e) {
throw new css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.container.NoSuchElementException: "))
+ e.Message),
css::uno::Reference< css::uno::XInterface >()); //TODO
}
if (!(any >>= exceptions[i])
|| exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
{
throw new css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
+ name),
css::uno::Reference< css::uno::XInterface >()); //TODO
}
OSL_ASSERT(exceptions[i].is());
}
osl::MutexGuard guard(m_mutex);
if (!m_exceptionsInit) {
m_exceptions = exceptions;
m_exceptionsInit = true;
}
return m_exceptions;
}
typereg::Reader FunctionDescription::getReader() const {
return typereg::Reader(
m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.56); FILE MERGED 2008/03/31 07:26:11 rt 1.6.56.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: functiondescription.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include "functiondescription.hxx"
#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
namespace css = com::sun::star;
using stoc::registry_tdprovider::FunctionDescription;
FunctionDescription::FunctionDescription(
css::uno::Reference< css::container::XHierarchicalNameAccess > const &
manager,
com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
sal_uInt16 index):
m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}
FunctionDescription::~FunctionDescription() {}
css::uno::Sequence<
css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
{
osl::MutexGuard guard(m_mutex);
if (m_exceptionsInit) {
return m_exceptions;
}
}
typereg::Reader reader(getReader());
sal_uInt16 n = reader.getMethodExceptionCount(m_index);
css::uno::Sequence<
css::uno::Reference< css::reflection::XCompoundTypeDescription > >
exceptions(n);
for (sal_uInt16 i = 0; i < n; ++i) {
rtl::OUString name(
reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
css::uno::Any any;
try {
any = m_manager->getByHierarchicalName(name);
} catch (css::container::NoSuchElementException & e) {
throw new css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.container.NoSuchElementException: "))
+ e.Message),
css::uno::Reference< css::uno::XInterface >()); //TODO
}
if (!(any >>= exceptions[i])
|| exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
{
throw new css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
+ name),
css::uno::Reference< css::uno::XInterface >()); //TODO
}
OSL_ASSERT(exceptions[i].is());
}
osl::MutexGuard guard(m_mutex);
if (!m_exceptionsInit) {
m_exceptions = exceptions;
m_exceptionsInit = true;
}
return m_exceptions;
}
typereg::Reader FunctionDescription::getReader() const {
return typereg::Reader(
m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<|endoftext|> |
<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2011-2015 Regents of the University of California.
*
* This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
* contributors.
*
* ndnSIM 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.
*
* ndnSIM 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
* ndnSIM, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
// test-mobility.cpp
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/config-store-module.h"
#include "ns3/mobility-module.h"
#include "ns3/athstats-helper.h"
#include "ns3/internet-module.h"
#include "ns3/ndnSIM-module.h"
#include <iostream>
using namespace std;
namespace ns3 {
NS_LOG_COMPONENT_DEFINE("ndn.TestMobility");
/**
* This scenario simulates a very simple network topology:
*
*
* +----------+ 1Mbps +--------+ 1Mbps +----------+
* | consumer | <------------> | router | <------------> | producer |
* +----------+ 10ms +--------+ 10ms +----------+
*
*
* Consumer requests data from producer with frequency 10 interests per second
* (interests contain constantly increasing sequence number).
*
* For every received interest, producer replies with a data packet, containing
* 1024 bytes of virtual payload.
*
* To run scenario and see what is happening, use the following command:
*
* NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=test-example
*/
static void
SetPosition (Ptr<Node> node, Vector position)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
mobility->SetPosition (position);
}
static Vector
GetPosition (Ptr<Node> node)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
return mobility->GetPosition ();
}
static void
AdvancePosition (Ptr<Node> node)
{
Vector pos = GetPosition (node);
pos.x += 5.0;
pos.y += 5.0;
if (pos.x >= 210.0)
{
return;
}
SetPosition (node, pos);
Simulator::Schedule (Seconds (1.0), &AdvancePosition, node);
}
int
main(int argc, char* argv[])
{
// setting default parameters for Wifi
// enable rts cts all the time.
Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("0"));
// disable fragmentation
Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",
StringValue("OfdmRate24Mbps"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
cmd.Parse(argc, argv);
Packet::EnablePrinting ();
// Mobility config
MobilityHelper mobility;
Ptr<UniformRandomVariable> randomizer = CreateObject<UniformRandomVariable>();
randomizer->SetAttribute("Min", DoubleValue(10));
randomizer->SetAttribute("Max", DoubleValue(100));
mobility.SetPositionAllocator ("ns3::RandomBoxPositionAllocator",
"X", StringValue ("ns3::UniformRandomVariable[Min=0|Max=100]"),
"Y", StringValue ("ns3::UniformRandomVariable[Min=0|Max=100]"));
/*
mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizer),
"Y", PointerValue(randomizer), "Z", PointerValue(randomizer));
*/
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
// Wifi config
WifiHelper wifi = WifiHelper::Default ();
NodeContainer stas;
NodeContainer ap;
NetDeviceContainer staDevs;
PacketSocketHelper packetSocket;
stas.Create (3);
ap.Create (2);
// give packet socket powers to nodes.
packetSocket.Install (stas);
packetSocket.Install (ap);
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
wifiPhy.Set("TxPowerStart", DoubleValue(5));
wifiPhy.Set("TxPowerEnd", DoubleValue(5));
Ssid ssid = Ssid ("wifi-default");
wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
// setup stas.
wifiMac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));
staDevs = wifi.Install (wifiPhy, wifiMac, stas);
// setup ap.
wifiMac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
wifi.Install (wifiPhy, wifiMac, ap);
// Install mobility
mobility.Install (stas);
mobility.Install (ap);
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
ndnHelper.SetDefaultRoutes(true);
ndnHelper.SetOldContentStore("ns3::ndn::cs::Splitcache",
"NormalPolicy", "ns3::ndn::cs::Lru",
"SpecialPolicy", "ns3::ndn::cs::Lru",
"TotalCacheSize", "500",
"Configure", "40");
// Percentage Special^
ndnHelper.Install(ap);
ndnHelper.SetOldContentStore("ns3::ndn::cs::Nocache");
ndnHelper.Install(stas);
// Choosing forwarding strategy
ndn::StrategyChoiceHelper::Install(stas, "/", "/localhost/nfd/strategy/best-route");
ndn::StrategyChoiceHelper::Install(ap, "/", "/localhost/nfd/strategy/best-route");
// Installing applications
// Consumer (basic and special data)
ndn::AppHelper consumerHelper("ns3::ndn::ConsumerZipfMandelbrot");
consumerHelper.SetAttribute("NumberOfContents", StringValue("10")); // 10 different contents
// Consumer will request /prefix/0, /prefix/1, ...
consumerHelper.SetPrefix("data/basic");
consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
consumerHelper.Install(stas.Get(0));
consumerHelper.SetPrefix("data/special");
consumerHelper.SetAttribute("Frequency", StringValue("2")); // 2 interests a second
consumerHelper.Install(stas.Get(2));
consumerHelper.SetPrefix("data/basic");
consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
consumerHelper.Install(stas.Get(1));
// Producer
ndn::AppHelper producerHelper("ns3::ndn::Producer");
// Producer will reply to all requests starting with /prefix
producerHelper.SetPrefix("/data");
producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
producerHelper.SetAttribute("Freshness", TimeValue(Seconds(-1.0))); // unlimited freshness
producerHelper.Install(ap.Get(0)); // first node
producerHelper.Install(ap.Get(1)); // second node
Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (0));
// Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (1));
// Simulator::Schedule (Seconds (2.0), &AdvancePosition, stas.Get (2));
// PacketSocketAddress socket;
// socket.SetSingleDevice (staDevs.Get (0)->GetIfIndex ());
// socket.SetPhysicalAddress (staDevs.Get (1)->GetAddress ());
// socket.SetProtocol (1);
// OnOffHelper onoff ("ns3::PacketSocketFactory", Address (socket));
// onoff.SetConstantRate (DataRate ("500kb/s"));
// ApplicationContainer apps = onoff.Install (stas.Get (0));
// apps.Start (Seconds (0.5));
// apps.Stop (Seconds (43.0));
// Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacTx", MakeCallback (&DevTxTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacRx", MakeCallback (&DevRxTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxOk", MakeCallback (&PhyRxOkTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxError", MakeCallback (&PhyRxErrorTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/Tx", MakeCallback (&PhyTxTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/State", MakeCallback (&PhyStateTrace));
AthstatsHelper athstats;
athstats.EnableAthstats ("athstats-sta", stas);
athstats.EnableAthstats ("athstats-ap", ap);
ndn::AppDelayTracer::InstallAll("app-delays-trace.txt");
ndn::CsTracer::InstallAll("cs-trace.txt", Seconds(1));
Simulator::Stop(Seconds(20.0));
Simulator::Run();
Simulator::Destroy();
return 0;
}
} // namespace ns3
int
main(int argc, char* argv[])
{
return ns3::main(argc, argv);
}
<commit_msg>mobility working<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2011-2015 Regents of the University of California.
*
* This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
* contributors.
*
* ndnSIM 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.
*
* ndnSIM 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
* ndnSIM, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
// test-mobility.cpp
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/config-store-module.h"
#include "ns3/mobility-module.h"
#include "ns3/athstats-helper.h"
#include "ns3/internet-module.h"
#include "ns3/ndnSIM-module.h"
#include <iostream>
using namespace std;
namespace ns3 {
NS_LOG_COMPONENT_DEFINE("ndn.TestMobility");
/**
* This scenario simulates a very simple network topology:
*
*
* +----------+ 1Mbps +--------+ 1Mbps +----------+
* | consumer | <------------> | router | <------------> | producer |
* +----------+ 10ms +--------+ 10ms +----------+
*
*
* Consumer requests data from producer with frequency 10 interests per second
* (interests contain constantly increasing sequence number).
*
* For every received interest, producer replies with a data packet, containing
* 1024 bytes of virtual payload.
*
* To run scenario and see what is happening, use the following command:
*
* NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=test-example
*/
static void
SetPosition (Ptr<Node> node, Vector position)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
mobility->SetPosition (position);
}
static Vector
GetPosition (Ptr<Node> node)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
return mobility->GetPosition ();
}
static void
AdvancePosition (Ptr<Node> node)
{
Vector pos = GetPosition (node);
pos.x += 5.0;
pos.y += 5.0;
if (pos.x >= 210.0)
{
return;
}
SetPosition (node, pos);
Simulator::Schedule (Seconds (1.0), &AdvancePosition, node);
}
int
main(int argc, char* argv[])
{
// setting default parameters for Wifi
// enable rts cts all the time.
Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("0"));
// disable fragmentation
Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",
StringValue("OfdmRate24Mbps"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
cmd.Parse(argc, argv);
Packet::EnablePrinting ();
// Mobility config
MobilityHelper mobility;
Ptr<UniformRandomVariable> randomizer = CreateObject<UniformRandomVariable>();
randomizer->SetAttribute("Min", DoubleValue(10));
randomizer->SetAttribute("Max", DoubleValue(100));
mobility.SetPositionAllocator ("ns3::RandomBoxPositionAllocator",
"X", StringValue ("ns3::UniformRandomVariable[Min=0|Max=10]"),
"Y", StringValue ("ns3::UniformRandomVariable[Min=0|Max=10]"));
/*
mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizer),
"Y", PointerValue(randomizer), "Z", PointerValue(randomizer));
*/
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
// Wifi config
WifiHelper wifi = WifiHelper::Default ();
NodeContainer stas;
NodeContainer ap;
NetDeviceContainer staDevs;
PacketSocketHelper packetSocket;
stas.Create (3);
ap.Create (2);
// give packet socket powers to nodes.
packetSocket.Install (stas);
packetSocket.Install (ap);
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
wifiPhy.Set("TxPowerStart", DoubleValue(5));
wifiPhy.Set("TxPowerEnd", DoubleValue(5));
Ssid ssid = Ssid ("wifi-default");
wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
// setup stas.
wifiMac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));
staDevs = wifi.Install (wifiPhy, wifiMac, stas);
// setup ap.
wifiMac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
wifi.Install (wifiPhy, wifiMac, ap);
// Install mobility
mobility.Install (stas);
// mobility.Install (ap);
mobility.Install (ap.Get(0));
mobility.SetPositionAllocator ("ns3::RandomBoxPositionAllocator",
"X", StringValue ("ns3::UniformRandomVariable[Min=100|Max=110]"),
"Y", StringValue ("ns3::UniformRandomVariable[Min=100|Max=110]"));
mobility.Install (ap.Get(1));
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
ndnHelper.SetDefaultRoutes(true);
ndnHelper.SetOldContentStore("ns3::ndn::cs::Splitcache",
"NormalPolicy", "ns3::ndn::cs::Lru",
"SpecialPolicy", "ns3::ndn::cs::Lru",
"TotalCacheSize", "500",
"Configure", "40");
// Percentage Special^
ndnHelper.Install(ap);
ndnHelper.SetOldContentStore("ns3::ndn::cs::Nocache");
ndnHelper.Install(stas);
// Choosing forwarding strategy
ndn::StrategyChoiceHelper::Install(stas, "/", "/localhost/nfd/strategy/best-route");
ndn::StrategyChoiceHelper::Install(ap, "/", "/localhost/nfd/strategy/best-route");
// Installing applications
// Consumer (basic and special data)
ndn::AppHelper consumerHelper("ns3::ndn::ConsumerZipfMandelbrot");
consumerHelper.SetAttribute("NumberOfContents", StringValue("10")); // 10 different contents
// Consumer will request /prefix/0, /prefix/1, ...
consumerHelper.SetPrefix("data/basic");
consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
consumerHelper.Install(stas.Get(0));
consumerHelper.SetPrefix("data/special");
consumerHelper.SetAttribute("Frequency", StringValue("2")); // 2 interests a second
consumerHelper.Install(stas.Get(2));
consumerHelper.SetPrefix("data/basic");
consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
consumerHelper.Install(stas.Get(1));
// Producer
ndn::AppHelper producerHelper("ns3::ndn::Producer");
// Producer will reply to all requests starting with /prefix
producerHelper.SetPrefix("/data");
producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
producerHelper.SetAttribute("Freshness", TimeValue(Seconds(-1.0))); // unlimited freshness
producerHelper.Install(ap.Get(0)); // first node
producerHelper.Install(ap.Get(1)); // second node
Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (0));
// Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (1));
// Simulator::Schedule (Seconds (2.0), &AdvancePosition, stas.Get (2));
// PacketSocketAddress socket;
// socket.SetSingleDevice (staDevs.Get (0)->GetIfIndex ());
// socket.SetPhysicalAddress (staDevs.Get (1)->GetAddress ());
// socket.SetProtocol (1);
// OnOffHelper onoff ("ns3::PacketSocketFactory", Address (socket));
// onoff.SetConstantRate (DataRate ("500kb/s"));
// ApplicationContainer apps = onoff.Install (stas.Get (0));
// apps.Start (Seconds (0.5));
// apps.Stop (Seconds (43.0));
// Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacTx", MakeCallback (&DevTxTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacRx", MakeCallback (&DevRxTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxOk", MakeCallback (&PhyRxOkTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxError", MakeCallback (&PhyRxErrorTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/Tx", MakeCallback (&PhyTxTrace));
// Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/State", MakeCallback (&PhyStateTrace));
AthstatsHelper athstats;
athstats.EnableAthstats ("athstats-sta", stas);
athstats.EnableAthstats ("athstats-ap", ap);
ndn::AppDelayTracer::InstallAll("app-delays-trace.txt");
ndn::CsTracer::InstallAll("cs-trace.txt", Seconds(1));
Simulator::Stop(Seconds(20.0));
Simulator::Run();
Simulator::Destroy();
return 0;
}
} // namespace ns3
int
main(int argc, char* argv[])
{
return ns3::main(argc, argv);
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdexcept>
#include <QMutexLocker>
#include <Utils.hpp>
#include "USBRadio.hpp"
#include "Geometry2d/Util.hpp"
// Include this file for base station usb vendor/product ids
#include "firmware-common/base2015/usb-interface.hpp"
// included for kicer status enum
#include "firmware-common/robot2015/cpu/status.h"
using namespace std;
using namespace Packet;
// Timeout for control transfers, in milliseconds
static const int Control_Timeout = 1000;
USBRadio::USBRadio() : _mutex(QMutex::Recursive) {
_printedError = false;
_device = nullptr;
_usb_context = nullptr;
libusb_init(&_usb_context);
for (int i = 0; i < NumRXTransfers; ++i) {
_rxTransfers[i] = libusb_alloc_transfer(0);
}
current_receive_debug = {DebugCommunication::DebugResponse::PIDError0};
}
USBRadio::~USBRadio() {
if (_device) {
libusb_close(_device);
}
for (int i = 0; i < NumRXTransfers; ++i) {
libusb_free_transfer(_rxTransfers[i]);
}
libusb_exit(_usb_context);
}
bool USBRadio::open() {
libusb_device** devices = nullptr;
ssize_t numDevices = libusb_get_device_list(_usb_context, &devices);
if (numDevices < 0) {
fprintf(stderr, "libusb_get_device_list failed\n");
return false;
}
int numRadios = 0;
for (int i = 0; i < numDevices; ++i) {
struct libusb_device_descriptor desc;
int err = libusb_get_device_descriptor(devices[i], &desc);
if (err == 0 && desc.idVendor == RJ_BASE2015_VENDOR_ID &&
desc.idProduct == RJ_BASE2015_PRODUCT_ID) {
++numRadios;
int err = libusb_open(devices[i], &_device);
if (err == 0) {
break;
}
}
}
libusb_free_device_list(devices, 1);
if (!numRadios) {
if (!_printedError) {
fprintf(stderr, "USBRadio: No radio is connected\n");
_printedError = true;
}
return false;
}
if (!_device) {
if (!_printedError) {
fprintf(stderr, "USBRadio: All radios are in use\n");
_printedError = true;
}
return false;
}
if (libusb_set_configuration(_device, 1)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't set configuration\n");
_printedError = true;
}
return false;
}
if (libusb_claim_interface(_device, 0)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't claim interface\n");
_printedError = true;
}
return false;
}
channel(_channel);
// Start the receive transfers
for (int i = 0; i < NumRXTransfers; ++i) {
// Populate the required libusb_transfer fields for a bulk transfer.
libusb_fill_bulk_transfer(
_rxTransfers[i], // the transfer to populate
_device, // handle of the device that will handle the transfer
LIBUSB_ENDPOINT_IN |
2, // address of the endpoint where this transfer will be sent
_rxBuffers[i], // data buffer
rtp::ReverseSize, // length of data buffer
rxCompleted, // callback function to be invoked on transfer
// completion
this, // user data to pass to callback function
0); // timeout for the transfer in milliseconds
libusb_submit_transfer(_rxTransfers[i]);
}
_printedError = false;
return true;
}
void USBRadio::rxCompleted(libusb_transfer* transfer) {
USBRadio* radio = (USBRadio*)transfer->user_data;
if (transfer->status == LIBUSB_TRANSFER_COMPLETED &&
transfer->actual_length == rtp::ReverseSize) {
// Parse the packet and add to the list of RadioRx's
radio->handleRxData(transfer->buffer);
}
// Restart the transfer
libusb_submit_transfer(transfer);
}
void USBRadio::command(uint8_t cmd) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioStrobe, 0, cmd,
nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::command control write failed");
}
}
void USBRadio::write(uint8_t reg, uint8_t value) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioWriteRegister,
value, reg, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::write control write failed");
}
}
uint8_t USBRadio::read(uint8_t reg) {
uint8_t value = 0;
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioReadRegister, 0,
reg, &value, 1, Control_Timeout)) {
throw runtime_error("USBRadio::read control write failed");
}
return value;
}
bool USBRadio::isOpen() const { return _device; }
void USBRadio::send(Packet::RadioTx& packet) {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
uint8_t forward_packet[rtp::ForwardSize];
// ensure Forward_Size is correct
static_assert(sizeof(rtp::Header) + 6 * sizeof(rtp::RobotTxMessage) ==
rtp::ForwardSize,
"Forward packet contents exceeds buffer size");
// Unit conversions
static const float Seconds_Per_Cycle = 0.005f;
static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f;
static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f);
rtp::Header* header = (rtp::Header*)forward_packet;
header->port = rtp::PortType::CONTROL;
header->address = rtp::BROADCAST_ADDRESS;
header->type = rtp::MessageType::CONTROL;
// Build a forward packet
for (int slot = 0; slot < 6; ++slot) {
// Calculate the offset into the @forward_packet for this robot's
// control message and cast it to a ControlMessage pointer for easy
// access
size_t offset =
sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
rtp::RobotTxMessage* msg =
(rtp::RobotTxMessage*)(forward_packet + offset);
if (slot < packet.robots_size()) {
const Packet::Control& robot = packet.robots(slot).control();
msg->uid = packet.robots(slot).uid();
msg->messageType = rtp::RobotTxMessage::ControlMessageType;
auto &controlMessage = msg->message.controlMessage;
controlMessage.bodyX = static_cast<int16_t >(robot.xvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyY = static_cast<int16_t >(robot.yvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyW = static_cast<int16_t >(robot.avelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.dribbler = clamp(static_cast<uint16_t>(robot.dvelocity()) * 2, 0, 255);
controlMessage.kickStrength = robot.kcstrength();
controlMessage.shootMode = robot.shootmode();
controlMessage.triggerMode = robot.triggermode();
controlMessage.song = robot.song();
} else {
// empty slot
msg->uid = rtp::INVALID_ROBOT_UID;
}
}
if (packet.robots_size()<6) {
auto slot = packet.robots_size();
size_t offset =
sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
rtp::RobotTxMessage* msg =
(rtp::RobotTxMessage*)(forward_packet + offset);
msg->uid = rtp::ANY_ROBOT_UID;
msg->messageType = rtp::RobotTxMessage::DebugMessageType;
auto &debugMessage = msg->message.debugMessage;
std::copy_n(current_receive_debug.begin(), std::min(current_receive_debug.size(), debugMessage.keys.size()), debugMessage.keys.begin());
}
// Send the forward packet
int sent = 0;
int transferRetCode =
libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 2, forward_packet,
sizeof(forward_packet), &sent, Control_Timeout);
if (transferRetCode != LIBUSB_SUCCESS || sent != sizeof(forward_packet)) {
fprintf(stderr, "USBRadio: Bulk write failed. sent = %d, size = %lu\n",
sent, (unsigned long int)sizeof(forward_packet));
if (transferRetCode != LIBUSB_SUCCESS)
fprintf(stderr, " Error: '%s'\n",
libusb_error_name(transferRetCode));
int ret = libusb_clear_halt(_device, LIBUSB_ENDPOINT_OUT | 2);
if (ret != 0) {
printf("tried to clear halt, error = %s\n. closing device",
libusb_error_name(ret));
libusb_close(_device);
_device = nullptr;
}
}
}
void USBRadio::receive() {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
// Handle USB events. This will call callbacks.
struct timeval tv = {0, 0};
libusb_handle_events_timeout(_usb_context, &tv);
}
// Note: this method assumes that sizeof(buf) == rtp::ReverseSize
void USBRadio::handleRxData(uint8_t* buf) {
RadioRx packet = RadioRx();
rtp::Header* header = (rtp::Header*)buf;
rtp::RobotStatusMessage* msg =
(rtp::RobotStatusMessage*)(buf + sizeof(rtp::Header));
packet.set_timestamp(RJ::timestamp());
packet.set_robot_id(msg->uid);
// Hardware version
packet.set_hardware_version(RJ2015);
// battery voltage
packet.set_battery(msg->battVoltage *
rtp::RobotStatusMessage::BATTERY_SCALE_FACTOR);
// ball sense
if (BallSenseStatus_IsValid(msg->ballSenseStatus)) {
packet.set_ball_sense_status(BallSenseStatus(msg->ballSenseStatus));
}
// Using same flags as 2011 robot. See firmware/robot2011/cpu/status.h.
// Report that everything is good b/c the bot currently has no way of
// detecting kicker issues
packet.set_kicker_status((msg->kickStatus ? Kicker_Charged : 0) |
Kicker_Enabled | Kicker_I2C_OK);
// motor errors
for (int i = 0; i < 5; i++) {
bool err = msg->motorErrors & (1 << i);
packet.add_motor_status(err ? MotorStatus::Hall_Failure
: MotorStatus::Good);
}
// fpga status
if (FpgaStatus_IsValid(msg->fpgaStatus)) {
packet.set_fpga_status(FpgaStatus(msg->fpgaStatus));
}
for (int index = 0; index < current_receive_debug.size(); ++index)
{
auto debugResponse = current_receive_debug[index];
auto debugResponseInfo = DebugCommunication::RESPONSE_INFO.at(debugResponse);
auto value = msg->debug_data.at(index);
auto packet_debug_response = packet.add_debug_responses();
packet_debug_response->set_key(debugResponseInfo.name);
packet_debug_response->set_value(value);
}
_reversePackets.push_back(packet);
}
void USBRadio::channel(int n) {
QMutexLocker lock(&_mutex);
if (_device) {
if (libusb_control_transfer(
_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioSetChannel, n, 0, nullptr, 0,
Control_Timeout)) {
throw runtime_error("USBRadio::channel control write failed");
}
}
Radio::channel(n);
}
<commit_msg>Send configuration message<commit_after>#include <stdio.h>
#include <stdexcept>
#include <QMutexLocker>
#include <Utils.hpp>
#include "USBRadio.hpp"
#include "Geometry2d/Util.hpp"
// Include this file for base station usb vendor/product ids
#include "firmware-common/base2015/usb-interface.hpp"
// included for kicer status enum
#include "firmware-common/robot2015/cpu/status.h"
using namespace std;
using namespace Packet;
// Timeout for control transfers, in milliseconds
static const int Control_Timeout = 1000;
USBRadio::USBRadio() : _mutex(QMutex::Recursive) {
_printedError = false;
_device = nullptr;
_usb_context = nullptr;
libusb_init(&_usb_context);
for (int i = 0; i < NumRXTransfers; ++i) {
_rxTransfers[i] = libusb_alloc_transfer(0);
}
current_receive_debug = {DebugCommunication::DebugResponse::PIDError0};
}
USBRadio::~USBRadio() {
if (_device) {
libusb_close(_device);
}
for (int i = 0; i < NumRXTransfers; ++i) {
libusb_free_transfer(_rxTransfers[i]);
}
libusb_exit(_usb_context);
}
bool USBRadio::open() {
libusb_device** devices = nullptr;
ssize_t numDevices = libusb_get_device_list(_usb_context, &devices);
if (numDevices < 0) {
fprintf(stderr, "libusb_get_device_list failed\n");
return false;
}
int numRadios = 0;
for (int i = 0; i < numDevices; ++i) {
struct libusb_device_descriptor desc;
int err = libusb_get_device_descriptor(devices[i], &desc);
if (err == 0 && desc.idVendor == RJ_BASE2015_VENDOR_ID &&
desc.idProduct == RJ_BASE2015_PRODUCT_ID) {
++numRadios;
int err = libusb_open(devices[i], &_device);
if (err == 0) {
break;
}
}
}
libusb_free_device_list(devices, 1);
if (!numRadios) {
if (!_printedError) {
fprintf(stderr, "USBRadio: No radio is connected\n");
_printedError = true;
}
return false;
}
if (!_device) {
if (!_printedError) {
fprintf(stderr, "USBRadio: All radios are in use\n");
_printedError = true;
}
return false;
}
if (libusb_set_configuration(_device, 1)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't set configuration\n");
_printedError = true;
}
return false;
}
if (libusb_claim_interface(_device, 0)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't claim interface\n");
_printedError = true;
}
return false;
}
channel(_channel);
// Start the receive transfers
for (int i = 0; i < NumRXTransfers; ++i) {
// Populate the required libusb_transfer fields for a bulk transfer.
libusb_fill_bulk_transfer(
_rxTransfers[i], // the transfer to populate
_device, // handle of the device that will handle the transfer
LIBUSB_ENDPOINT_IN |
2, // address of the endpoint where this transfer will be sent
_rxBuffers[i], // data buffer
rtp::ReverseSize, // length of data buffer
rxCompleted, // callback function to be invoked on transfer
// completion
this, // user data to pass to callback function
0); // timeout for the transfer in milliseconds
libusb_submit_transfer(_rxTransfers[i]);
}
_printedError = false;
return true;
}
void USBRadio::rxCompleted(libusb_transfer* transfer) {
USBRadio* radio = (USBRadio*)transfer->user_data;
if (transfer->status == LIBUSB_TRANSFER_COMPLETED &&
transfer->actual_length == rtp::ReverseSize) {
// Parse the packet and add to the list of RadioRx's
radio->handleRxData(transfer->buffer);
}
// Restart the transfer
libusb_submit_transfer(transfer);
}
void USBRadio::command(uint8_t cmd) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioStrobe, 0, cmd,
nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::command control write failed");
}
}
void USBRadio::write(uint8_t reg, uint8_t value) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioWriteRegister,
value, reg, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::write control write failed");
}
}
uint8_t USBRadio::read(uint8_t reg) {
uint8_t value = 0;
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioReadRegister, 0,
reg, &value, 1, Control_Timeout)) {
throw runtime_error("USBRadio::read control write failed");
}
return value;
}
bool USBRadio::isOpen() const { return _device; }
void USBRadio::send(Packet::RadioTx& packet) {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
uint8_t forward_packet[rtp::ForwardSize];
// ensure Forward_Size is correct
static_assert(sizeof(rtp::Header) + 6 * sizeof(rtp::RobotTxMessage) ==
rtp::ForwardSize,
"Forward packet contents exceeds buffer size");
// Unit conversions
static const float Seconds_Per_Cycle = 0.005f;
static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f;
static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f);
rtp::Header* header = (rtp::Header*)forward_packet;
header->port = rtp::PortType::CONTROL;
header->address = rtp::BROADCAST_ADDRESS;
header->type = rtp::MessageType::CONTROL;
// Build a forward packet
for (int slot = 0; slot < 6; ++slot) {
// Calculate the offset into the @forward_packet for this robot's
// control message and cast it to a ControlMessage pointer for easy
// access
size_t offset =
sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
rtp::RobotTxMessage* msg =
(rtp::RobotTxMessage*)(forward_packet + offset);
if (slot < packet.robots_size()) {
const Packet::Control& robot = packet.robots(slot).control();
msg->uid = packet.robots(slot).uid();
msg->messageType = rtp::RobotTxMessage::ControlMessageType;
auto &controlMessage = msg->message.controlMessage;
controlMessage.bodyX = static_cast<int16_t >(robot.xvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyY = static_cast<int16_t >(robot.yvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyW = static_cast<int16_t >(robot.avelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.dribbler = clamp(static_cast<uint16_t>(robot.dvelocity()) * 2, 0, 255);
controlMessage.kickStrength = robot.kcstrength();
controlMessage.shootMode = robot.shootmode();
controlMessage.triggerMode = robot.triggermode();
controlMessage.song = robot.song();
} else {
// empty slot
msg->uid = rtp::INVALID_ROBOT_UID;
}
}
int numRobotTXMessages = packet.robots_size();
if (numRobotTXMessages<6) {
auto slot = numRobotTXMessages;
size_t offset =
sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
rtp::RobotTxMessage* msg =
(rtp::RobotTxMessage*)(forward_packet + offset);
msg->uid = rtp::ANY_ROBOT_UID;
msg->messageType = rtp::RobotTxMessage::ConfMessageType;
auto &confMessage = msg->message.confMessage;
// confMessage.keys[0] = DebugCommunication::ConfigCommunication::PID_P;
// confMessage.values[0] = 0;
numRobotTXMessages++;
}
if (numRobotTXMessages<6) {
auto slot = numRobotTXMessages;
size_t offset =
sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
rtp::RobotTxMessage* msg =
(rtp::RobotTxMessage*)(forward_packet + offset);
msg->uid = rtp::ANY_ROBOT_UID;
msg->messageType = rtp::RobotTxMessage::DebugMessageType;
auto &debugMessage = msg->message.debugMessage;
std::copy_n(current_receive_debug.begin(), std::min(current_receive_debug.size(), debugMessage.keys.size()), debugMessage.keys.begin());
numRobotTXMessages++;
}
// Send the forward packet
int sent = 0;
int transferRetCode =
libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 2, forward_packet,
sizeof(forward_packet), &sent, Control_Timeout);
if (transferRetCode != LIBUSB_SUCCESS || sent != sizeof(forward_packet)) {
fprintf(stderr, "USBRadio: Bulk write failed. sent = %d, size = %lu\n",
sent, (unsigned long int)sizeof(forward_packet));
if (transferRetCode != LIBUSB_SUCCESS)
fprintf(stderr, " Error: '%s'\n",
libusb_error_name(transferRetCode));
int ret = libusb_clear_halt(_device, LIBUSB_ENDPOINT_OUT | 2);
if (ret != 0) {
printf("tried to clear halt, error = %s\n. closing device",
libusb_error_name(ret));
libusb_close(_device);
_device = nullptr;
}
}
}
void USBRadio::receive() {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
// Handle USB events. This will call callbacks.
struct timeval tv = {0, 0};
libusb_handle_events_timeout(_usb_context, &tv);
}
// Note: this method assumes that sizeof(buf) == rtp::ReverseSize
void USBRadio::handleRxData(uint8_t* buf) {
RadioRx packet = RadioRx();
rtp::Header* header = (rtp::Header*)buf;
rtp::RobotStatusMessage* msg =
(rtp::RobotStatusMessage*)(buf + sizeof(rtp::Header));
packet.set_timestamp(RJ::timestamp());
packet.set_robot_id(msg->uid);
// Hardware version
packet.set_hardware_version(RJ2015);
// battery voltage
packet.set_battery(msg->battVoltage *
rtp::RobotStatusMessage::BATTERY_SCALE_FACTOR);
// ball sense
if (BallSenseStatus_IsValid(msg->ballSenseStatus)) {
packet.set_ball_sense_status(BallSenseStatus(msg->ballSenseStatus));
}
// Using same flags as 2011 robot. See firmware/robot2011/cpu/status.h.
// Report that everything is good b/c the bot currently has no way of
// detecting kicker issues
packet.set_kicker_status((msg->kickStatus ? Kicker_Charged : 0) |
Kicker_Enabled | Kicker_I2C_OK);
// motor errors
for (int i = 0; i < 5; i++) {
bool err = msg->motorErrors & (1 << i);
packet.add_motor_status(err ? MotorStatus::Hall_Failure
: MotorStatus::Good);
}
// fpga status
if (FpgaStatus_IsValid(msg->fpgaStatus)) {
packet.set_fpga_status(FpgaStatus(msg->fpgaStatus));
}
for (int index = 0; index < current_receive_debug.size(); ++index)
{
auto debugResponse = current_receive_debug[index];
auto debugResponseInfo = DebugCommunication::RESPONSE_INFO.at(debugResponse);
auto value = msg->debug_data.at(index);
auto packet_debug_response = packet.add_debug_responses();
packet_debug_response->set_key(debugResponseInfo.name);
packet_debug_response->set_value(value);
}
_reversePackets.push_back(packet);
}
void USBRadio::channel(int n) {
QMutexLocker lock(&_mutex);
if (_device) {
if (libusb_control_transfer(
_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioSetChannel, n, 0, nullptr, 0,
Control_Timeout)) {
throw runtime_error("USBRadio::channel control write failed");
}
}
Radio::channel(n);
}
<|endoftext|> |
<commit_before>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:
// 4103: used #pragma pack to change alignment
// 4114: same type qualifier used more than once
// 4201: nonstandard extension used : nameless struct/union
// 4237: "keyword" reserved for future use
// 4251: class needs to have dll-interface to export class
// 4275: non DLL-interface class used as base for DLL-interface class
// 4290: C++ Exception Specification ignored
// 4503: decorated name length exceeded, name was truncated
// 4786: string too long - truncated to 255 characters
#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)
#endif // WIN32
#include <osgProducer/Viewer>
#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>
#include <osgDB/FileUtils>
#include <osgDB/ReadFile>
#include <osgText/Text>
#include <osgTerrain/DataSet>
#include <osgGA/NodeTrackerManipulator>
class GraphicsContext {
public:
GraphicsContext()
{
rs = new Producer::RenderSurface;
rs->setWindowRectangle(0,0,1,1);
rs->useBorder(false);
rs->useConfigEventThread(false);
rs->realize();
}
virtual ~GraphicsContext()
{
}
private:
Producer::ref_ptr<Producer::RenderSurface> rs;
};
osg::Node* createEarth()
{
osg::ref_ptr<osg::Node> scene;
{
std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
// make osgTerrain::DataSet quieter..
osgTerrain::DataSet::setNotifyOffset(1);
osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;
// register the source imagery
{
osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);
source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));
source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);
dataSet->addSource(source);
}
// set up destination database paramters.
dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
dataSet->setConvertFromGeographicToGeocentric(true);
dataSet->setDestinationName("test.osg");
// load the source data and record sizes.
dataSet->loadSources();
GraphicsContext context;
dataSet->createDestination(30);
if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
else dataSet->writeDestination();
scene = dataSet->getDestinationRootNode();
}
return scene.release();
}
class ModelPositionCallback : public osg::NodeCallback
{
public:
ModelPositionCallback():
_latitude(0.0),
_longitude(0.0),
_height(100000.0)
{}
void updateParameters()
{
_latitude -= ((2.0*osg::PI)/360.0)/20.0;
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
updateParameters();
osg::NodePath nodePath = nv->getNodePath();
osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
if (mt)
{
osg::CoordinateSystemNode* csn = 0;
// find coordinate system node from our parental chain
unsigned int i;
for(i=0; i<nodePath.size() && csn==0; ++i)
{
csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
}
if (csn)
{
osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
if (ellipsoid)
{
osg::Matrixd matrix;
for(i+=1; i<nodePath.size()-1; ++i)
{
osg::Transform* transform = nodePath[i]->asTransform();
if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
}
//osg::Matrixd matrix;
ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
matrix.preMult(osg::Matrixd::rotate(_rotation));
mt->setMatrix(matrix);
}
}
}
traverse(node,nv);
}
double _latitude;
double _longitude;
double _height;
osg::Quat _rotation;
};
class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
FindNamedNodeVisitor(const std::string& name):
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_name(name) {}
virtual void apply(osg::Node& node)
{
if (node.getName()==_name)
{
_foundNodes.push_back(&node);
}
traverse(node);
}
typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
std::string _name;
NodeList _foundNodes;
};
int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
viewer.getCullSettings().setNearFarRatio(0.00001f);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
osg::Quat rotation;
osg::Vec4 vec4;
while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
{
osg::Quat local_rotate;
local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);
rotation = rotation * local_rotate;
}
osg::NodeCallback* nc = 0;
std::string flightpath_filename;
while (arguments.read("--flight-path",flightpath_filename))
{
std::ifstream fin(flightpath_filename.c_str());
if (fin)
{
osg::AnimationPath* path = new osg::AnimationPath;
path->read(fin);
nc = new osg::AnimationPathCallback(path);
}
}
osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
std::string mode;
while (arguments.read("--tracker-mode",mode))
{
if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
else
{
std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
std::cout<<" NODE_CENTER_AND_ROTATION"<<std::endl;
std::cout<<" NODE_CENTER_AND_AZIM"<<std::endl;
std::cout<<" NODE_CENTER"<<std::endl;
return 1;
}
}
osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
while (arguments.read("--rotation-mode",mode))
{
if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
else
{
std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
std::cout<<" TRACKBALL"<<std::endl;
std::cout<<" ELEVATION_AZIM"<<std::endl;
return 1;
}
}
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
osg::ref_ptr<osg::Node> root = createEarth();
if (!root) return 0;
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root.get());
osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
if (csn)
{
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
double s = 30000.0 / cessna->getBound().radius();
osg::MatrixTransform* scaler = new osg::MatrixTransform;
scaler->addChild(cessna);
scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);
osg::MatrixTransform* mt = new osg::MatrixTransform;
mt->addChild(scaler);
if (!nc) nc = new ModelPositionCallback;
mt->setUpdateCallback(nc);
csn->addChild(mt);
osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
tm->setTrackerMode(trackerMode);
tm->setRotationMode(rotationMode);
tm->setTrackNode(scaler);
unsigned int num = viewer.addCameraManipulator(tm);
viewer.selectCameraManipulator(num);
}
else
{
std::cout<<"Failed to read cessna.osg"<<std::endl;
}
}
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Corrected orientation of aeroplane and direction of rotation around earth.<commit_after>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:
// 4103: used #pragma pack to change alignment
// 4114: same type qualifier used more than once
// 4201: nonstandard extension used : nameless struct/union
// 4237: "keyword" reserved for future use
// 4251: class needs to have dll-interface to export class
// 4275: non DLL-interface class used as base for DLL-interface class
// 4290: C++ Exception Specification ignored
// 4503: decorated name length exceeded, name was truncated
// 4786: string too long - truncated to 255 characters
#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)
#endif // WIN32
#include <osgProducer/Viewer>
#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>
#include <osgDB/FileUtils>
#include <osgDB/ReadFile>
#include <osgText/Text>
#include <osgTerrain/DataSet>
#include <osgGA/NodeTrackerManipulator>
class GraphicsContext {
public:
GraphicsContext()
{
rs = new Producer::RenderSurface;
rs->setWindowRectangle(0,0,1,1);
rs->useBorder(false);
rs->useConfigEventThread(false);
rs->realize();
}
virtual ~GraphicsContext()
{
}
private:
Producer::ref_ptr<Producer::RenderSurface> rs;
};
osg::Node* createEarth()
{
osg::ref_ptr<osg::Node> scene;
{
std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
// make osgTerrain::DataSet quieter..
osgTerrain::DataSet::setNotifyOffset(1);
osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;
// register the source imagery
{
osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);
source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));
source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);
dataSet->addSource(source);
}
// set up destination database paramters.
dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
dataSet->setConvertFromGeographicToGeocentric(true);
dataSet->setDestinationName("test.osg");
// load the source data and record sizes.
dataSet->loadSources();
GraphicsContext context;
dataSet->createDestination(30);
if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
else dataSet->writeDestination();
scene = dataSet->getDestinationRootNode();
}
return scene.release();
}
class ModelPositionCallback : public osg::NodeCallback
{
public:
ModelPositionCallback():
_latitude(0.0),
_longitude(0.0),
_height(100000.0)
{
_rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
}
void updateParameters()
{
_longitude += ((2.0*osg::PI)/360.0)/20.0;
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
updateParameters();
osg::NodePath nodePath = nv->getNodePath();
osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
if (mt)
{
osg::CoordinateSystemNode* csn = 0;
// find coordinate system node from our parental chain
unsigned int i;
for(i=0; i<nodePath.size() && csn==0; ++i)
{
csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
}
if (csn)
{
osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
if (ellipsoid)
{
osg::Matrixd matrix;
for(i+=1; i<nodePath.size()-1; ++i)
{
osg::Transform* transform = nodePath[i]->asTransform();
if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
}
//osg::Matrixd matrix;
ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
matrix.preMult(osg::Matrixd::rotate(_rotation));
mt->setMatrix(matrix);
}
}
}
traverse(node,nv);
}
double _latitude;
double _longitude;
double _height;
osg::Quat _rotation;
};
class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
FindNamedNodeVisitor(const std::string& name):
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_name(name) {}
virtual void apply(osg::Node& node)
{
if (node.getName()==_name)
{
_foundNodes.push_back(&node);
}
traverse(node);
}
typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
std::string _name;
NodeList _foundNodes;
};
int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
viewer.getCullSettings().setNearFarRatio(0.00001f);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
osg::Quat rotation;
osg::Vec4 vec4;
while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
{
osg::Quat local_rotate;
local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);
rotation = rotation * local_rotate;
}
osg::NodeCallback* nc = 0;
std::string flightpath_filename;
while (arguments.read("--flight-path",flightpath_filename))
{
std::ifstream fin(flightpath_filename.c_str());
if (fin)
{
osg::AnimationPath* path = new osg::AnimationPath;
path->read(fin);
nc = new osg::AnimationPathCallback(path);
}
}
osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
std::string mode;
while (arguments.read("--tracker-mode",mode))
{
if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
else
{
std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
std::cout<<" NODE_CENTER_AND_ROTATION"<<std::endl;
std::cout<<" NODE_CENTER_AND_AZIM"<<std::endl;
std::cout<<" NODE_CENTER"<<std::endl;
return 1;
}
}
osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
while (arguments.read("--rotation-mode",mode))
{
if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
else
{
std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
std::cout<<" TRACKBALL"<<std::endl;
std::cout<<" ELEVATION_AZIM"<<std::endl;
return 1;
}
}
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
osg::ref_ptr<osg::Node> root = createEarth();
if (!root) return 0;
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root.get());
osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
if (csn)
{
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
double s = 30000.0 / cessna->getBound().radius();
osg::MatrixTransform* scaler = new osg::MatrixTransform;
scaler->addChild(cessna);
scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);
osg::MatrixTransform* mt = new osg::MatrixTransform;
mt->addChild(scaler);
if (!nc) nc = new ModelPositionCallback;
mt->setUpdateCallback(nc);
csn->addChild(mt);
osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
tm->setTrackerMode(trackerMode);
tm->setRotationMode(rotationMode);
tm->setTrackNode(scaler);
unsigned int num = viewer.addCameraManipulator(tm);
viewer.selectCameraManipulator(num);
}
else
{
std::cout<<"Failed to read cessna.osg"<<std::endl;
}
}
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Pkd.h"
#include <iostream>
#include <stdint.h>
#include <thread>
#define POS(idx, dim) pos(idx, dim)
using namespace megamol;
ospray::PkdBuilder::PkdBuilder()
: megamol::stdplugin::datatools::AbstractParticleManipulator("outData", "inData")
, inDataHash(0)
, outDataHash(0)
/*, numParticles(0)
, numInnerNodes(0)*/ {
//model = std::make_shared<ParticleModel>();
}
ospray::PkdBuilder::~PkdBuilder() { Release(); }
bool ospray::PkdBuilder::manipulateData(
core::moldyn::MultiParticleDataCall& outData, core::moldyn::MultiParticleDataCall& inData) {
if ((inData.DataHash() != inDataHash) || (inData.FrameID() != frameID)) {
inDataHash = inData.DataHash();
//outDataHash++;
frameID = inData.FrameID();
outData = inData;
models.resize(inData.GetParticleListCount());
for (unsigned int i = 0; i < inData.GetParticleListCount(); ++i) {
auto& parts = inData.AccessParticles(i);
auto& out = outData.AccessParticles(i);
// empty the model
// this->model->position.clear();
models[i].position.clear();
// put data the data into the model
// and build the pkd tree
// this->model->fill(parts);
models[i].fill(parts);
// this->build();
Pkd pkd;
pkd.model = &models[i];
pkd.build();
out.SetCount(parts.GetCount());
out.SetVertexData(
megamol::core::moldyn::SimpleSphericalParticles::VERTDATA_FLOAT_XYZ, &models[i].position[0].x, 16);
out.SetColourData(
megamol::core::moldyn::SimpleSphericalParticles::COLDATA_UINT8_RGBA, &models[i].position[0].w, 16);
out.SetGlobalRadius(parts.GetGlobalRadius());
}
outData.SetUnlocker(nullptr, false);
}
return true;
}
void ospray::Pkd::setDim(size_t ID, int dim) const {
#if DIM_FROM_DEPTH
return;
#else
ospcommon::vec3f& particle = (ospcommon::vec3f&)this->model->position[ID];
int& pxAsInt = (int&)particle.x;
pxAsInt = (pxAsInt & ~3) | dim;
#endif
}
inline size_t ospray::Pkd::maxDim(const ospcommon::vec3f& v) const {
const float maxVal = ospcommon::reduce_max(v);
if (maxVal == v.x) {
return 0;
} else if (maxVal == v.y) {
return 1;
} else if (maxVal == v.z) {
return 2;
} else {
assert(false && "Invalid max val index for vec!?");
return -1;
}
}
inline void ospray::Pkd::swap(const size_t a, const size_t b) const {
std::swap(model->position[a], model->position[b]);
}
void ospray::Pkd::build() {
// PING;
assert(this->model != NULL);
assert(!model->position.empty());
numParticles = model->position.size();
assert(numParticles <= (1ULL << 31));
#if 0
cout << "#osp:pkd: TEST: RANDOMIZING PARTICLES" << endl;
for (size_t i = numParticles - 1; i>0; --i) {
size_t j = size_t(drand48()*i);
if (i != j) swap(i, j);
}
cout << "#osp:pkd: RANDOMIZED" << endl;
#endif
numInnerNodes = numInnerNodesOf(numParticles);
// determine num levels
numLevels = 0;
size_t nodeID = 0;
while (isValidNode(nodeID)) {
++numLevels;
nodeID = leftChildOf(nodeID);
}
// PRINT(numLevels);
const ospcommon::box3f& bounds = model->getBounds();
/*std::cout << "#osp:pkd: bounds of model " << bounds << std::endl;
std::cout << "#osp:pkd: number of input particles " << numParticles << std::endl;*/
this->buildRec(0, bounds, 0);
}
void ospray::Pkd::buildRec(const size_t nodeID, const ospcommon::box3f& bounds, const size_t depth) const {
// if (depth < 4)
// std::cout << "#osp:pkd: building subtree " << nodeID << std::endl;
if (!hasLeftChild(nodeID))
// has no children -> it's a valid kd-tree already :-)
return;
// we have at least one child.
const size_t dim = this->maxDim(bounds.size());
// if (depth < 4) { PRINT(bounds); printf("depth %ld-> dim %ld\n",depth,dim); }
const size_t N = numParticles;
if (!hasRightChild(nodeID)) {
// no right child, but not a leaf emtpy. must have exactly one
// child on the left. see if we have to swap, but otherwise
// nothing to do.
size_t lChild = leftChildOf(nodeID);
if (POS(lChild, dim) > POS(nodeID, dim)) swap(nodeID, lChild);
// and done
setDim(nodeID, dim);
return;
}
{
// we have a left and a right subtree, each of at least 1 node.
SubtreeIterator l0(leftChildOf(nodeID));
SubtreeIterator r0(rightChildOf(nodeID));
SubtreeIterator l((size_t)l0); //(leftChildOf(nodeID));
SubtreeIterator r((size_t)r0); //(rightChildOf(nodeID));
// size_t numSwaps = 0, numComps = 0;
float rootPos = POS(nodeID, dim);
while (1) {
while (isValidNode(l, N) && (POS(l, dim) <= rootPos)) ++l;
while (isValidNode(r, N) && (POS(r, dim) >= rootPos)) ++r;
if (isValidNode(l, N)) {
if (isValidNode(r, N)) {
// both mis-mathces valid, just swap them and go on
swap(l, r);
++l;
++r;
continue;
} else {
// mis-match on left side, but nothing on right side to swap with: swap with root
// --> can't go on on right side any more, but can still compact matches on left
l0 = l;
++l;
while (isValidNode(l, N)) {
if (POS(l, dim) <= rootPos) {
swap(l0, l);
++l0;
}
++l;
}
swap(nodeID, l0);
++l0;
rootPos = POS(nodeID, dim);
l = l0;
r = r0;
continue;
}
} else {
if (isValidNode(r, N)) {
// mis-match on left side, but nothing on right side to swap with: swap with root
// --> can't go on on right side any more, but can still compact matches on left
r0 = r;
++r;
while (isValidNode(r, N)) {
if (POS(r, dim) >= rootPos) {
swap(r0, r);
++r0;
}
++r;
}
swap(nodeID, r0);
++r0;
rootPos = POS(nodeID, dim);
l = l0;
r = r0;
continue;
} else {
// no mis-match on either side ... done.
break;
}
}
}
}
ospcommon::box3f lBounds = bounds;
ospcommon::box3f rBounds = bounds;
setDim(nodeID, dim);
lBounds.upper[dim] = rBounds.lower[dim] = pos(nodeID, dim);
if ((numLevels - depth) > 20) {
std::thread lThread(&pkdBuildThread, new PKDBuildJob(this, leftChildOf(nodeID), lBounds, depth + 1));
buildRec(rightChildOf(nodeID), rBounds, depth + 1);
lThread.join();
} else {
buildRec(leftChildOf(nodeID), lBounds, depth + 1);
buildRec(rightChildOf(nodeID), rBounds, depth + 1);
}
}
<commit_msg>better init value for datahash<commit_after>#include "stdafx.h"
#include "Pkd.h"
#include <iostream>
#include <stdint.h>
#include <thread>
#define POS(idx, dim) pos(idx, dim)
using namespace megamol;
ospray::PkdBuilder::PkdBuilder()
: megamol::stdplugin::datatools::AbstractParticleManipulator("outData", "inData")
, inDataHash(std::numeric_limits<size_t>::max())
, outDataHash(0)
/*, numParticles(0)
, numInnerNodes(0)*/ {
//model = std::make_shared<ParticleModel>();
}
ospray::PkdBuilder::~PkdBuilder() { Release(); }
bool ospray::PkdBuilder::manipulateData(
core::moldyn::MultiParticleDataCall& outData, core::moldyn::MultiParticleDataCall& inData) {
if ((inData.DataHash() != inDataHash) || (inData.FrameID() != frameID)) {
inDataHash = inData.DataHash();
//outDataHash++;
frameID = inData.FrameID();
outData = inData;
models.resize(inData.GetParticleListCount());
for (unsigned int i = 0; i < inData.GetParticleListCount(); ++i) {
auto& parts = inData.AccessParticles(i);
auto& out = outData.AccessParticles(i);
// empty the model
// this->model->position.clear();
models[i].position.clear();
// put data the data into the model
// and build the pkd tree
// this->model->fill(parts);
models[i].fill(parts);
// this->build();
Pkd pkd;
pkd.model = &models[i];
pkd.build();
out.SetCount(parts.GetCount());
out.SetVertexData(
megamol::core::moldyn::SimpleSphericalParticles::VERTDATA_FLOAT_XYZ, &models[i].position[0].x, 16);
out.SetColourData(
megamol::core::moldyn::SimpleSphericalParticles::COLDATA_UINT8_RGBA, &models[i].position[0].w, 16);
out.SetGlobalRadius(parts.GetGlobalRadius());
}
outData.SetUnlocker(nullptr, false);
}
return true;
}
void ospray::Pkd::setDim(size_t ID, int dim) const {
#if DIM_FROM_DEPTH
return;
#else
ospcommon::vec3f& particle = (ospcommon::vec3f&)this->model->position[ID];
int& pxAsInt = (int&)particle.x;
pxAsInt = (pxAsInt & ~3) | dim;
#endif
}
inline size_t ospray::Pkd::maxDim(const ospcommon::vec3f& v) const {
const float maxVal = ospcommon::reduce_max(v);
if (maxVal == v.x) {
return 0;
} else if (maxVal == v.y) {
return 1;
} else if (maxVal == v.z) {
return 2;
} else {
assert(false && "Invalid max val index for vec!?");
return -1;
}
}
inline void ospray::Pkd::swap(const size_t a, const size_t b) const {
std::swap(model->position[a], model->position[b]);
}
void ospray::Pkd::build() {
// PING;
assert(this->model != NULL);
assert(!model->position.empty());
numParticles = model->position.size();
assert(numParticles <= (1ULL << 31));
#if 0
cout << "#osp:pkd: TEST: RANDOMIZING PARTICLES" << endl;
for (size_t i = numParticles - 1; i>0; --i) {
size_t j = size_t(drand48()*i);
if (i != j) swap(i, j);
}
cout << "#osp:pkd: RANDOMIZED" << endl;
#endif
numInnerNodes = numInnerNodesOf(numParticles);
// determine num levels
numLevels = 0;
size_t nodeID = 0;
while (isValidNode(nodeID)) {
++numLevels;
nodeID = leftChildOf(nodeID);
}
// PRINT(numLevels);
const ospcommon::box3f& bounds = model->getBounds();
/*std::cout << "#osp:pkd: bounds of model " << bounds << std::endl;
std::cout << "#osp:pkd: number of input particles " << numParticles << std::endl;*/
this->buildRec(0, bounds, 0);
}
void ospray::Pkd::buildRec(const size_t nodeID, const ospcommon::box3f& bounds, const size_t depth) const {
// if (depth < 4)
// std::cout << "#osp:pkd: building subtree " << nodeID << std::endl;
if (!hasLeftChild(nodeID))
// has no children -> it's a valid kd-tree already :-)
return;
// we have at least one child.
const size_t dim = this->maxDim(bounds.size());
// if (depth < 4) { PRINT(bounds); printf("depth %ld-> dim %ld\n",depth,dim); }
const size_t N = numParticles;
if (!hasRightChild(nodeID)) {
// no right child, but not a leaf emtpy. must have exactly one
// child on the left. see if we have to swap, but otherwise
// nothing to do.
size_t lChild = leftChildOf(nodeID);
if (POS(lChild, dim) > POS(nodeID, dim)) swap(nodeID, lChild);
// and done
setDim(nodeID, dim);
return;
}
{
// we have a left and a right subtree, each of at least 1 node.
SubtreeIterator l0(leftChildOf(nodeID));
SubtreeIterator r0(rightChildOf(nodeID));
SubtreeIterator l((size_t)l0); //(leftChildOf(nodeID));
SubtreeIterator r((size_t)r0); //(rightChildOf(nodeID));
// size_t numSwaps = 0, numComps = 0;
float rootPos = POS(nodeID, dim);
while (1) {
while (isValidNode(l, N) && (POS(l, dim) <= rootPos)) ++l;
while (isValidNode(r, N) && (POS(r, dim) >= rootPos)) ++r;
if (isValidNode(l, N)) {
if (isValidNode(r, N)) {
// both mis-mathces valid, just swap them and go on
swap(l, r);
++l;
++r;
continue;
} else {
// mis-match on left side, but nothing on right side to swap with: swap with root
// --> can't go on on right side any more, but can still compact matches on left
l0 = l;
++l;
while (isValidNode(l, N)) {
if (POS(l, dim) <= rootPos) {
swap(l0, l);
++l0;
}
++l;
}
swap(nodeID, l0);
++l0;
rootPos = POS(nodeID, dim);
l = l0;
r = r0;
continue;
}
} else {
if (isValidNode(r, N)) {
// mis-match on left side, but nothing on right side to swap with: swap with root
// --> can't go on on right side any more, but can still compact matches on left
r0 = r;
++r;
while (isValidNode(r, N)) {
if (POS(r, dim) >= rootPos) {
swap(r0, r);
++r0;
}
++r;
}
swap(nodeID, r0);
++r0;
rootPos = POS(nodeID, dim);
l = l0;
r = r0;
continue;
} else {
// no mis-match on either side ... done.
break;
}
}
}
}
ospcommon::box3f lBounds = bounds;
ospcommon::box3f rBounds = bounds;
setDim(nodeID, dim);
lBounds.upper[dim] = rBounds.lower[dim] = pos(nodeID, dim);
if ((numLevels - depth) > 20) {
std::thread lThread(&pkdBuildThread, new PKDBuildJob(this, leftChildOf(nodeID), lBounds, depth + 1));
buildRec(rightChildOf(nodeID), rBounds, depth + 1);
lThread.join();
} else {
buildRec(leftChildOf(nodeID), lBounds, depth + 1);
buildRec(rightChildOf(nodeID), rBounds, depth + 1);
}
}
<|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 "app/clipboard/clipboard.h"
#include <gtk/gtk.h>
#include <map>
#include <set>
#include <string>
#include <utility>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gtk_util.h"
#include "base/utf_string_conversions.h"
#include "gfx/size.h"
namespace {
const char kMimeBmp[] = "image/bmp";
const char kMimeHtml[] = "text/html";
const char kMimeText[] = "text/plain";
const char kMimeURI[] = "text/uri-list";
const char kMimeWebkitSmartPaste[] = "chromium/x-webkit-paste";
std::string GdkAtomToString(const GdkAtom& atom) {
gchar* name = gdk_atom_name(atom);
std::string rv(name);
g_free(name);
return rv;
}
GdkAtom StringToGdkAtom(const std::string& str) {
return gdk_atom_intern(str.c_str(), FALSE);
}
// GtkClipboardGetFunc callback.
// GTK will call this when an application wants data we copied to the clipboard.
void GetData(GtkClipboard* clipboard,
GtkSelectionData* selection_data,
guint info,
gpointer user_data) {
Clipboard::TargetMap* data_map =
reinterpret_cast<Clipboard::TargetMap*>(user_data);
std::string target_string = GdkAtomToString(selection_data->target);
Clipboard::TargetMap::iterator iter = data_map->find(target_string);
if (iter == data_map->end())
return;
if (target_string == kMimeBmp) {
gtk_selection_data_set_pixbuf(selection_data,
reinterpret_cast<GdkPixbuf*>(iter->second.first));
} else if (target_string == kMimeURI) {
gchar* uri_list[2];
uri_list[0] = reinterpret_cast<gchar*>(iter->second.first);
uri_list[1] = NULL;
gtk_selection_data_set_uris(selection_data, uri_list);
} else {
gtk_selection_data_set(selection_data, selection_data->target, 8,
reinterpret_cast<guchar*>(iter->second.first),
iter->second.second);
}
}
// GtkClipboardClearFunc callback.
// We are guaranteed this will be called exactly once for each call to
// gtk_clipboard_set_with_data.
void ClearData(GtkClipboard* clipboard,
gpointer user_data) {
Clipboard::TargetMap* map =
reinterpret_cast<Clipboard::TargetMap*>(user_data);
// The same data may be inserted under multiple keys, so use a set to
// uniq them.
std::set<char*> ptrs;
for (Clipboard::TargetMap::iterator iter = map->begin();
iter != map->end(); ++iter) {
if (iter->first == kMimeBmp)
g_object_unref(reinterpret_cast<GdkPixbuf*>(iter->second.first));
else
ptrs.insert(iter->second.first);
}
for (std::set<char*>::iterator iter = ptrs.begin();
iter != ptrs.end(); ++iter) {
delete[] *iter;
}
delete map;
}
// Called on GdkPixbuf destruction; see WriteBitmap().
void GdkPixbufFree(guchar* pixels, gpointer data) {
free(pixels);
}
} // namespace
Clipboard::Clipboard() {
clipboard_ = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
primary_selection_ = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
}
Clipboard::~Clipboard() {
// TODO(estade): do we want to save clipboard data after we exit?
// gtk_clipboard_set_can_store and gtk_clipboard_store work
// but have strangely awful performance.
}
void Clipboard::WriteObjects(const ObjectMap& objects) {
clipboard_data_ = new TargetMap();
for (ObjectMap::const_iterator iter = objects.begin();
iter != objects.end(); ++iter) {
DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
}
SetGtkClipboard();
}
// When a URL is copied from a render view context menu (via "copy link
// location", for example), we additionally stick it in the X clipboard. This
// matches other linux browsers.
void Clipboard::DidWriteURL(const std::string& utf8_text) {
gtk_clipboard_set_text(primary_selection_, utf8_text.c_str(),
utf8_text.length());
}
// Take ownership of the GTK clipboard and inform it of the targets we support.
void Clipboard::SetGtkClipboard() {
scoped_array<GtkTargetEntry> targets(
new GtkTargetEntry[clipboard_data_->size()]);
int i = 0;
for (Clipboard::TargetMap::iterator iter = clipboard_data_->begin();
iter != clipboard_data_->end(); ++iter, ++i) {
targets[i].target = const_cast<char*>(iter->first.c_str());
targets[i].flags = 0;
targets[i].info = 0;
}
gtk_clipboard_set_with_data(clipboard_, targets.get(),
clipboard_data_->size(),
GetData, ClearData,
clipboard_data_);
// clipboard_data_ now owned by the GtkClipboard.
clipboard_data_ = NULL;
}
void Clipboard::WriteText(const char* text_data, size_t text_len) {
char* data = new char[text_len + 1];
memcpy(data, text_data, text_len);
data[text_len] = '\0';
InsertMapping(kMimeText, data, text_len);
InsertMapping("TEXT", data, text_len);
InsertMapping("STRING", data, text_len);
InsertMapping("UTF8_STRING", data, text_len);
InsertMapping("COMPOUND_TEXT", data, text_len);
}
void Clipboard::WriteHTML(const char* markup_data,
size_t markup_len,
const char* url_data,
size_t url_len) {
// TODO(estade): We need to expand relative links with |url_data|.
static const char* html_prefix = "<meta http-equiv=\"content-type\" "
"content=\"text/html; charset=utf-8\">";
size_t html_prefix_len = strlen(html_prefix);
size_t total_len = html_prefix_len + markup_len + 1;
char* data = new char[total_len];
snprintf(data, total_len, "%s", html_prefix);
memcpy(data + html_prefix_len, markup_data, markup_len);
data[total_len - 1] = '\0';
InsertMapping(kMimeHtml, data, total_len);
}
// Write an extra flavor that signifies WebKit was the last to modify the
// pasteboard. This flavor has no data.
void Clipboard::WriteWebSmartPaste() {
InsertMapping(kMimeWebkitSmartPaste, NULL, 0);
}
void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) {
const gfx::Size* size = reinterpret_cast<const gfx::Size*>(size_data);
guchar* data =
gtk_util::BGRAToRGBA(reinterpret_cast<const uint8_t*>(pixel_data),
size->width(), size->height(), 0);
GdkPixbuf* pixbuf =
gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE,
8, size->width(), size->height(),
size->width() * 4, GdkPixbufFree, NULL);
// We store the GdkPixbuf*, and the size_t half of the pair is meaningless.
// Note that this contrasts with the vast majority of entries in our target
// map, which directly store the data and its length.
InsertMapping(kMimeBmp, reinterpret_cast<char*>(pixbuf), 0);
}
void Clipboard::WriteBookmark(const char* title_data, size_t title_len,
const char* url_data, size_t url_len) {
// Write as a URI.
char* data = new char[url_len + 1];
memcpy(data, url_data, url_len);
data[url_len] = '\0';
InsertMapping(kMimeURI, data, url_len + 1);
}
void Clipboard::WriteData(const char* format_name, size_t format_len,
const char* data_data, size_t data_len) {
char* data = new char[data_len];
memcpy(data, data_data, data_len);
std::string format(format_name, format_len);
// We assume that certain mapping types are only written by trusted code.
// Therefore we must upkeep their integrity.
if (format == kMimeBmp || format == kMimeURI)
return;
InsertMapping(format.c_str(), data, data_len);
}
// We do not use gtk_clipboard_wait_is_target_available because of
// a bug with the gtk clipboard. It caches the available targets
// and does not always refresh the cache when it is appropriate.
bool Clipboard::IsFormatAvailable(const Clipboard::FormatType& format,
Clipboard::Buffer buffer) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return false;
bool format_is_plain_text = GetPlainTextFormatType() == format;
if (format_is_plain_text) {
// This tries a number of common text targets.
if (gtk_clipboard_wait_is_text_available(clipboard))
return true;
}
bool retval = false;
GdkAtom* targets = NULL;
GtkSelectionData* data =
gtk_clipboard_wait_for_contents(clipboard,
gdk_atom_intern("TARGETS", false));
if (!data)
return false;
int num = 0;
gtk_selection_data_get_targets(data, &targets, &num);
// Some programs post data to the clipboard without any targets. If this is
// the case we attempt to make sense of the contents as text. This is pretty
// unfortunate since it means we have to actually copy the data to see if it
// is available, but at least this path shouldn't be hit for conforming
// programs.
if (num <= 0) {
if (format_is_plain_text) {
gchar* text = gtk_clipboard_wait_for_text(clipboard);
if (text) {
g_free(text);
retval = true;
}
}
}
GdkAtom format_atom = StringToGdkAtom(format);
for (int i = 0; i < num; i++) {
if (targets[i] == format_atom) {
retval = true;
break;
}
}
g_free(targets);
gtk_selection_data_free(data);
return retval;
}
bool Clipboard::IsFormatAvailableByString(const std::string& format,
Clipboard::Buffer buffer) const {
return IsFormatAvailable(format, buffer);
}
void Clipboard::ReadText(Clipboard::Buffer buffer, string16* result) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return;
result->clear();
gchar* text = gtk_clipboard_wait_for_text(clipboard);
if (text == NULL)
return;
// TODO(estade): do we want to handle the possible error here?
UTF8ToUTF16(text, strlen(text), result);
g_free(text);
}
void Clipboard::ReadAsciiText(Clipboard::Buffer buffer,
std::string* result) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return;
result->clear();
gchar* text = gtk_clipboard_wait_for_text(clipboard);
if (text == NULL)
return;
result->assign(text);
g_free(text);
}
void Clipboard::ReadFile(FilePath* file) const {
*file = FilePath();
}
// TODO(estade): handle different charsets.
// TODO(port): set *src_url.
void Clipboard::ReadHTML(Clipboard::Buffer buffer, string16* markup,
std::string* src_url) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return;
markup->clear();
GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard,
StringToGdkAtom(GetHtmlFormatType()));
if (!data)
return;
// If the data starts with 0xFEFF, i.e., Byte Order Mark, assume it is
// UTF-16, otherwise assume UTF-8.
if (data->length >= 2 &&
reinterpret_cast<uint16_t*>(data->data)[0] == 0xFEFF) {
markup->assign(reinterpret_cast<uint16_t*>(data->data) + 1,
(data->length / 2) - 1);
} else {
UTF8ToUTF16(reinterpret_cast<char*>(data->data), data->length, markup);
}
gtk_selection_data_free(data);
}
void Clipboard::ReadBookmark(string16* title, std::string* url) const {
// TODO(estade): implement this.
NOTIMPLEMENTED();
}
void Clipboard::ReadData(const std::string& format, std::string* result) {
GtkSelectionData* data =
gtk_clipboard_wait_for_contents(clipboard_, StringToGdkAtom(format));
if (!data)
return;
result->assign(reinterpret_cast<char*>(data->data), data->length);
gtk_selection_data_free(data);
}
// static
Clipboard::FormatType Clipboard::GetPlainTextFormatType() {
return GdkAtomToString(GDK_TARGET_STRING);
}
// static
Clipboard::FormatType Clipboard::GetPlainTextWFormatType() {
return GetPlainTextFormatType();
}
// static
Clipboard::FormatType Clipboard::GetHtmlFormatType() {
return std::string(kMimeHtml);
}
// static
Clipboard::FormatType Clipboard::GetBitmapFormatType() {
return std::string(kMimeBmp);
}
// static
Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() {
return std::string(kMimeWebkitSmartPaste);
}
void Clipboard::InsertMapping(const char* key,
char* data,
size_t data_len) {
DCHECK(clipboard_data_->find(key) == clipboard_data_->end());
(*clipboard_data_)[key] = std::make_pair(data, data_len);
}
GtkClipboard* Clipboard::LookupBackingClipboard(Buffer clipboard) const {
switch (clipboard) {
case BUFFER_STANDARD:
return clipboard_;
case BUFFER_SELECTION:
return primary_selection_;
default:
NOTREACHED();
return NULL;
}
}
<commit_msg>GTK - don't paste a garbage text/html character.<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 "app/clipboard/clipboard.h"
#include <gtk/gtk.h>
#include <map>
#include <set>
#include <string>
#include <utility>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gtk_util.h"
#include "base/utf_string_conversions.h"
#include "gfx/size.h"
namespace {
const char kMimeBmp[] = "image/bmp";
const char kMimeHtml[] = "text/html";
const char kMimeText[] = "text/plain";
const char kMimeURI[] = "text/uri-list";
const char kMimeWebkitSmartPaste[] = "chromium/x-webkit-paste";
std::string GdkAtomToString(const GdkAtom& atom) {
gchar* name = gdk_atom_name(atom);
std::string rv(name);
g_free(name);
return rv;
}
GdkAtom StringToGdkAtom(const std::string& str) {
return gdk_atom_intern(str.c_str(), FALSE);
}
// GtkClipboardGetFunc callback.
// GTK will call this when an application wants data we copied to the clipboard.
void GetData(GtkClipboard* clipboard,
GtkSelectionData* selection_data,
guint info,
gpointer user_data) {
Clipboard::TargetMap* data_map =
reinterpret_cast<Clipboard::TargetMap*>(user_data);
std::string target_string = GdkAtomToString(selection_data->target);
Clipboard::TargetMap::iterator iter = data_map->find(target_string);
if (iter == data_map->end())
return;
if (target_string == kMimeBmp) {
gtk_selection_data_set_pixbuf(selection_data,
reinterpret_cast<GdkPixbuf*>(iter->second.first));
} else if (target_string == kMimeURI) {
gchar* uri_list[2];
uri_list[0] = reinterpret_cast<gchar*>(iter->second.first);
uri_list[1] = NULL;
gtk_selection_data_set_uris(selection_data, uri_list);
} else {
gtk_selection_data_set(selection_data, selection_data->target, 8,
reinterpret_cast<guchar*>(iter->second.first),
iter->second.second);
}
}
// GtkClipboardClearFunc callback.
// We are guaranteed this will be called exactly once for each call to
// gtk_clipboard_set_with_data.
void ClearData(GtkClipboard* clipboard,
gpointer user_data) {
Clipboard::TargetMap* map =
reinterpret_cast<Clipboard::TargetMap*>(user_data);
// The same data may be inserted under multiple keys, so use a set to
// uniq them.
std::set<char*> ptrs;
for (Clipboard::TargetMap::iterator iter = map->begin();
iter != map->end(); ++iter) {
if (iter->first == kMimeBmp)
g_object_unref(reinterpret_cast<GdkPixbuf*>(iter->second.first));
else
ptrs.insert(iter->second.first);
}
for (std::set<char*>::iterator iter = ptrs.begin();
iter != ptrs.end(); ++iter) {
delete[] *iter;
}
delete map;
}
// Called on GdkPixbuf destruction; see WriteBitmap().
void GdkPixbufFree(guchar* pixels, gpointer data) {
free(pixels);
}
} // namespace
Clipboard::Clipboard() {
clipboard_ = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
primary_selection_ = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
}
Clipboard::~Clipboard() {
// TODO(estade): do we want to save clipboard data after we exit?
// gtk_clipboard_set_can_store and gtk_clipboard_store work
// but have strangely awful performance.
}
void Clipboard::WriteObjects(const ObjectMap& objects) {
clipboard_data_ = new TargetMap();
for (ObjectMap::const_iterator iter = objects.begin();
iter != objects.end(); ++iter) {
DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
}
SetGtkClipboard();
}
// When a URL is copied from a render view context menu (via "copy link
// location", for example), we additionally stick it in the X clipboard. This
// matches other linux browsers.
void Clipboard::DidWriteURL(const std::string& utf8_text) {
gtk_clipboard_set_text(primary_selection_, utf8_text.c_str(),
utf8_text.length());
}
// Take ownership of the GTK clipboard and inform it of the targets we support.
void Clipboard::SetGtkClipboard() {
scoped_array<GtkTargetEntry> targets(
new GtkTargetEntry[clipboard_data_->size()]);
int i = 0;
for (Clipboard::TargetMap::iterator iter = clipboard_data_->begin();
iter != clipboard_data_->end(); ++iter, ++i) {
targets[i].target = const_cast<char*>(iter->first.c_str());
targets[i].flags = 0;
targets[i].info = 0;
}
gtk_clipboard_set_with_data(clipboard_, targets.get(),
clipboard_data_->size(),
GetData, ClearData,
clipboard_data_);
// clipboard_data_ now owned by the GtkClipboard.
clipboard_data_ = NULL;
}
void Clipboard::WriteText(const char* text_data, size_t text_len) {
char* data = new char[text_len];
memcpy(data, text_data, text_len);
InsertMapping(kMimeText, data, text_len);
InsertMapping("TEXT", data, text_len);
InsertMapping("STRING", data, text_len);
InsertMapping("UTF8_STRING", data, text_len);
InsertMapping("COMPOUND_TEXT", data, text_len);
}
void Clipboard::WriteHTML(const char* markup_data,
size_t markup_len,
const char* url_data,
size_t url_len) {
// TODO(estade): We need to expand relative links with |url_data|.
static const char* html_prefix = "<meta http-equiv=\"content-type\" "
"content=\"text/html; charset=utf-8\">";
size_t html_prefix_len = strlen(html_prefix);
size_t total_len = html_prefix_len + markup_len + 1;
char* data = new char[total_len];
snprintf(data, total_len, "%s", html_prefix);
memcpy(data + html_prefix_len, markup_data, markup_len);
// Some programs expect NULL-terminated data. See http://crbug.com/42624
data[total_len - 1] = '\0';
InsertMapping(kMimeHtml, data, total_len);
}
// Write an extra flavor that signifies WebKit was the last to modify the
// pasteboard. This flavor has no data.
void Clipboard::WriteWebSmartPaste() {
InsertMapping(kMimeWebkitSmartPaste, NULL, 0);
}
void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) {
const gfx::Size* size = reinterpret_cast<const gfx::Size*>(size_data);
guchar* data =
gtk_util::BGRAToRGBA(reinterpret_cast<const uint8_t*>(pixel_data),
size->width(), size->height(), 0);
GdkPixbuf* pixbuf =
gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE,
8, size->width(), size->height(),
size->width() * 4, GdkPixbufFree, NULL);
// We store the GdkPixbuf*, and the size_t half of the pair is meaningless.
// Note that this contrasts with the vast majority of entries in our target
// map, which directly store the data and its length.
InsertMapping(kMimeBmp, reinterpret_cast<char*>(pixbuf), 0);
}
void Clipboard::WriteBookmark(const char* title_data, size_t title_len,
const char* url_data, size_t url_len) {
// Write as a URI.
char* data = new char[url_len + 1];
memcpy(data, url_data, url_len);
data[url_len] = '\0';
InsertMapping(kMimeURI, data, url_len + 1);
}
void Clipboard::WriteData(const char* format_name, size_t format_len,
const char* data_data, size_t data_len) {
char* data = new char[data_len];
memcpy(data, data_data, data_len);
std::string format(format_name, format_len);
// We assume that certain mapping types are only written by trusted code.
// Therefore we must upkeep their integrity.
if (format == kMimeBmp || format == kMimeURI)
return;
InsertMapping(format.c_str(), data, data_len);
}
// We do not use gtk_clipboard_wait_is_target_available because of
// a bug with the gtk clipboard. It caches the available targets
// and does not always refresh the cache when it is appropriate.
bool Clipboard::IsFormatAvailable(const Clipboard::FormatType& format,
Clipboard::Buffer buffer) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return false;
bool format_is_plain_text = GetPlainTextFormatType() == format;
if (format_is_plain_text) {
// This tries a number of common text targets.
if (gtk_clipboard_wait_is_text_available(clipboard))
return true;
}
bool retval = false;
GdkAtom* targets = NULL;
GtkSelectionData* data =
gtk_clipboard_wait_for_contents(clipboard,
gdk_atom_intern("TARGETS", false));
if (!data)
return false;
int num = 0;
gtk_selection_data_get_targets(data, &targets, &num);
// Some programs post data to the clipboard without any targets. If this is
// the case we attempt to make sense of the contents as text. This is pretty
// unfortunate since it means we have to actually copy the data to see if it
// is available, but at least this path shouldn't be hit for conforming
// programs.
if (num <= 0) {
if (format_is_plain_text) {
gchar* text = gtk_clipboard_wait_for_text(clipboard);
if (text) {
g_free(text);
retval = true;
}
}
}
GdkAtom format_atom = StringToGdkAtom(format);
for (int i = 0; i < num; i++) {
if (targets[i] == format_atom) {
retval = true;
break;
}
}
g_free(targets);
gtk_selection_data_free(data);
return retval;
}
bool Clipboard::IsFormatAvailableByString(const std::string& format,
Clipboard::Buffer buffer) const {
return IsFormatAvailable(format, buffer);
}
void Clipboard::ReadText(Clipboard::Buffer buffer, string16* result) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return;
result->clear();
gchar* text = gtk_clipboard_wait_for_text(clipboard);
if (text == NULL)
return;
// TODO(estade): do we want to handle the possible error here?
UTF8ToUTF16(text, strlen(text), result);
g_free(text);
}
void Clipboard::ReadAsciiText(Clipboard::Buffer buffer,
std::string* result) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return;
result->clear();
gchar* text = gtk_clipboard_wait_for_text(clipboard);
if (text == NULL)
return;
result->assign(text);
g_free(text);
}
void Clipboard::ReadFile(FilePath* file) const {
*file = FilePath();
}
// TODO(estade): handle different charsets.
// TODO(port): set *src_url.
void Clipboard::ReadHTML(Clipboard::Buffer buffer, string16* markup,
std::string* src_url) const {
GtkClipboard* clipboard = LookupBackingClipboard(buffer);
if (clipboard == NULL)
return;
markup->clear();
GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard,
StringToGdkAtom(GetHtmlFormatType()));
if (!data)
return;
// If the data starts with 0xFEFF, i.e., Byte Order Mark, assume it is
// UTF-16, otherwise assume UTF-8.
if (data->length >= 2 &&
reinterpret_cast<uint16_t*>(data->data)[0] == 0xFEFF) {
markup->assign(reinterpret_cast<uint16_t*>(data->data) + 1,
(data->length / 2) - 1);
} else {
UTF8ToUTF16(reinterpret_cast<char*>(data->data), data->length, markup);
}
// If there is a terminating NULL, drop it.
if (markup->at(markup->length() - 1) == '\0')
markup->resize(markup->length() - 1);
gtk_selection_data_free(data);
}
void Clipboard::ReadBookmark(string16* title, std::string* url) const {
// TODO(estade): implement this.
NOTIMPLEMENTED();
}
void Clipboard::ReadData(const std::string& format, std::string* result) {
GtkSelectionData* data =
gtk_clipboard_wait_for_contents(clipboard_, StringToGdkAtom(format));
if (!data)
return;
result->assign(reinterpret_cast<char*>(data->data), data->length);
gtk_selection_data_free(data);
}
// static
Clipboard::FormatType Clipboard::GetPlainTextFormatType() {
return GdkAtomToString(GDK_TARGET_STRING);
}
// static
Clipboard::FormatType Clipboard::GetPlainTextWFormatType() {
return GetPlainTextFormatType();
}
// static
Clipboard::FormatType Clipboard::GetHtmlFormatType() {
return std::string(kMimeHtml);
}
// static
Clipboard::FormatType Clipboard::GetBitmapFormatType() {
return std::string(kMimeBmp);
}
// static
Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() {
return std::string(kMimeWebkitSmartPaste);
}
void Clipboard::InsertMapping(const char* key,
char* data,
size_t data_len) {
DCHECK(clipboard_data_->find(key) == clipboard_data_->end());
(*clipboard_data_)[key] = std::make_pair(data, data_len);
}
GtkClipboard* Clipboard::LookupBackingClipboard(Buffer clipboard) const {
switch (clipboard) {
case BUFFER_STANDARD:
return clipboard_;
case BUFFER_SELECTION:
return primary_selection_;
default:
NOTREACHED();
return NULL;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options/password_manager_handler.h"
#include "base/callback.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/password_form.h"
PasswordManagerHandler::PasswordManagerHandler()
: ALLOW_THIS_IN_INITIALIZER_LIST(populater_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(exception_populater_(this)) {
}
PasswordManagerHandler::~PasswordManagerHandler() {
PasswordStore* store = GetPasswordStore();
if (store)
store->RemoveObserver(this);
}
void PasswordManagerHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
static const OptionsStringResource resources[] = {
{ "savedPasswordsTitle",
IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
{ "passwordExceptionsTitle",
IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
{ "passwordSearchPlaceholder",
IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
{ "passwordShowButton",
IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
{ "passwordHideButton",
IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
{ "passwordsSiteColumn",
IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN },
{ "passwordsUsernameColumn",
IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN },
{ "passwordsRemoveButton",
IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON },
{ "passwordsNoPasswordsDescription",
IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
{ "passwordsNoExceptionsDescription",
IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
{ "passwordsRemoveAllButton",
IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON },
{ "passwordsRemoveAllTitle",
IDS_PASSWORDS_PAGE_VIEW_CAPTION_DELETE_ALL_PASSWORDS },
{ "passwordsRemoveAllWarning",
IDS_PASSWORDS_PAGE_VIEW_TEXT_DELETE_ALL_PASSWORDS },
};
RegisterStrings(localized_strings, resources, arraysize(resources));
RegisterTitle(localized_strings, "passwordsPage",
IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);
localized_strings->SetString("passwordManagerLearnMoreURL",
google_util::AppendGoogleLocaleParam(
GURL(chrome::kPasswordManagerLearnMoreURL)).spec());
}
void PasswordManagerHandler::Initialize() {
show_passwords_.Init(prefs::kPasswordManagerAllowShowPasswords,
web_ui_->GetProfile()->GetPrefs(), this);
// We should not cache web_ui_->GetProfile(). See crosbug.com/6304.
PasswordStore* store = GetPasswordStore();
if (store)
store->AddObserver(this);
}
void PasswordManagerHandler::RegisterMessages() {
DCHECK(web_ui_);
web_ui_->RegisterMessageCallback("updatePasswordLists",
NewCallback(this, &PasswordManagerHandler::UpdatePasswordLists));
web_ui_->RegisterMessageCallback("removeSavedPassword",
NewCallback(this, &PasswordManagerHandler::RemoveSavedPassword));
web_ui_->RegisterMessageCallback("removePasswordException",
NewCallback(this, &PasswordManagerHandler::RemovePasswordException));
web_ui_->RegisterMessageCallback("removeAllSavedPasswords",
NewCallback(this, &PasswordManagerHandler::RemoveAllSavedPasswords));
web_ui_->RegisterMessageCallback("removeAllPasswordExceptions", NewCallback(
this, &PasswordManagerHandler::RemoveAllPasswordExceptions));
}
void PasswordManagerHandler::OnLoginsChanged() {
UpdatePasswordLists(NULL);
}
PasswordStore* PasswordManagerHandler::GetPasswordStore() {
return web_ui_->GetProfile()->GetPasswordStore(Profile::EXPLICIT_ACCESS);
}
void PasswordManagerHandler::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == chrome::NOTIFICATION_PREF_CHANGED) {
std::string* pref_name = Details<std::string>(details).ptr();
if (*pref_name == prefs::kPasswordManagerAllowShowPasswords) {
UpdatePasswordLists(NULL);
}
}
OptionsPageUIHandler::Observe(type, source, details);
}
void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) {
// Reset the current lists.
password_list_.reset();
password_exception_list_.reset();
languages_ =
web_ui_->GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
populater_.Populate();
exception_populater_.Populate();
}
void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) {
PasswordStore* store = GetPasswordStore();
if (!store)
return;
std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
int index;
if (base::StringToInt(string_value, &index) && index >= 0 &&
static_cast<size_t>(index) < password_list_.size())
store->RemoveLogin(*password_list_[index]);
}
void PasswordManagerHandler::RemovePasswordException(
const ListValue* args) {
PasswordStore* store = GetPasswordStore();
if (!store)
return;
std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
int index;
if (base::StringToInt(string_value, &index) && index >= 0 &&
static_cast<size_t>(index) < password_exception_list_.size())
store->RemoveLogin(*password_exception_list_[index]);
}
void PasswordManagerHandler::RemoveAllSavedPasswords(
const ListValue* args) {
// TODO(jhawkins): This will cause a list refresh for every password in the
// list. Add PasswordStore::RemoveAllLogins().
PasswordStore* store = GetPasswordStore();
if (!store)
return;
for (size_t i = 0; i < password_list_.size(); ++i)
store->RemoveLogin(*password_list_[i]);
}
void PasswordManagerHandler::RemoveAllPasswordExceptions(
const ListValue* args) {
PasswordStore* store = GetPasswordStore();
if (!store)
return;
for (size_t i = 0; i < password_exception_list_.size(); ++i)
store->RemoveLogin(*password_exception_list_[i]);
}
void PasswordManagerHandler::SetPasswordList() {
ListValue entries;
bool show_passwords = *show_passwords_;
string16 empty;
for (size_t i = 0; i < password_list_.size(); ++i) {
ListValue* entry = new ListValue();
entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin,
languages_)));
entry->Append(new StringValue(password_list_[i]->username_value));
entry->Append(new StringValue(
show_passwords ? password_list_[i]->password_value : empty));
entries.Append(entry);
}
web_ui_->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
entries);
}
void PasswordManagerHandler::SetPasswordExceptionList() {
ListValue entries;
for (size_t i = 0; i < password_exception_list_.size(); ++i) {
entries.Append(new StringValue(
net::FormatUrl(password_exception_list_[i]->origin, languages_)));
}
web_ui_->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
entries);
}
PasswordManagerHandler::ListPopulater::ListPopulater(
PasswordManagerHandler* page)
: page_(page),
pending_login_query_(0) {
}
PasswordManagerHandler::ListPopulater::~ListPopulater() {
}
PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater(
PasswordManagerHandler* page) : ListPopulater(page) {
}
void PasswordManagerHandler::PasswordListPopulater::Populate() {
PasswordStore* store = page_->GetPasswordStore();
if (store != NULL) {
if (pending_login_query_)
store->CancelRequest(pending_login_query_);
pending_login_query_ = store->GetAutofillableLogins(this);
} else {
LOG(ERROR) << "No password store! Cannot display passwords.";
}
}
void PasswordManagerHandler::PasswordListPopulater::
OnPasswordStoreRequestDone(
CancelableRequestProvider::Handle handle,
const std::vector<webkit_glue::PasswordForm*>& result) {
DCHECK_EQ(pending_login_query_, handle);
pending_login_query_ = 0;
page_->password_list_.reset();
page_->password_list_.insert(page_->password_list_.end(),
result.begin(), result.end());
page_->SetPasswordList();
}
PasswordManagerHandler::PasswordExceptionListPopulater::
PasswordExceptionListPopulater(PasswordManagerHandler* page)
: ListPopulater(page) {
}
void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() {
PasswordStore* store = page_->GetPasswordStore();
if (store != NULL) {
if (pending_login_query_)
store->CancelRequest(pending_login_query_);
pending_login_query_ = store->GetBlacklistLogins(this);
} else {
LOG(ERROR) << "No password store! Cannot display exceptions.";
}
}
void PasswordManagerHandler::PasswordExceptionListPopulater::
OnPasswordStoreRequestDone(
CancelableRequestProvider::Handle handle,
const std::vector<webkit_glue::PasswordForm*>& result) {
DCHECK_EQ(pending_login_query_, handle);
pending_login_query_ = 0;
page_->password_exception_list_.reset();
page_->password_exception_list_.insert(page_->password_exception_list_.end(),
result.begin(), result.end());
page_->SetPasswordExceptionList();
}
<commit_msg>WebUI: work around a crash triggered by a specific navigation in tabbed options. This does not fix the root cause, which is explained in comment 3 on bug 88986. TEST=pressing the back button after closing the password manager does not crash BUG=88986<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/ui/webui/options/password_manager_handler.h"
#include "base/callback.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/password_form.h"
PasswordManagerHandler::PasswordManagerHandler()
: ALLOW_THIS_IN_INITIALIZER_LIST(populater_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(exception_populater_(this)) {
}
PasswordManagerHandler::~PasswordManagerHandler() {
PasswordStore* store = GetPasswordStore();
if (store)
store->RemoveObserver(this);
}
void PasswordManagerHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
static const OptionsStringResource resources[] = {
{ "savedPasswordsTitle",
IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
{ "passwordExceptionsTitle",
IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
{ "passwordSearchPlaceholder",
IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
{ "passwordShowButton",
IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
{ "passwordHideButton",
IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
{ "passwordsSiteColumn",
IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN },
{ "passwordsUsernameColumn",
IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN },
{ "passwordsRemoveButton",
IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON },
{ "passwordsNoPasswordsDescription",
IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
{ "passwordsNoExceptionsDescription",
IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
{ "passwordsRemoveAllButton",
IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON },
{ "passwordsRemoveAllTitle",
IDS_PASSWORDS_PAGE_VIEW_CAPTION_DELETE_ALL_PASSWORDS },
{ "passwordsRemoveAllWarning",
IDS_PASSWORDS_PAGE_VIEW_TEXT_DELETE_ALL_PASSWORDS },
};
RegisterStrings(localized_strings, resources, arraysize(resources));
RegisterTitle(localized_strings, "passwordsPage",
IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);
localized_strings->SetString("passwordManagerLearnMoreURL",
google_util::AppendGoogleLocaleParam(
GURL(chrome::kPasswordManagerLearnMoreURL)).spec());
}
void PasswordManagerHandler::Initialize() {
// Due to the way that handlers are (re)initialized under certain types of
// navigation, we may already be initialized. (See bugs 88986 and 86448.)
// If this is the case, return immediately. This is a hack.
// TODO(mdm): remove this hack once it is no longer necessary.
if (!show_passwords_.GetPrefName().empty())
return;
show_passwords_.Init(prefs::kPasswordManagerAllowShowPasswords,
web_ui_->GetProfile()->GetPrefs(), this);
// We should not cache web_ui_->GetProfile(). See crosbug.com/6304.
PasswordStore* store = GetPasswordStore();
if (store)
store->AddObserver(this);
}
void PasswordManagerHandler::RegisterMessages() {
DCHECK(web_ui_);
web_ui_->RegisterMessageCallback("updatePasswordLists",
NewCallback(this, &PasswordManagerHandler::UpdatePasswordLists));
web_ui_->RegisterMessageCallback("removeSavedPassword",
NewCallback(this, &PasswordManagerHandler::RemoveSavedPassword));
web_ui_->RegisterMessageCallback("removePasswordException",
NewCallback(this, &PasswordManagerHandler::RemovePasswordException));
web_ui_->RegisterMessageCallback("removeAllSavedPasswords",
NewCallback(this, &PasswordManagerHandler::RemoveAllSavedPasswords));
web_ui_->RegisterMessageCallback("removeAllPasswordExceptions", NewCallback(
this, &PasswordManagerHandler::RemoveAllPasswordExceptions));
}
void PasswordManagerHandler::OnLoginsChanged() {
UpdatePasswordLists(NULL);
}
PasswordStore* PasswordManagerHandler::GetPasswordStore() {
return web_ui_->GetProfile()->GetPasswordStore(Profile::EXPLICIT_ACCESS);
}
void PasswordManagerHandler::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == chrome::NOTIFICATION_PREF_CHANGED) {
std::string* pref_name = Details<std::string>(details).ptr();
if (*pref_name == prefs::kPasswordManagerAllowShowPasswords) {
UpdatePasswordLists(NULL);
}
}
OptionsPageUIHandler::Observe(type, source, details);
}
void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) {
// Reset the current lists.
password_list_.reset();
password_exception_list_.reset();
languages_ =
web_ui_->GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
populater_.Populate();
exception_populater_.Populate();
}
void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) {
PasswordStore* store = GetPasswordStore();
if (!store)
return;
std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
int index;
if (base::StringToInt(string_value, &index) && index >= 0 &&
static_cast<size_t>(index) < password_list_.size())
store->RemoveLogin(*password_list_[index]);
}
void PasswordManagerHandler::RemovePasswordException(
const ListValue* args) {
PasswordStore* store = GetPasswordStore();
if (!store)
return;
std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
int index;
if (base::StringToInt(string_value, &index) && index >= 0 &&
static_cast<size_t>(index) < password_exception_list_.size())
store->RemoveLogin(*password_exception_list_[index]);
}
void PasswordManagerHandler::RemoveAllSavedPasswords(
const ListValue* args) {
// TODO(jhawkins): This will cause a list refresh for every password in the
// list. Add PasswordStore::RemoveAllLogins().
PasswordStore* store = GetPasswordStore();
if (!store)
return;
for (size_t i = 0; i < password_list_.size(); ++i)
store->RemoveLogin(*password_list_[i]);
}
void PasswordManagerHandler::RemoveAllPasswordExceptions(
const ListValue* args) {
PasswordStore* store = GetPasswordStore();
if (!store)
return;
for (size_t i = 0; i < password_exception_list_.size(); ++i)
store->RemoveLogin(*password_exception_list_[i]);
}
void PasswordManagerHandler::SetPasswordList() {
// Due to the way that handlers are (re)initialized under certain types of
// navigation, we may not be initialized yet. (See bugs 88986 and 86448.)
// If this is the case, initialize on demand. This is a hack.
// TODO(mdm): remove this hack once it is no longer necessary.
if (show_passwords_.GetPrefName().empty())
Initialize();
ListValue entries;
bool show_passwords = *show_passwords_;
string16 empty;
for (size_t i = 0; i < password_list_.size(); ++i) {
ListValue* entry = new ListValue();
entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin,
languages_)));
entry->Append(new StringValue(password_list_[i]->username_value));
entry->Append(new StringValue(
show_passwords ? password_list_[i]->password_value : empty));
entries.Append(entry);
}
web_ui_->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
entries);
}
void PasswordManagerHandler::SetPasswordExceptionList() {
ListValue entries;
for (size_t i = 0; i < password_exception_list_.size(); ++i) {
entries.Append(new StringValue(
net::FormatUrl(password_exception_list_[i]->origin, languages_)));
}
web_ui_->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
entries);
}
PasswordManagerHandler::ListPopulater::ListPopulater(
PasswordManagerHandler* page)
: page_(page),
pending_login_query_(0) {
}
PasswordManagerHandler::ListPopulater::~ListPopulater() {
}
PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater(
PasswordManagerHandler* page) : ListPopulater(page) {
}
void PasswordManagerHandler::PasswordListPopulater::Populate() {
PasswordStore* store = page_->GetPasswordStore();
if (store != NULL) {
if (pending_login_query_)
store->CancelRequest(pending_login_query_);
pending_login_query_ = store->GetAutofillableLogins(this);
} else {
LOG(ERROR) << "No password store! Cannot display passwords.";
}
}
void PasswordManagerHandler::PasswordListPopulater::
OnPasswordStoreRequestDone(
CancelableRequestProvider::Handle handle,
const std::vector<webkit_glue::PasswordForm*>& result) {
DCHECK_EQ(pending_login_query_, handle);
pending_login_query_ = 0;
page_->password_list_.reset();
page_->password_list_.insert(page_->password_list_.end(),
result.begin(), result.end());
page_->SetPasswordList();
}
PasswordManagerHandler::PasswordExceptionListPopulater::
PasswordExceptionListPopulater(PasswordManagerHandler* page)
: ListPopulater(page) {
}
void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() {
PasswordStore* store = page_->GetPasswordStore();
if (store != NULL) {
if (pending_login_query_)
store->CancelRequest(pending_login_query_);
pending_login_query_ = store->GetBlacklistLogins(this);
} else {
LOG(ERROR) << "No password store! Cannot display exceptions.";
}
}
void PasswordManagerHandler::PasswordExceptionListPopulater::
OnPasswordStoreRequestDone(
CancelableRequestProvider::Handle handle,
const std::vector<webkit_glue::PasswordForm*>& result) {
DCHECK_EQ(pending_login_query_, handle);
pending_login_query_ = 0;
page_->password_exception_list_.reset();
page_->password_exception_list_.insert(page_->password_exception_list_.end(),
result.begin(), result.end());
page_->SetPasswordExceptionList();
}
<|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/file_path.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/ui_test_utils.h"
#include "gfx/point.h"
#include "gfx/rect.h"
#include "googleurl/src/gurl.h"
namespace {
class MouseLeaveTest : public UITest {
public:
MouseLeaveTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
DISALLOW_COPY_AND_ASSIGN(MouseLeaveTest);
};
TEST_F(MouseLeaveTest, TestOnMouseOut) {
GURL test_url = ui_test_utils::GetTestUrl(
FilePath(FilePath::kCurrentDirectory),
FilePath(FILE_PATH_LITERAL("mouseleave.html")));
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
gfx::Rect tab_view_bounds;
ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
true));
gfx::Point in_content_point(
tab_view_bounds.x() + tab_view_bounds.width() / 2,
tab_view_bounds.y() + 10);
gfx::Point above_content_point(
tab_view_bounds.x() + tab_view_bounds.width() / 2,
tab_view_bounds.y() - 2);
// Start by moving the point just above the content.
ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));
// Navigate to the test html page.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_url));
const int timeout_ms = 5 * action_max_timeout_ms();
// Wait for the onload() handler to complete so we can do the
// next part of the test.
ASSERT_TRUE(WaitUntilCookieValue(
tab.get(), test_url, "__state", timeout_ms, "initial"));
// Move the cursor to the top-center of the content, which will trigger
// a javascript onMouseOver event.
ASSERT_TRUE(window->SimulateOSMouseMove(in_content_point));
// Wait on the correct intermediate value of the cookie.
ASSERT_TRUE(WaitUntilCookieValue(
tab.get(), test_url, "__state", timeout_ms, "initial,entered"));
// Move the cursor above the content again, which should trigger
// a javascript onMouseOut event.
ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));
// Wait on the correct final value of the cookie.
ASSERT_TRUE(WaitUntilCookieValue(
tab.get(), test_url, "__state", timeout_ms, "initial,entered,left"));
}
} // namespace
<commit_msg>Mac: Disable TestOnMouseOut, it requires more automation provider support than there is atm.<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/file_path.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/ui_test_utils.h"
#include "gfx/point.h"
#include "gfx/rect.h"
#include "googleurl/src/gurl.h"
namespace {
class MouseLeaveTest : public UITest {
public:
MouseLeaveTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
DISALLOW_COPY_AND_ASSIGN(MouseLeaveTest);
};
#if defined(OS_MACOSX)
// Missing automation provider support: http://crbug.com/45892
#define MAYBE_TestOnMouseOut FAILS_TestOnMouseOut
#else
#define MAYBE_TestOnMouseOut TestOnMouseOut
#endif
TEST_F(MouseLeaveTest, MAYBE_TestOnMouseOut) {
GURL test_url = ui_test_utils::GetTestUrl(
FilePath(FilePath::kCurrentDirectory),
FilePath(FILE_PATH_LITERAL("mouseleave.html")));
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
gfx::Rect tab_view_bounds;
ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
true));
gfx::Point in_content_point(
tab_view_bounds.x() + tab_view_bounds.width() / 2,
tab_view_bounds.y() + 10);
gfx::Point above_content_point(
tab_view_bounds.x() + tab_view_bounds.width() / 2,
tab_view_bounds.y() - 2);
// Start by moving the point just above the content.
ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));
// Navigate to the test html page.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_url));
const int timeout_ms = 5 * action_max_timeout_ms();
// Wait for the onload() handler to complete so we can do the
// next part of the test.
ASSERT_TRUE(WaitUntilCookieValue(
tab.get(), test_url, "__state", timeout_ms, "initial"));
// Move the cursor to the top-center of the content, which will trigger
// a javascript onMouseOver event.
ASSERT_TRUE(window->SimulateOSMouseMove(in_content_point));
// Wait on the correct intermediate value of the cookie.
ASSERT_TRUE(WaitUntilCookieValue(
tab.get(), test_url, "__state", timeout_ms, "initial,entered"));
// Move the cursor above the content again, which should trigger
// a javascript onMouseOut event.
ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));
// Wait on the correct final value of the cookie.
ASSERT_TRUE(WaitUntilCookieValue(
tab.get(), test_url, "__state", timeout_ms, "initial,entered,left"));
}
} // namespace
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifdef SYMBIAN_BACKEND_USE_SQLITE
#include "cnttransformonlineaccount.h"
#include "cntmodelextuids.h"
QList<CContactItemField *> CntTransformOnlineAccount::transformDetailL(const QContactDetail &detail)
{
if(detail.definitionName() != QContactOnlineAccount::DefinitionName)
User::Leave(KErrArgument);
QList<CContactItemField *> fieldList;
//cast to phonenumber
const QContactOnlineAccount &onlineAccount(static_cast<const QContactOnlineAccount&>(detail));
//get the subType
QStringList subTypes = onlineAccount.subTypes();
//create new field
TPtrC fieldText(reinterpret_cast<const TUint16*>(onlineAccount.accountUri().utf16()));
if(fieldText.Length()) {
CContactItemField* newField = CContactItemField::NewLC(KStorageTypeText);
newField->TextStorage()->SetTextL(fieldText);
//no subtype
if(!subTypes.count())
{
User::LeaveIfError(KErrArgument);
}
// online account
else if (subTypes.contains(QContactOnlineAccount::SubTypeImpp))
{
newField->AddFieldTypeL(KUidContactFieldIMPP);
newField->SetMapping(KUidContactFieldVCardMapUnknown);
}
//internet
else if (subTypes.contains(QContactOnlineAccount::SubTypeSipVoip))
{
newField->AddFieldTypeL(KUidContactFieldSIPID);
newField->SetMapping(KUidContactFieldVCardMapSIPID);
newField->AddFieldTypeL(KUidContactFieldVCardMapVOIP);
}
//share video
else if (subTypes.contains(QContactOnlineAccount::SubTypeVideoShare))
{
newField->AddFieldTypeL(KUidContactFieldSIPID);
newField->SetMapping(KUidContactFieldVCardMapSIPID);
newField->AddFieldTypeL(KUidContactFieldVCardMapSWIS);
}
//sip
else if (subTypes.contains(QContactOnlineAccount::SubTypeSip))
{
newField->AddFieldTypeL(KUidContactFieldSIPID);
newField->SetMapping(KUidContactFieldVCardMapSIPID);
newField->AddFieldTypeL(KUidContactFieldVCardMapSIPID);
}
else
{
User::LeaveIfError(KErrNotSupported);
}
//contexts
setContextsL(onlineAccount, *newField);
fieldList.append(newField);
CleanupStack::Pop(newField);
// Transform Service Provider Text
TPtrC ServiceProviderText(reinterpret_cast<const TUint16*>(onlineAccount.serviceProvider().utf16()));
if(ServiceProviderText.Length()) {
CContactItemField* serviceProviderField = CContactItemField::NewLC(KStorageTypeText);
serviceProviderField->TextStorage()->SetTextL(ServiceProviderText);
serviceProviderField->AddFieldTypeL(KUidContactFieldServiceProvider);
fieldList.append(serviceProviderField);
CleanupStack::Pop(serviceProviderField);
}
// Transform presence informaiton
TPtrC presenceText(reinterpret_cast<const TUint16*>(onlineAccount.presence().utf16()));
if(presenceText.Length()) {
QString presence = QString::number(encodePresence(onlineAccount.presence()));
CContactItemField* presenceField = CContactItemField::NewLC(KStorageTypeText);
TPtrC presenceEncodedText(reinterpret_cast<const TUint16*>(presence.utf16()));
presenceField->TextStorage()->SetTextL(presenceEncodedText);
presenceField->AddFieldTypeL(KUidContactFieldPresence);
fieldList.append(presenceField);
CleanupStack::Pop(presenceField);
}
// Transform statusMessage
TPtrC statusMsgText(reinterpret_cast<const TUint16*>(onlineAccount.statusMessage().utf16()));
if(statusMsgText.Length()) {
CContactItemField* statusMsgField = CContactItemField::NewLC(KStorageTypeText);
statusMsgField->TextStorage()->SetTextL(statusMsgText);
statusMsgField->AddFieldTypeL(KUidContactFieldStatusMsg);
fieldList.append(statusMsgField);
CleanupStack::Pop(statusMsgField);
}
}
return fieldList;
}
QContactDetail *CntTransformOnlineAccount::transformItemField(const CContactItemField& field, const QContact &contact)
{
Q_UNUSED(contact);
QContactOnlineAccount *onlineAccount = new QContactOnlineAccount();
CContactTextField* storage = field.TextStorage();
QString onlineAccountString = QString::fromUtf16(storage->Text().Ptr(), storage->Text().Length());
// Adding Online Account Detail.
for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
//Account URI
if (field.ContentType().ContainsFieldType(KUidContactFieldIMPP)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeImpp);
}
else if (field.ContentType().ContainsFieldType(KUidContactFieldVCardMapVOIP)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeSipVoip);
}
else if (field.ContentType().ContainsFieldType(KUidContactFieldVCardMapSWIS)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeVideoShare);
}
else if (field.ContentType().ContainsFieldType(KUidContactFieldVCardMapSIPID)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeSip);
}
//Service Provider
else if (field.ContentType().FieldType(i) == KUidContactFieldServiceProvider) {
onlineAccount->setServiceProvider(onlineAccountString);
}
//Presence
else if (field.ContentType().FieldType(i) == KUidContactFieldPresence) {
QString presenceInfo = decodePresence(onlineAccountString.toInt());
onlineAccount->setPresence(presenceInfo);
}
//Status Message
else if (field.ContentType().FieldType(i) == KUidContactFieldStatusMsg) {
onlineAccount->setStatusMessage(onlineAccountString);
}
}
// set context
for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
setContexts(field.ContentType().FieldType(i), *onlineAccount);
}
return onlineAccount;
}
bool CntTransformOnlineAccount::supportsField(TUint32 fieldType) const
{
bool ret = false;
if (fieldType == KUidContactFieldSIPID.iUid ||
fieldType == KUidContactFieldIMPP.iUid ||
fieldType == KUidContactFieldServiceProvider.iUid ||
fieldType == KUidContactFieldPresence.iUid ||
fieldType == KUidContactFieldStatusMsg.iUid )
{
ret = true;
}
return ret;
}
bool CntTransformOnlineAccount::supportsDetail(QString detailName) const
{
bool ret = false;
if (detailName == QContactOnlineAccount::DefinitionName) {
ret = true;
}
return ret;
}
QList<TUid> CntTransformOnlineAccount::supportedSortingFieldTypes(QString detailFieldName) const
{
QList<TUid> uids;
if (detailFieldName == QContactOnlineAccount::FieldAccountUri) {
uids << KUidContactFieldIMPP;
uids << KUidContactFieldSIPID;
}
return uids;
}
/*!
* Checks whether the subtype is supported
*
* \a subType The subtype to be checked
* \return True if this subtype is supported
*/
bool CntTransformOnlineAccount::supportsSubType(const QString& subType) const
{
if(QContactOnlineAccount::FieldSubTypes == subType)
return true;
else
return false;
}
/*!
* Returns the filed id corresponding to a field
*
* \a fieldName The name of the supported field
* \return fieldId for the fieldName, 0 if not supported
*/
quint32 CntTransformOnlineAccount::getIdForField(const QString& fieldName) const
{
if (QContactOnlineAccount::FieldAccountUri == fieldName)
return 0;
else if (QContactOnlineAccount::SubTypeSip == fieldName)
return KUidContactFieldSIPID.iUid;
else if (QContactOnlineAccount::SubTypeImpp == fieldName)
return KUidContactFieldIMPP.iUid;
else if (QContactOnlineAccount::SubTypeSipVoip == fieldName)
return KUidContactFieldVCardMapVOIP.iUid;
else if (QContactOnlineAccount::SubTypeVideoShare == fieldName)
return KUidContactFieldVCardMapSWIS.iUid;
else
return 0;
}
/*!
* Modifies the detail definitions. The default detail definitions are
* queried from QContactManagerEngine::schemaDefinitions and then modified
* with this function in the transform leaf classes.
*
* \a definitions The detail definitions to modify.
* \a contactType The contact type the definitions apply for.
*/
void CntTransformOnlineAccount::detailDefinitions(QMap<QString, QContactDetailDefinition> &definitions, const QString& contactType) const
{
Q_UNUSED(contactType);
if(definitions.contains(QContactOnlineAccount::DefinitionName)) {
QContactDetailDefinition d = definitions.value(QContactOnlineAccount::DefinitionName);
QMap<QString, QContactDetailFieldDefinition> fields = d.fields();
QContactDetailFieldDefinition f;
// Don't support "ContextOther"
f.setDataType(QVariant::StringList);
f.setAllowableValues(QVariantList()
<< QLatin1String(QContactDetail::ContextHome)
<< QLatin1String(QContactDetail::ContextWork));
fields[QContactDetail::FieldContext] = f;
d.setFields(fields);
// Replace original definitions
definitions.insert(d.name(), d);
}
}
/*!
* Encode the presence information.
* \a aPresence
*/
quint32 CntTransformOnlineAccount::encodePresence(QString aPresence)
{
if (QContactOnlineAccount::PresenceAvailable == aPresence)
return CntTransformOnlineAccount::EPresenceAvailable;
else if (QContactOnlineAccount::PresenceHidden == aPresence)
return CntTransformOnlineAccount::EPresenceHidden;
else if (QContactOnlineAccount::PresenceBusy == aPresence)
return CntTransformOnlineAccount::EPresenceBusy;
else if (QContactOnlineAccount::PresenceAway == aPresence)
return CntTransformOnlineAccount::EPresenceAway;
else if (QContactOnlineAccount::PresenceExtendedAway == aPresence)
return CntTransformOnlineAccount::EPresenceExtendedAway;
else if (QContactOnlineAccount::PresenceUnknown == aPresence)
return CntTransformOnlineAccount::EPresenceUnknown;
else
return CntTransformOnlineAccount::EPresenceOffline;
}
/*!
* Decode the presence information.
* \a aPresence
*/
QString CntTransformOnlineAccount::decodePresence(quint32 aPresence)
{
if (CntTransformOnlineAccount::EPresenceAvailable == aPresence)
return QContactOnlineAccount::PresenceAvailable;
else if (CntTransformOnlineAccount::EPresenceHidden == aPresence)
return QContactOnlineAccount::PresenceHidden;
else if (CntTransformOnlineAccount::EPresenceBusy == aPresence)
return QContactOnlineAccount::PresenceBusy;
else if ( CntTransformOnlineAccount::EPresenceAway == aPresence)
return QContactOnlineAccount::PresenceAway;
else if ( CntTransformOnlineAccount::EPresenceExtendedAway == aPresence)
return QContactOnlineAccount::PresenceExtendedAway;
else if ( CntTransformOnlineAccount::EPresenceUnknown == aPresence)
return QContactOnlineAccount::PresenceUnknown;
else
return QContactOnlineAccount::PresenceOffline;
}
#endif // SYMBIAN_BACKEND_USE_SQLITE
// End of file
<commit_msg>remove presence from onlineaccount detail implementation, need to implement the presence seperately.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifdef SYMBIAN_BACKEND_USE_SQLITE
#include "cnttransformonlineaccount.h"
#include "cntmodelextuids.h"
#include "qcontactpresence.h"
QList<CContactItemField *> CntTransformOnlineAccount::transformDetailL(const QContactDetail &detail)
{
if(detail.definitionName() != QContactOnlineAccount::DefinitionName)
User::Leave(KErrArgument);
QList<CContactItemField *> fieldList;
//cast to phonenumber
const QContactOnlineAccount &onlineAccount(static_cast<const QContactOnlineAccount&>(detail));
//get the subType
QStringList subTypes = onlineAccount.subTypes();
//create new field
TPtrC fieldText(reinterpret_cast<const TUint16*>(onlineAccount.accountUri().utf16()));
if(fieldText.Length()) {
CContactItemField* newField = CContactItemField::NewLC(KStorageTypeText);
newField->TextStorage()->SetTextL(fieldText);
//no subtype
if(!subTypes.count())
{
User::LeaveIfError(KErrArgument);
}
// online account
else if (subTypes.contains(QContactOnlineAccount::SubTypeImpp))
{
newField->AddFieldTypeL(KUidContactFieldIMPP);
newField->SetMapping(KUidContactFieldVCardMapUnknown);
}
//internet
else if (subTypes.contains(QContactOnlineAccount::SubTypeSipVoip))
{
newField->AddFieldTypeL(KUidContactFieldSIPID);
newField->SetMapping(KUidContactFieldVCardMapSIPID);
newField->AddFieldTypeL(KUidContactFieldVCardMapVOIP);
}
//share video
else if (subTypes.contains(QContactOnlineAccount::SubTypeVideoShare))
{
newField->AddFieldTypeL(KUidContactFieldSIPID);
newField->SetMapping(KUidContactFieldVCardMapSIPID);
newField->AddFieldTypeL(KUidContactFieldVCardMapSWIS);
}
//sip
else if (subTypes.contains(QContactOnlineAccount::SubTypeSip))
{
newField->AddFieldTypeL(KUidContactFieldSIPID);
newField->SetMapping(KUidContactFieldVCardMapSIPID);
newField->AddFieldTypeL(KUidContactFieldVCardMapSIPID);
}
else
{
User::LeaveIfError(KErrNotSupported);
}
//contexts
setContextsL(onlineAccount, *newField);
fieldList.append(newField);
CleanupStack::Pop(newField);
// Transform Service Provider Text
TPtrC ServiceProviderText(reinterpret_cast<const TUint16*>(onlineAccount.serviceProvider().utf16()));
if(ServiceProviderText.Length()) {
CContactItemField* serviceProviderField = CContactItemField::NewLC(KStorageTypeText);
serviceProviderField->TextStorage()->SetTextL(ServiceProviderText);
serviceProviderField->AddFieldTypeL(KUidContactFieldServiceProvider);
fieldList.append(serviceProviderField);
CleanupStack::Pop(serviceProviderField);
}
//FIXME:no presence in onlineaccount anymore..
// // Transform presence informaiton
// TPtrC presenceText(reinterpret_cast<const TUint16*>(onlineAccount.presence().utf16()));
// if(presenceText.Length()) {
// QString presence = QString::number(encodePresence(onlineAccount.presence()));
// CContactItemField* presenceField = CContactItemField::NewLC(KStorageTypeText);
// TPtrC presenceEncodedText(reinterpret_cast<const TUint16*>(presence.utf16()));
// presenceField->TextStorage()->SetTextL(presenceEncodedText);
// presenceField->AddFieldTypeL(KUidContactFieldPresence);
// fieldList.append(presenceField);
// CleanupStack::Pop(presenceField);
// }
// // Transform statusMessage
// TPtrC statusMsgText(reinterpret_cast<const TUint16*>(onlineAccount.statusMessage().utf16()));
// if(statusMsgText.Length()) {
// CContactItemField* statusMsgField = CContactItemField::NewLC(KStorageTypeText);
// statusMsgField->TextStorage()->SetTextL(statusMsgText);
// statusMsgField->AddFieldTypeL(KUidContactFieldStatusMsg);
// fieldList.append(statusMsgField);
// CleanupStack::Pop(statusMsgField);
// }
}
return fieldList;
}
QContactDetail *CntTransformOnlineAccount::transformItemField(const CContactItemField& field, const QContact &contact)
{
Q_UNUSED(contact);
QContactOnlineAccount *onlineAccount = new QContactOnlineAccount();
CContactTextField* storage = field.TextStorage();
QString onlineAccountString = QString::fromUtf16(storage->Text().Ptr(), storage->Text().Length());
// Adding Online Account Detail.
for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
//Account URI
if (field.ContentType().ContainsFieldType(KUidContactFieldIMPP)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeImpp);
}
else if (field.ContentType().ContainsFieldType(KUidContactFieldVCardMapVOIP)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeSipVoip);
}
else if (field.ContentType().ContainsFieldType(KUidContactFieldVCardMapSWIS)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeVideoShare);
}
else if (field.ContentType().ContainsFieldType(KUidContactFieldVCardMapSIPID)) {
onlineAccount->setAccountUri(onlineAccountString);
onlineAccount->setSubTypes(QContactOnlineAccount::SubTypeSip);
}
//Service Provider
else if (field.ContentType().FieldType(i) == KUidContactFieldServiceProvider) {
onlineAccount->setServiceProvider(onlineAccountString);
}
//Presence
else if (field.ContentType().FieldType(i) == KUidContactFieldPresence) {
QString presenceInfo = decodePresence(onlineAccountString.toInt());
// onlineAccount->setPresence(presenceInfo);
}
//Status Message
else if (field.ContentType().FieldType(i) == KUidContactFieldStatusMsg) {
// onlineAccount->setStatusMessage(onlineAccountString);
}
}
// set context
for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
setContexts(field.ContentType().FieldType(i), *onlineAccount);
}
return onlineAccount;
}
bool CntTransformOnlineAccount::supportsField(TUint32 fieldType) const
{
bool ret = false;
if (fieldType == KUidContactFieldSIPID.iUid ||
fieldType == KUidContactFieldIMPP.iUid ||
fieldType == KUidContactFieldServiceProvider.iUid ||
fieldType == KUidContactFieldPresence.iUid ||
fieldType == KUidContactFieldStatusMsg.iUid )
{
ret = true;
}
return ret;
}
bool CntTransformOnlineAccount::supportsDetail(QString detailName) const
{
bool ret = false;
if (detailName == QContactOnlineAccount::DefinitionName) {
ret = true;
}
return ret;
}
QList<TUid> CntTransformOnlineAccount::supportedSortingFieldTypes(QString detailFieldName) const
{
QList<TUid> uids;
if (detailFieldName == QContactOnlineAccount::FieldAccountUri) {
uids << KUidContactFieldIMPP;
uids << KUidContactFieldSIPID;
}
return uids;
}
/*!
* Checks whether the subtype is supported
*
* \a subType The subtype to be checked
* \return True if this subtype is supported
*/
bool CntTransformOnlineAccount::supportsSubType(const QString& subType) const
{
if(QContactOnlineAccount::FieldSubTypes == subType)
return true;
else
return false;
}
/*!
* Returns the filed id corresponding to a field
*
* \a fieldName The name of the supported field
* \return fieldId for the fieldName, 0 if not supported
*/
quint32 CntTransformOnlineAccount::getIdForField(const QString& fieldName) const
{
if (QContactOnlineAccount::FieldAccountUri == fieldName)
return 0;
else if (QContactOnlineAccount::SubTypeSip == fieldName)
return KUidContactFieldSIPID.iUid;
else if (QContactOnlineAccount::SubTypeImpp == fieldName)
return KUidContactFieldIMPP.iUid;
else if (QContactOnlineAccount::SubTypeSipVoip == fieldName)
return KUidContactFieldVCardMapVOIP.iUid;
else if (QContactOnlineAccount::SubTypeVideoShare == fieldName)
return KUidContactFieldVCardMapSWIS.iUid;
else
return 0;
}
/*!
* Modifies the detail definitions. The default detail definitions are
* queried from QContactManagerEngine::schemaDefinitions and then modified
* with this function in the transform leaf classes.
*
* \a definitions The detail definitions to modify.
* \a contactType The contact type the definitions apply for.
*/
void CntTransformOnlineAccount::detailDefinitions(QMap<QString, QContactDetailDefinition> &definitions, const QString& contactType) const
{
Q_UNUSED(contactType);
if(definitions.contains(QContactOnlineAccount::DefinitionName)) {
QContactDetailDefinition d = definitions.value(QContactOnlineAccount::DefinitionName);
QMap<QString, QContactDetailFieldDefinition> fields = d.fields();
QContactDetailFieldDefinition f;
// Don't support "ContextOther"
f.setDataType(QVariant::StringList);
f.setAllowableValues(QVariantList()
<< QLatin1String(QContactDetail::ContextHome)
<< QLatin1String(QContactDetail::ContextWork));
fields[QContactDetail::FieldContext] = f;
d.setFields(fields);
// Replace original definitions
definitions.insert(d.name(), d);
}
}
/*!
* Encode the presence information.
* \a aPresence
*/
quint32 CntTransformOnlineAccount::encodePresence(QString aPresence)
{
//FIXME:presence
// if (QContactPresence::PresenceAvailable == aPresence)
// return CntTransformOnlineAccount::EPresenceAvailable;
// else if (QContactPresence::PresenceHidden == aPresence)
// return CntTransformOnlineAccount::EPresenceHidden;
// else if (QContactPresence::PresenceBusy == aPresence)
// return CntTransformOnlineAccount::EPresenceBusy;
// else if (QContactPresence::PresenceAway == aPresence)
// return CntTransformOnlineAccount::EPresenceAway;
// else if (QContactPresence::PresenceExtendedAway == aPresence)
// return CntTransformOnlineAccount::EPresenceExtendedAway;
// else if (QContactPresence::PresenceUnknown == aPresence)
// return CntTransformOnlineAccount::EPresenceUnknown;
// else
return CntTransformOnlineAccount::EPresenceOffline;
}
/*!
* Decode the presence information.
* \a aPresence
*/
QString CntTransformOnlineAccount::decodePresence(quint32 aPresence)
{
if (CntTransformOnlineAccount::EPresenceAvailable == aPresence)
return QContactPresence::PresenceAvailable;
else if (CntTransformOnlineAccount::EPresenceHidden == aPresence)
return QContactPresence::PresenceHidden;
else if (CntTransformOnlineAccount::EPresenceBusy == aPresence)
return QContactPresence::PresenceBusy;
else if ( CntTransformOnlineAccount::EPresenceAway == aPresence)
return QContactPresence::PresenceAway;
else if ( CntTransformOnlineAccount::EPresenceExtendedAway == aPresence)
return QContactPresence::PresenceExtendedAway;
else if ( CntTransformOnlineAccount::EPresenceUnknown == aPresence)
return QContactPresence::PresenceUnknown;
else
return QContactPresence::PresenceOffline;
}
#endif // SYMBIAN_BACKEND_USE_SQLITE
// End of file
<|endoftext|> |
<commit_before>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
ctx_solver_simplify_tactic.cpp
Abstract:
Context simplifier for propagating solver assignments.
Author:
Nikolaj (nbjorner) 2012-3-6
Notes:
--*/
#include"ctx_solver_simplify_tactic.h"
#include"arith_decl_plugin.h"
#include"smt_params.h"
#include"smt_kernel.h"
#include"ast_pp.h"
#include"mk_simplified_app.h"
class ctx_solver_simplify_tactic : public tactic {
ast_manager& m;
params_ref m_params;
smt_params m_front_p;
smt::kernel m_solver;
arith_util m_arith;
mk_simplified_app m_mk_app;
func_decl_ref m_fn;
obj_map<sort, func_decl*> m_fns;
unsigned m_num_steps;
volatile bool m_cancel;
public:
ctx_solver_simplify_tactic(ast_manager & m, params_ref const & p = params_ref()):
m(m), m_params(p), m_solver(m, m_front_p),
m_arith(m), m_mk_app(m), m_fn(m), m_num_steps(0),
m_cancel(false) {
sort* i_sort = m_arith.mk_int();
m_fn = m.mk_func_decl(symbol(0xbeef101), i_sort, m.mk_bool_sort());
}
virtual tactic * translate(ast_manager & m) {
return alloc(ctx_solver_simplify_tactic, m, m_params);
}
virtual ~ctx_solver_simplify_tactic() {
obj_map<sort, func_decl*>::iterator it = m_fns.begin(), end = m_fns.end();
for (; it != end; ++it) {
m.dec_ref(it->m_value);
}
m_fns.reset();
}
virtual void updt_params(params_ref const & p) {
m_solver.updt_params(p);
}
virtual void collect_param_descrs(param_descrs & r) {
m_solver.collect_param_descrs(r);
}
virtual void collect_statistics(statistics & st) const {
st.update("solver-simplify-steps", m_num_steps);
}
virtual void reset_statistics() { m_num_steps = 0; }
virtual void operator()(goal_ref const & in,
goal_ref_buffer & result,
model_converter_ref & mc,
proof_converter_ref & pc,
expr_dependency_ref & core) {
mc = 0; pc = 0; core = 0;
reduce(*(in.get()));
in->inc_depth();
result.push_back(in.get());
}
virtual void cleanup() {
reset_statistics();
m_solver.reset();
m_cancel = false;
}
protected:
virtual void set_cancel(bool f) {
m_solver.set_cancel(f);
m_cancel = false;
}
void reduce(goal& g) {
SASSERT(g.is_well_sorted());
expr_ref fml(m);
tactic_report report("ctx-solver-simplify", g);
if (g.inconsistent())
return;
ptr_vector<expr> fmls;
g.get_formulas(fmls);
fml = m.mk_and(fmls.size(), fmls.c_ptr());
m_solver.push();
reduce(fml);
m_solver.pop(1);
SASSERT(m_solver.get_scope_level() == 0);
TRACE("ctx_solver_simplify_tactic",
for (unsigned i = 0; i < fmls.size(); ++i) {
tout << mk_pp(fmls[i], m) << "\n";
}
tout << "=>\n";
tout << mk_pp(fml, m) << "\n";);
DEBUG_CODE(
{
m_solver.push();
expr_ref fml1(m);
fml1 = m.mk_and(fmls.size(), fmls.c_ptr());
fml1 = m.mk_iff(fml, fml1);
fml1 = m.mk_not(fml1);
m_solver.assert_expr(fml1);
lbool is_sat = m_solver.check();
TRACE("ctx_solver_simplify_tactic", tout << "is non-equivalence sat?: " << is_sat << "\n";);
if (is_sat != l_false) {
TRACE("ctx_solver_simplify_tactic",
tout << "result is not equivalent to input\n";
tout << mk_pp(fml1, m) << "\n";);
UNREACHABLE();
}
m_solver.pop(1);
});
g.reset();
g.assert_expr(fml, 0, 0);
IF_VERBOSE(TACTIC_VERBOSITY_LVL, verbose_stream() << "(ctx-solver-simplify :num-steps " << m_num_steps << ")\n";);
SASSERT(g.is_well_sorted());
}
void reduce(expr_ref& result){
SASSERT(m.is_bool(result));
ptr_vector<expr> todo;
ptr_vector<expr> names;
svector<bool> is_checked;
svector<unsigned> parent_ids, self_ids;
expr_ref_vector fresh_vars(m), trail(m);
expr_ref res(m), tmp(m);
obj_map<expr,std::pair<unsigned, expr*> > cache;
unsigned id = 1;
expr_ref n2(m), fml(m);
unsigned path_id = 0, self_pos = 0;
app * a;
unsigned sz;
std::pair<unsigned,expr*> path_r;
ptr_vector<expr> found;
expr_ref_vector args(m);
expr_ref n = mk_fresh(id, m.mk_bool_sort());
trail.push_back(n);
fml = result.get();
tmp = m.mk_not(m.mk_iff(fml, n));
m_solver.assert_expr(tmp);
todo.push_back(fml);
names.push_back(n);
is_checked.push_back(false);
parent_ids.push_back(0);
self_ids.push_back(0);
m_solver.push();
while (!todo.empty() && !m_cancel) {
expr_ref res(m);
args.reset();
expr* e = todo.back();
unsigned pos = parent_ids.back();
n = names.back();
bool checked = is_checked.back();
if (cache.contains(e)) {
goto done;
}
if (m.is_bool(e) && !checked && simplify_bool(n, res)) {
TRACE("ctx_solver_simplify_tactic", tout << "simplified: " << mk_pp(e, m) << " |-> " << mk_pp(res, m) << "\n";);
goto done;
}
if (!is_app(e)) {
res = e;
goto done;
}
a = to_app(e);
if (!is_checked.back()) {
self_ids.back() = ++path_id;
is_checked.back() = true;
}
self_pos = self_ids.back();
sz = a->get_num_args();
n2 = 0;
found.reset(); // arguments already simplified.
for (unsigned i = 0; i < sz; ++i) {
expr* arg = a->get_arg(i);
if (cache.find(arg, path_r) && !found.contains(arg)) {
//
// This is a single traversal version of the context
// simplifier. It simplifies only the first occurrence of
// a sub-term with respect to the context.
//
found.push_back(arg);
if (path_r.first == self_pos) {
TRACE("ctx_solver_simplify_tactic", tout << "cached " << mk_pp(arg, m) << " |-> " << mk_pp(path_r.second, m) << "\n";);
args.push_back(path_r.second);
}
else if (m.is_bool(arg)) {
res = local_simplify(a, n, id, i);
TRACE("ctx_solver_simplify_tactic",
tout << "Already cached: " << path_r.first << " " << mk_pp(res, m) << "\n";);
args.push_back(res);
}
else {
args.push_back(arg);
}
}
else if (!n2 && !found.contains(arg)) {
n2 = mk_fresh(id, m.get_sort(arg));
trail.push_back(n2);
todo.push_back(arg);
parent_ids.push_back(self_pos);
self_ids.push_back(0);
names.push_back(n2);
args.push_back(n2);
is_checked.push_back(false);
}
else {
args.push_back(arg);
}
}
m_mk_app(a->get_decl(), args.size(), args.c_ptr(), res);
trail.push_back(res);
// child needs to be visited.
if (n2) {
m_solver.push();
tmp = m.mk_eq(res, n);
m_solver.assert_expr(tmp);
continue;
}
done:
if (res) {
cache.insert(e, std::make_pair(pos, res));
}
TRACE("ctx_solver_simplify_tactic",
tout << mk_pp(e, m) << " checked: " << checked << " cached: " << mk_pp(res?res.get():e, m) << "\n";);
todo.pop_back();
parent_ids.pop_back();
self_ids.pop_back();
names.pop_back();
is_checked.pop_back();
m_solver.pop(1);
}
if (!m_cancel) {
VERIFY(cache.find(fml, path_r));
result = path_r.second;
}
}
bool simplify_bool(expr* n, expr_ref& res) {
expr_ref tmp(m);
m_solver.push();
m_solver.assert_expr(n);
lbool is_sat = m_solver.check();
m_solver.pop(1);
if (is_sat == l_false) {
res = m.mk_true();
return true;
}
m_solver.push();
tmp = m.mk_not(n);
m_solver.assert_expr(tmp);
is_sat = m_solver.check();
m_solver.pop(1);
if (is_sat == l_false) {
res = m.mk_false();
return true;
}
return false;
}
expr_ref mk_fresh(unsigned& id, sort* s) {
func_decl* fn;
if (m.is_bool(s)) {
fn = m_fn;
}
else if (!m_fns.find(s, fn)) {
fn = m.mk_func_decl(symbol(0xbeef101 + id), m_arith.mk_int(), s);
m.inc_ref(fn);
m_fns.insert(s, fn);
}
return expr_ref(m.mk_app(fn, m_arith.mk_numeral(rational(id++), true)), m);
}
expr_ref local_simplify(app* a, expr* n, unsigned& id, unsigned index) {
SASSERT(index < a->get_num_args());
SASSERT(m.is_bool(a->get_arg(index)));
expr_ref n2(m), result(m), tmp(m);
n2 = mk_fresh(id, m.get_sort(a->get_arg(index)));
ptr_buffer<expr> args;
for (unsigned i = 0; i < a->get_num_args(); ++i) {
if (i == index) {
args.push_back(n2);
}
else {
args.push_back(a->get_arg(i));
}
}
m_mk_app(a->get_decl(), args.size(), args.c_ptr(), result);
m_solver.push();
tmp = m.mk_eq(result, n);
m_solver.assert_expr(tmp);
if (!simplify_bool(n2, result)) {
result = a;
}
m_solver.pop(1);
return result;
}
};
tactic * mk_ctx_solver_simplify_tactic(ast_manager & m, params_ref const & p) {
return clean(alloc(ctx_solver_simplify_tactic, m, p));
}
<commit_msg>Fix minor problem<commit_after>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
ctx_solver_simplify_tactic.cpp
Abstract:
Context simplifier for propagating solver assignments.
Author:
Nikolaj (nbjorner) 2012-3-6
Notes:
--*/
#include"ctx_solver_simplify_tactic.h"
#include"arith_decl_plugin.h"
#include"smt_params.h"
#include"smt_kernel.h"
#include"ast_pp.h"
#include"mk_simplified_app.h"
#include"ast_util.h"
class ctx_solver_simplify_tactic : public tactic {
ast_manager& m;
params_ref m_params;
smt_params m_front_p;
smt::kernel m_solver;
arith_util m_arith;
mk_simplified_app m_mk_app;
func_decl_ref m_fn;
obj_map<sort, func_decl*> m_fns;
unsigned m_num_steps;
volatile bool m_cancel;
public:
ctx_solver_simplify_tactic(ast_manager & m, params_ref const & p = params_ref()):
m(m), m_params(p), m_solver(m, m_front_p),
m_arith(m), m_mk_app(m), m_fn(m), m_num_steps(0),
m_cancel(false) {
sort* i_sort = m_arith.mk_int();
m_fn = m.mk_func_decl(symbol(0xbeef101), i_sort, m.mk_bool_sort());
}
virtual tactic * translate(ast_manager & m) {
return alloc(ctx_solver_simplify_tactic, m, m_params);
}
virtual ~ctx_solver_simplify_tactic() {
obj_map<sort, func_decl*>::iterator it = m_fns.begin(), end = m_fns.end();
for (; it != end; ++it) {
m.dec_ref(it->m_value);
}
m_fns.reset();
}
virtual void updt_params(params_ref const & p) {
m_solver.updt_params(p);
}
virtual void collect_param_descrs(param_descrs & r) {
m_solver.collect_param_descrs(r);
}
virtual void collect_statistics(statistics & st) const {
st.update("solver-simplify-steps", m_num_steps);
}
virtual void reset_statistics() { m_num_steps = 0; }
virtual void operator()(goal_ref const & in,
goal_ref_buffer & result,
model_converter_ref & mc,
proof_converter_ref & pc,
expr_dependency_ref & core) {
mc = 0; pc = 0; core = 0;
reduce(*(in.get()));
in->inc_depth();
result.push_back(in.get());
}
virtual void cleanup() {
reset_statistics();
m_solver.reset();
m_cancel = false;
}
protected:
virtual void set_cancel(bool f) {
m_solver.set_cancel(f);
m_cancel = false;
}
void reduce(goal& g) {
SASSERT(g.is_well_sorted());
expr_ref fml(m);
tactic_report report("ctx-solver-simplify", g);
if (g.inconsistent())
return;
ptr_vector<expr> fmls;
g.get_formulas(fmls);
fml = mk_and(m, fmls.size(), fmls.c_ptr());
m_solver.push();
reduce(fml);
m_solver.pop(1);
SASSERT(m_solver.get_scope_level() == 0);
TRACE("ctx_solver_simplify_tactic",
for (unsigned i = 0; i < fmls.size(); ++i) {
tout << mk_pp(fmls[i], m) << "\n";
}
tout << "=>\n";
tout << mk_pp(fml, m) << "\n";);
DEBUG_CODE(
{
m_solver.push();
expr_ref fml1(m);
fml1 = mk_and(m, fmls.size(), fmls.c_ptr());
fml1 = m.mk_iff(fml, fml1);
fml1 = m.mk_not(fml1);
m_solver.assert_expr(fml1);
lbool is_sat = m_solver.check();
TRACE("ctx_solver_simplify_tactic", tout << "is non-equivalence sat?: " << is_sat << "\n";);
if (is_sat != l_false) {
TRACE("ctx_solver_simplify_tactic",
tout << "result is not equivalent to input\n";
tout << mk_pp(fml1, m) << "\n";);
UNREACHABLE();
}
m_solver.pop(1);
});
g.reset();
g.assert_expr(fml, 0, 0);
IF_VERBOSE(TACTIC_VERBOSITY_LVL, verbose_stream() << "(ctx-solver-simplify :num-steps " << m_num_steps << ")\n";);
SASSERT(g.is_well_sorted());
}
void reduce(expr_ref& result){
SASSERT(m.is_bool(result));
ptr_vector<expr> todo;
ptr_vector<expr> names;
svector<bool> is_checked;
svector<unsigned> parent_ids, self_ids;
expr_ref_vector fresh_vars(m), trail(m);
expr_ref res(m), tmp(m);
obj_map<expr,std::pair<unsigned, expr*> > cache;
unsigned id = 1;
expr_ref n2(m), fml(m);
unsigned path_id = 0, self_pos = 0;
app * a;
unsigned sz;
std::pair<unsigned,expr*> path_r;
ptr_vector<expr> found;
expr_ref_vector args(m);
expr_ref n = mk_fresh(id, m.mk_bool_sort());
trail.push_back(n);
fml = result.get();
tmp = m.mk_not(m.mk_iff(fml, n));
m_solver.assert_expr(tmp);
todo.push_back(fml);
names.push_back(n);
is_checked.push_back(false);
parent_ids.push_back(0);
self_ids.push_back(0);
m_solver.push();
while (!todo.empty() && !m_cancel) {
expr_ref res(m);
args.reset();
expr* e = todo.back();
unsigned pos = parent_ids.back();
n = names.back();
bool checked = is_checked.back();
if (cache.contains(e)) {
goto done;
}
if (m.is_bool(e) && !checked && simplify_bool(n, res)) {
TRACE("ctx_solver_simplify_tactic", tout << "simplified: " << mk_pp(e, m) << " |-> " << mk_pp(res, m) << "\n";);
goto done;
}
if (!is_app(e)) {
res = e;
goto done;
}
a = to_app(e);
if (!is_checked.back()) {
self_ids.back() = ++path_id;
is_checked.back() = true;
}
self_pos = self_ids.back();
sz = a->get_num_args();
n2 = 0;
found.reset(); // arguments already simplified.
for (unsigned i = 0; i < sz; ++i) {
expr* arg = a->get_arg(i);
if (cache.find(arg, path_r) && !found.contains(arg)) {
//
// This is a single traversal version of the context
// simplifier. It simplifies only the first occurrence of
// a sub-term with respect to the context.
//
found.push_back(arg);
if (path_r.first == self_pos) {
TRACE("ctx_solver_simplify_tactic", tout << "cached " << mk_pp(arg, m) << " |-> " << mk_pp(path_r.second, m) << "\n";);
args.push_back(path_r.second);
}
else if (m.is_bool(arg)) {
res = local_simplify(a, n, id, i);
TRACE("ctx_solver_simplify_tactic",
tout << "Already cached: " << path_r.first << " " << mk_pp(res, m) << "\n";);
args.push_back(res);
}
else {
args.push_back(arg);
}
}
else if (!n2 && !found.contains(arg)) {
n2 = mk_fresh(id, m.get_sort(arg));
trail.push_back(n2);
todo.push_back(arg);
parent_ids.push_back(self_pos);
self_ids.push_back(0);
names.push_back(n2);
args.push_back(n2);
is_checked.push_back(false);
}
else {
args.push_back(arg);
}
}
m_mk_app(a->get_decl(), args.size(), args.c_ptr(), res);
trail.push_back(res);
// child needs to be visited.
if (n2) {
m_solver.push();
tmp = m.mk_eq(res, n);
m_solver.assert_expr(tmp);
continue;
}
done:
if (res) {
cache.insert(e, std::make_pair(pos, res));
}
TRACE("ctx_solver_simplify_tactic",
tout << mk_pp(e, m) << " checked: " << checked << " cached: " << mk_pp(res?res.get():e, m) << "\n";);
todo.pop_back();
parent_ids.pop_back();
self_ids.pop_back();
names.pop_back();
is_checked.pop_back();
m_solver.pop(1);
}
if (!m_cancel) {
VERIFY(cache.find(fml, path_r));
result = path_r.second;
}
}
bool simplify_bool(expr* n, expr_ref& res) {
expr_ref tmp(m);
m_solver.push();
m_solver.assert_expr(n);
lbool is_sat = m_solver.check();
m_solver.pop(1);
if (is_sat == l_false) {
res = m.mk_true();
return true;
}
m_solver.push();
tmp = m.mk_not(n);
m_solver.assert_expr(tmp);
is_sat = m_solver.check();
m_solver.pop(1);
if (is_sat == l_false) {
res = m.mk_false();
return true;
}
return false;
}
expr_ref mk_fresh(unsigned& id, sort* s) {
func_decl* fn;
if (m.is_bool(s)) {
fn = m_fn;
}
else if (!m_fns.find(s, fn)) {
fn = m.mk_func_decl(symbol(0xbeef101 + id), m_arith.mk_int(), s);
m.inc_ref(fn);
m_fns.insert(s, fn);
}
return expr_ref(m.mk_app(fn, m_arith.mk_numeral(rational(id++), true)), m);
}
expr_ref local_simplify(app* a, expr* n, unsigned& id, unsigned index) {
SASSERT(index < a->get_num_args());
SASSERT(m.is_bool(a->get_arg(index)));
expr_ref n2(m), result(m), tmp(m);
n2 = mk_fresh(id, m.get_sort(a->get_arg(index)));
ptr_buffer<expr> args;
for (unsigned i = 0; i < a->get_num_args(); ++i) {
if (i == index) {
args.push_back(n2);
}
else {
args.push_back(a->get_arg(i));
}
}
m_mk_app(a->get_decl(), args.size(), args.c_ptr(), result);
m_solver.push();
tmp = m.mk_eq(result, n);
m_solver.assert_expr(tmp);
if (!simplify_bool(n2, result)) {
result = a;
}
m_solver.pop(1);
return result;
}
};
tactic * mk_ctx_solver_simplify_tactic(ast_manager & m, params_ref const & p) {
return clean(alloc(ctx_solver_simplify_tactic, m, p));
}
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://lxqt.org/
*
* Copyright: 2015 LXQt team
* Authors:
* Paulo Lieuthier <[email protected]>
*
* This program or 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 Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "statusnotifieritem.h"
#include "statusnotifieritemadaptor.h"
#include <QDBusInterface>
#include <QDBusServiceWatcher>
#include <dbusmenu-qt5/dbusmenuexporter.h>
int StatusNotifierItem::mServiceCounter = 0;
StatusNotifierItem::StatusNotifierItem(QString id, QObject *parent)
: QObject(parent),
mAdaptor(new StatusNotifierItemAdaptor(this)),
mService(QString("org.freedesktop.StatusNotifierItem-%1-%2")
.arg(QCoreApplication::applicationPid())
.arg(++mServiceCounter)),
mId(id),
mTitle("Test"),
mStatus("Active"),
mMenu(nullptr),
mMenuExporter(nullptr),
mSessionBus(QDBusConnection::connectToBus(QDBusConnection::SessionBus, mService))
{
// Separate DBus connection to the session bus is created, because QDbus does not provide
// a way to register different objects for different services with the same paths.
// For status notifiers we need different /StatusNotifierItem for each service.
// register service
mSessionBus.registerService(mService);
mSessionBus.registerObject(QLatin1String("/StatusNotifierItem"), this);
registerToHost();
// monitor the watcher service in case the host restarts
QDBusServiceWatcher *watcher = new QDBusServiceWatcher("org.kde.StatusNotifierWatcher",
mSessionBus,
QDBusServiceWatcher::WatchForOwnerChange,
this);
connect(watcher, &QDBusServiceWatcher::serviceOwnerChanged,
this, &StatusNotifierItem::onServiceOwnerChanged);
}
StatusNotifierItem::~StatusNotifierItem()
{
mSessionBus.unregisterObject(QLatin1String("/StatusNotifierItem"));
mSessionBus.unregisterService(mService);
QDBusConnection::disconnectFromBus(mService);
}
void StatusNotifierItem::registerToHost()
{
QDBusInterface interface("org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
mSessionBus);
interface.asyncCall("RegisterStatusNotifierItem", mService);
}
void StatusNotifierItem::onServiceOwnerChanged(const QString& service, const QString& oldOwner,
const QString& newOwner)
{
if (!newOwner.isEmpty())
registerToHost();
}
void StatusNotifierItem::onMenuDestroyed()
{
mMenu = nullptr;
mMenuExporter = nullptr; //mMenu is a QObject parent of the mMenuExporter
}
void StatusNotifierItem::setTitle(const QString &title)
{
if (mTitle == title)
return;
mTitle = title;
Q_EMIT mAdaptor->NewTitle();
}
void StatusNotifierItem::setStatus(const QString &status)
{
if (mStatus == status)
return;
mStatus = status;
Q_EMIT mAdaptor->NewStatus(mStatus);
}
void StatusNotifierItem::setMenuPath(const QString& path)
{
mMenuPath.setPath(path);
}
void StatusNotifierItem::setIconByName(const QString &name)
{
if (mIconName == name)
return;
mIconName = name;
Q_EMIT mAdaptor->NewIcon();
}
void StatusNotifierItem::setIconByPixmap(const QIcon &icon)
{
if (mIconCacheKey == icon.cacheKey())
return;
mIconCacheKey = icon.cacheKey();
mIcon = iconToPixmapList(icon);
mIconName.clear();
Q_EMIT mAdaptor->NewIcon();
}
void StatusNotifierItem::setOverlayIconByName(const QString &name)
{
if (mOverlayIconName == name)
return;
mOverlayIconName = name;
Q_EMIT mAdaptor->NewOverlayIcon();
}
void StatusNotifierItem::setOverlayIconByPixmap(const QIcon &icon)
{
if (mOverlayIconCacheKey == icon.cacheKey())
return;
mOverlayIconCacheKey = icon.cacheKey();
mOverlayIcon = iconToPixmapList(icon);
mOverlayIconName.clear();
Q_EMIT mAdaptor->NewOverlayIcon();
}
void StatusNotifierItem::setAttentionIconByName(const QString &name)
{
if (mAttentionIconName == name)
return;
mAttentionIconName = name;
Q_EMIT mAdaptor->NewAttentionIcon();
}
void StatusNotifierItem::setAttentionIconByPixmap(const QIcon &icon)
{
if (mAttentionIconCacheKey == icon.cacheKey())
return;
mAttentionIconCacheKey = icon.cacheKey();
mAttentionIcon = iconToPixmapList(icon);
mAttentionIconName.clear();
Q_EMIT mAdaptor->NewAttentionIcon();
}
void StatusNotifierItem::setToolTipTitle(const QString &title)
{
if (mTooltipTitle == title)
return;
mTooltipTitle = title;
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setToolTipSubTitle(const QString &subTitle)
{
if (mTooltipSubtitle == subTitle)
return;
mTooltipSubtitle = subTitle;
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setToolTipIconByName(const QString &name)
{
if (mTooltipIconName == name)
return;
mTooltipIconName = name;
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setToolTipIconByPixmap(const QIcon &icon)
{
if (mTooltipIconCacheKey == icon.cacheKey())
return;
mTooltipIconCacheKey = icon.cacheKey();
mTooltipIcon = iconToPixmapList(icon);
mTooltipIconName.clear();
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setContextMenu(QMenu* menu)
{
if (mMenu == menu)
return;
if (nullptr != mMenu)
{
disconnect(mMenu, &QObject::destroyed, this, &StatusNotifierItem::onMenuDestroyed);
}
mMenu = menu;
setMenuPath("/MenuBar");
//Note: we need to destroy menu exporter before creating new one -> to free the DBus object path for new menu
delete mMenuExporter;
if (nullptr != mMenu)
{
connect(mMenu, &QObject::destroyed, this, &StatusNotifierItem::onMenuDestroyed);
mMenuExporter = new DBusMenuExporter{this->menu().path(), mMenu, mSessionBus};
}
}
void StatusNotifierItem::Activate(int x, int y)
{
if (mStatus == "NeedsAttention")
mStatus = "Active";
Q_EMIT activateRequested(QPoint(x, y));
}
void StatusNotifierItem::SecondaryActivate(int x, int y)
{
if (mStatus == "NeedsAttention")
mStatus = "Active";
Q_EMIT secondaryActivateRequested(QPoint(x, y));
}
void StatusNotifierItem::ContextMenu(int x, int y)
{
if (mMenu)
{
if (mMenu->isVisible())
mMenu->popup(QPoint(x, y));
else
mMenu->hide();
}
}
void StatusNotifierItem::Scroll(int delta, const QString &orientation)
{
Qt::Orientation orient = Qt::Vertical;
if (orientation.toLower() == "horizontal")
orient = Qt::Horizontal;
Q_EMIT scrollRequested(delta, orient);
}
void StatusNotifierItem::showMessage(const QString& title, const QString& msg,
const QString& iconName, int secs)
{
QDBusInterface interface("org.freedesktop.Notifications", "/org/freedesktop/Notifications",
"org.freedesktop.Notifications", mSessionBus);
interface.call("Notify", mTitle, (uint) 0, iconName, title,
msg, QStringList(), QVariantMap(), secs);
}
IconPixmapList StatusNotifierItem::iconToPixmapList(const QIcon& icon)
{
IconPixmapList pixmapList;
// long live KDE!
const QList<QSize> sizes = icon.availableSizes();
for (const QSize &size : sizes)
{
QImage image = icon.pixmap(size).toImage();
IconPixmap pix;
pix.height = image.height();
pix.width = image.width();
if (image.format() != QImage::Format_ARGB32)
image = image.convertToFormat(QImage::Format_ARGB32);
pix.bytes = QByteArray((char *) image.bits(), image.byteCount());
// swap to network byte order if we are little endian
if (QSysInfo::ByteOrder == QSysInfo::LittleEndian)
{
quint32 *uintBuf = (quint32 *) pix.bytes.data();
for (uint i = 0; i < pix.bytes.size() / sizeof(quint32); ++i)
{
*uintBuf = qToBigEndian(*uintBuf);
++uintBuf;
}
}
pixmapList.append(pix);
}
return pixmapList;
}
<commit_msg>Flag unused vars in onServiceOwnerChanged<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://lxqt.org/
*
* Copyright: 2015 LXQt team
* Authors:
* Paulo Lieuthier <[email protected]>
*
* This program or 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 Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "statusnotifieritem.h"
#include "statusnotifieritemadaptor.h"
#include <QDBusInterface>
#include <QDBusServiceWatcher>
#include <dbusmenu-qt5/dbusmenuexporter.h>
int StatusNotifierItem::mServiceCounter = 0;
StatusNotifierItem::StatusNotifierItem(QString id, QObject *parent)
: QObject(parent),
mAdaptor(new StatusNotifierItemAdaptor(this)),
mService(QString("org.freedesktop.StatusNotifierItem-%1-%2")
.arg(QCoreApplication::applicationPid())
.arg(++mServiceCounter)),
mId(id),
mTitle("Test"),
mStatus("Active"),
mMenu(nullptr),
mMenuExporter(nullptr),
mSessionBus(QDBusConnection::connectToBus(QDBusConnection::SessionBus, mService))
{
// Separate DBus connection to the session bus is created, because QDbus does not provide
// a way to register different objects for different services with the same paths.
// For status notifiers we need different /StatusNotifierItem for each service.
// register service
mSessionBus.registerService(mService);
mSessionBus.registerObject(QLatin1String("/StatusNotifierItem"), this);
registerToHost();
// monitor the watcher service in case the host restarts
QDBusServiceWatcher *watcher = new QDBusServiceWatcher("org.kde.StatusNotifierWatcher",
mSessionBus,
QDBusServiceWatcher::WatchForOwnerChange,
this);
connect(watcher, &QDBusServiceWatcher::serviceOwnerChanged,
this, &StatusNotifierItem::onServiceOwnerChanged);
}
StatusNotifierItem::~StatusNotifierItem()
{
mSessionBus.unregisterObject(QLatin1String("/StatusNotifierItem"));
mSessionBus.unregisterService(mService);
QDBusConnection::disconnectFromBus(mService);
}
void StatusNotifierItem::registerToHost()
{
QDBusInterface interface("org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
mSessionBus);
interface.asyncCall("RegisterStatusNotifierItem", mService);
}
void StatusNotifierItem::onServiceOwnerChanged(const QString& service, const QString& oldOwner,
const QString& newOwner)
{
Q_UNUSED(service);
Q_UNUSED(oldOwner);
if (!newOwner.isEmpty())
registerToHost();
}
void StatusNotifierItem::onMenuDestroyed()
{
mMenu = nullptr;
mMenuExporter = nullptr; //mMenu is a QObject parent of the mMenuExporter
}
void StatusNotifierItem::setTitle(const QString &title)
{
if (mTitle == title)
return;
mTitle = title;
Q_EMIT mAdaptor->NewTitle();
}
void StatusNotifierItem::setStatus(const QString &status)
{
if (mStatus == status)
return;
mStatus = status;
Q_EMIT mAdaptor->NewStatus(mStatus);
}
void StatusNotifierItem::setMenuPath(const QString& path)
{
mMenuPath.setPath(path);
}
void StatusNotifierItem::setIconByName(const QString &name)
{
if (mIconName == name)
return;
mIconName = name;
Q_EMIT mAdaptor->NewIcon();
}
void StatusNotifierItem::setIconByPixmap(const QIcon &icon)
{
if (mIconCacheKey == icon.cacheKey())
return;
mIconCacheKey = icon.cacheKey();
mIcon = iconToPixmapList(icon);
mIconName.clear();
Q_EMIT mAdaptor->NewIcon();
}
void StatusNotifierItem::setOverlayIconByName(const QString &name)
{
if (mOverlayIconName == name)
return;
mOverlayIconName = name;
Q_EMIT mAdaptor->NewOverlayIcon();
}
void StatusNotifierItem::setOverlayIconByPixmap(const QIcon &icon)
{
if (mOverlayIconCacheKey == icon.cacheKey())
return;
mOverlayIconCacheKey = icon.cacheKey();
mOverlayIcon = iconToPixmapList(icon);
mOverlayIconName.clear();
Q_EMIT mAdaptor->NewOverlayIcon();
}
void StatusNotifierItem::setAttentionIconByName(const QString &name)
{
if (mAttentionIconName == name)
return;
mAttentionIconName = name;
Q_EMIT mAdaptor->NewAttentionIcon();
}
void StatusNotifierItem::setAttentionIconByPixmap(const QIcon &icon)
{
if (mAttentionIconCacheKey == icon.cacheKey())
return;
mAttentionIconCacheKey = icon.cacheKey();
mAttentionIcon = iconToPixmapList(icon);
mAttentionIconName.clear();
Q_EMIT mAdaptor->NewAttentionIcon();
}
void StatusNotifierItem::setToolTipTitle(const QString &title)
{
if (mTooltipTitle == title)
return;
mTooltipTitle = title;
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setToolTipSubTitle(const QString &subTitle)
{
if (mTooltipSubtitle == subTitle)
return;
mTooltipSubtitle = subTitle;
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setToolTipIconByName(const QString &name)
{
if (mTooltipIconName == name)
return;
mTooltipIconName = name;
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setToolTipIconByPixmap(const QIcon &icon)
{
if (mTooltipIconCacheKey == icon.cacheKey())
return;
mTooltipIconCacheKey = icon.cacheKey();
mTooltipIcon = iconToPixmapList(icon);
mTooltipIconName.clear();
Q_EMIT mAdaptor->NewToolTip();
}
void StatusNotifierItem::setContextMenu(QMenu* menu)
{
if (mMenu == menu)
return;
if (nullptr != mMenu)
{
disconnect(mMenu, &QObject::destroyed, this, &StatusNotifierItem::onMenuDestroyed);
}
mMenu = menu;
setMenuPath("/MenuBar");
//Note: we need to destroy menu exporter before creating new one -> to free the DBus object path for new menu
delete mMenuExporter;
if (nullptr != mMenu)
{
connect(mMenu, &QObject::destroyed, this, &StatusNotifierItem::onMenuDestroyed);
mMenuExporter = new DBusMenuExporter{this->menu().path(), mMenu, mSessionBus};
}
}
void StatusNotifierItem::Activate(int x, int y)
{
if (mStatus == "NeedsAttention")
mStatus = "Active";
Q_EMIT activateRequested(QPoint(x, y));
}
void StatusNotifierItem::SecondaryActivate(int x, int y)
{
if (mStatus == "NeedsAttention")
mStatus = "Active";
Q_EMIT secondaryActivateRequested(QPoint(x, y));
}
void StatusNotifierItem::ContextMenu(int x, int y)
{
if (mMenu)
{
if (mMenu->isVisible())
mMenu->popup(QPoint(x, y));
else
mMenu->hide();
}
}
void StatusNotifierItem::Scroll(int delta, const QString &orientation)
{
Qt::Orientation orient = Qt::Vertical;
if (orientation.toLower() == "horizontal")
orient = Qt::Horizontal;
Q_EMIT scrollRequested(delta, orient);
}
void StatusNotifierItem::showMessage(const QString& title, const QString& msg,
const QString& iconName, int secs)
{
QDBusInterface interface("org.freedesktop.Notifications", "/org/freedesktop/Notifications",
"org.freedesktop.Notifications", mSessionBus);
interface.call("Notify", mTitle, (uint) 0, iconName, title,
msg, QStringList(), QVariantMap(), secs);
}
IconPixmapList StatusNotifierItem::iconToPixmapList(const QIcon& icon)
{
IconPixmapList pixmapList;
// long live KDE!
const QList<QSize> sizes = icon.availableSizes();
for (const QSize &size : sizes)
{
QImage image = icon.pixmap(size).toImage();
IconPixmap pix;
pix.height = image.height();
pix.width = image.width();
if (image.format() != QImage::Format_ARGB32)
image = image.convertToFormat(QImage::Format_ARGB32);
pix.bytes = QByteArray((char *) image.bits(), image.byteCount());
// swap to network byte order if we are little endian
if (QSysInfo::ByteOrder == QSysInfo::LittleEndian)
{
quint32 *uintBuf = (quint32 *) pix.bytes.data();
for (uint i = 0; i < pix.bytes.size() / sizeof(quint32); ++i)
{
*uintBuf = qToBigEndian(*uintBuf);
++uintBuf;
}
}
pixmapList.append(pix);
}
return pixmapList;
}
<|endoftext|> |
<commit_before>#include <bitcoin/storage/postgresql_storage.hpp>
#include <bitcoin/block.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/util/assert.hpp>
#include <bitcoin/util/logger.hpp>
#include "postgresql_blockchain.hpp"
namespace libbitcoin {
hash_digest hash_from_bytea(std::string byte_stream);
data_chunk bytes_from_bytea(std::string byte_stream);
uint32_t extract_bits_head(uint32_t bits);
uint32_t extract_bits_body(uint32_t bits);
postgresql_storage::postgresql_storage(kernel_ptr kernel,
std::string database, std::string user, std::string password)
: sql_(std::string("postgresql:dbname=") + database +
";user=" + user + ";password=" + password)
{
blockchain_.reset(new pq_blockchain(sql_, service(), kernel));
// Organise/validate old blocks in case of unclean shutdown
strand()->post(std::bind(&pq_blockchain::start, blockchain_));
}
size_t postgresql_storage::insert(const message::transaction_input& input,
size_t transaction_id, size_t index_in_parent)
{
std::string hash = pretty_hex(input.previous_output.hash),
pretty_script = pretty_hex(save_script(input.input_script));
static cppdb::statement statement = sql_.prepare(
"INSERT INTO inputs (input_id, transaction_id, index_in_parent, \
script, previous_output_hash, previous_output_index, sequence) \
VALUES (DEFAULT, ?, ?, decode(?, 'hex'), decode(?, 'hex'), ?, ?) \
RETURNING input_id"
);
statement.reset();
statement.bind(transaction_id);
statement.bind(index_in_parent);
statement.bind(pretty_script);
statement.bind(hash);
statement.bind(input.previous_output.index);
statement.bind(input.sequence);
return statement.row().get<size_t>(0);
}
size_t postgresql_storage::insert(const message::transaction_output& output,
size_t transaction_id, size_t index_in_parent)
{
std::string pretty_script = pretty_hex(save_script(output.output_script));
static cppdb::statement statement = sql_.prepare(
"INSERT INTO outputs ( \
output_id, transaction_id, index_in_parent, script, value) \
VALUES (DEFAULT, ?, ?, decode(?, 'hex'), internal_to_sql(?)) \
RETURNING output_id"
);
statement.reset();
statement.bind(transaction_id);
statement.bind(index_in_parent);
statement.bind(pretty_script);
statement.bind(output.value);
return statement.row().get<size_t>(0);
}
size_t postgresql_storage::insert(const message::transaction& transaction,
std::vector<size_t>& input_ids, std::vector<size_t>& output_ids)
{
hash_digest transaction_hash = hash_transaction(transaction);
std::string transaction_hash_repr = pretty_hex(transaction_hash);
// We use special function to insert txs.
// Some blocks contain duplicates. See SQL for more details.
static cppdb::statement statement = sql_.prepare(
"SELECT insert_transaction(decode(?, 'hex'), ?, ?, ?)"
);
statement.reset();
statement.bind(transaction_hash_repr);
statement.bind(transaction.version);
statement.bind(transaction.locktime);
statement.bind(is_coinbase(transaction));
cppdb::result result = statement.row();
size_t transaction_id = result.get<size_t>(0);
if (transaction_id == 0)
{
cppdb::result old_transaction_id = sql_ <<
"SELECT transaction_id \
FROM transactions \
WHERE transaction_hash=decode(?, 'hex')"
<< transaction_hash_repr
<< cppdb::row;
return old_transaction_id.get<size_t>(0);
}
for (size_t i = 0; i < transaction.inputs.size(); ++i)
{
size_t input_id = insert(transaction.inputs[i], transaction_id, i);
input_ids.push_back(input_id);
}
for (size_t i = 0; i < transaction.outputs.size(); ++i)
{
size_t output_id = insert(transaction.outputs[i], transaction_id, i);
output_ids.push_back(output_id);
}
return transaction_id;
}
void postgresql_storage::store(const message::block& block,
store_handler handle_store)
{
strand()->post(std::bind(
&postgresql_storage::do_store_block, shared_from_this(),
block, handle_store));
}
void postgresql_storage::do_store_block(const message::block& block,
store_handler handle_store)
{
hash_digest block_hash = hash_block_header(block);
std::string block_hash_repr = pretty_hex(block_hash),
prev_block_repr = pretty_hex(block.prev_block),
merkle_repr = pretty_hex(block.merkle_root);
cppdb::transaction guard(sql_);
cppdb::result result = sql_ <<
"SELECT block_id FROM blocks WHERE block_hash=decode(?, 'hex')"
<< block_hash_repr << cppdb::row;
if (!result.empty())
{
log_warning() << "Block '" << block_hash_repr << "' already exists";
blockchain_->organizer()->refresh_block(result.get<size_t>(0));
blockchain_->raise_barrier();
handle_store(error::object_already_exists);
return;
}
static cppdb::statement statement = sql_.prepare(
"INSERT INTO blocks( \
block_id, \
block_hash, \
space, \
depth, \
span_left, \
span_right, \
version, \
prev_block_hash, \
merkle, \
when_created, \
bits_head, \
bits_body, \
nonce \
) VALUES ( \
DEFAULT, \
decode(?, 'hex'), \
nextval('blocks_space_sequence'), \
0, \
0, \
0, \
?, \
decode(?, 'hex'), \
decode(?, 'hex'), \
TO_TIMESTAMP(?), \
?, \
?, \
? \
) \
RETURNING block_id"
);
statement.reset();
statement.bind(block_hash_repr);
statement.bind(block.version);
statement.bind(prev_block_repr);
statement.bind(merkle_repr);
statement.bind(block.timestamp);
uint32_t bits_head = extract_bits_head(block.bits),
bits_body = extract_bits_body(block.bits);
statement.bind(bits_head);
statement.bind(bits_body);
statement.bind(block.nonce);
result = statement.row();
pq_block_info block_info;
block_info.block_id = result.get<size_t>(0);
for (size_t i = 0; i < block.transactions.size(); ++i)
{
message::transaction transaction = block.transactions[i];
pq_transaction_info tx_info;
tx_info.transaction_id =
insert(transaction, tx_info.input_ids, tx_info.output_ids);
// Create block <-> txn mapping
static cppdb::statement link_txs = sql_.prepare(
"INSERT INTO transactions_parents ( \
transaction_id, block_id, index_in_block) \
VALUES (?, ?, ?)"
);
link_txs.reset();
link_txs.bind(tx_info.transaction_id);
link_txs.bind(block_info.block_id);
link_txs.bind(i);
link_txs.exec();
block_info.transactions.push_back(tx_info);
}
blockchain_->buffer_block(std::make_pair(block_info, block));
blockchain_->organizer()->refresh_block(block_info.block_id);
blockchain_->raise_barrier();
guard.commit();
handle_store(std::error_code());
}
void postgresql_storage::fetch_block_locator(
fetch_handler_block_locator handle_fetch)
{
strand()->post(std::bind(
&postgresql_storage::do_fetch_block_locator, shared_from_this(),
handle_fetch));
}
void postgresql_storage::do_fetch_block_locator(
fetch_handler_block_locator handle_fetch)
{
cppdb::result number_blocks_result = sql_ <<
"SELECT depth \
FROM chains \
ORDER BY work DESC \
LIMIT 1"
<< cppdb::row;
if (number_blocks_result.empty())
{
handle_fetch(error::object_doesnt_exist, message::block_locator());
return;
}
// Start at max_depth
int top_depth = number_blocks_result.get<size_t>(0);
std::vector<size_t> indices;
// Push last 10 indices first
size_t step = 1, start = 0;
for (int i = top_depth; i > 0; i -= step, ++start)
{
if (start >= 10)
step *= 2;
indices.push_back(i);
}
indices.push_back(0);
// Now actually fetch the hashes for these blocks
std::stringstream hack_sql;
hack_sql <<
"SELECT encode(block_hash, 'hex') \
FROM main_chain \
WHERE depth IN (";
for (size_t i = 0; i < indices.size(); ++i)
{
if (i != 0)
hack_sql << ", ";
hack_sql << indices[i];
}
hack_sql << ") ORDER BY depth DESC";
// ----------------------------------------------
cppdb::result block_hashes_result = sql_ << hack_sql.str();
message::block_locator locator;
while (block_hashes_result.next())
{
std::string block_hash_repr = block_hashes_result.get<std::string>(0);
locator.push_back(hash_from_bytea(block_hash_repr));
}
BITCOIN_ASSERT(locator.size() == indices.size());
handle_fetch(std::error_code(), locator);
}
void postgresql_storage::fetch_balance(const short_hash& pubkey_hash,
fetch_handler_balance handle_fetch)
{
strand()->post(std::bind(
&postgresql_storage::do_fetch_balance, shared_from_this(),
pubkey_hash, handle_fetch));
}
void postgresql_storage::do_fetch_balance(const short_hash& pubkey_hash,
fetch_handler_balance handle_fetch)
{
std::string total_script = "76 a9 14 " + pretty_hex(pubkey_hash) + " 88 ac";
static cppdb::statement statement = sql_.prepare(
"WITH outs AS ( \
SELECT \
transaction_hash, \
outputs.index_in_parent, \
outputs.value \
FROM \
outputs, \
transactions \
WHERE \
script=decode(?, 'hex') \
AND outputs.transaction_id=transactions.transaction_id \
) \
SELECT \
sql_to_internal(SUM(outs.value)) \
FROM outs \
LEFT JOIN inputs \
ON \
inputs.previous_output_hash=transaction_hash \
AND inputs.previous_output_index=outs.index_in_parent \
WHERE inputs IS NULL"
);
statement.reset();
statement.bind(total_script);
cppdb::result result = statement.row();
uint64_t value = 0;
if (!result.is_null(0))
value = result.get<uint64_t>(0);
handle_fetch(std::error_code(), value);
}
} // libbitcoin
<commit_msg>if dupli tx stop block caching<commit_after>#include <bitcoin/storage/postgresql_storage.hpp>
#include <bitcoin/block.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/util/assert.hpp>
#include <bitcoin/util/logger.hpp>
#include "postgresql_blockchain.hpp"
namespace libbitcoin {
hash_digest hash_from_bytea(std::string byte_stream);
data_chunk bytes_from_bytea(std::string byte_stream);
uint32_t extract_bits_head(uint32_t bits);
uint32_t extract_bits_body(uint32_t bits);
postgresql_storage::postgresql_storage(kernel_ptr kernel,
std::string database, std::string user, std::string password)
: sql_(std::string("postgresql:dbname=") + database +
";user=" + user + ";password=" + password)
{
blockchain_.reset(new pq_blockchain(sql_, service(), kernel));
// Organise/validate old blocks in case of unclean shutdown
strand()->post(std::bind(&pq_blockchain::start, blockchain_));
}
size_t postgresql_storage::insert(const message::transaction_input& input,
size_t transaction_id, size_t index_in_parent)
{
std::string hash = pretty_hex(input.previous_output.hash),
pretty_script = pretty_hex(save_script(input.input_script));
static cppdb::statement statement = sql_.prepare(
"INSERT INTO inputs (input_id, transaction_id, index_in_parent, \
script, previous_output_hash, previous_output_index, sequence) \
VALUES (DEFAULT, ?, ?, decode(?, 'hex'), decode(?, 'hex'), ?, ?) \
RETURNING input_id"
);
statement.reset();
statement.bind(transaction_id);
statement.bind(index_in_parent);
statement.bind(pretty_script);
statement.bind(hash);
statement.bind(input.previous_output.index);
statement.bind(input.sequence);
return statement.row().get<size_t>(0);
}
size_t postgresql_storage::insert(const message::transaction_output& output,
size_t transaction_id, size_t index_in_parent)
{
std::string pretty_script = pretty_hex(save_script(output.output_script));
static cppdb::statement statement = sql_.prepare(
"INSERT INTO outputs ( \
output_id, transaction_id, index_in_parent, script, value) \
VALUES (DEFAULT, ?, ?, decode(?, 'hex'), internal_to_sql(?)) \
RETURNING output_id"
);
statement.reset();
statement.bind(transaction_id);
statement.bind(index_in_parent);
statement.bind(pretty_script);
statement.bind(output.value);
return statement.row().get<size_t>(0);
}
size_t postgresql_storage::insert(const message::transaction& transaction,
std::vector<size_t>& input_ids, std::vector<size_t>& output_ids)
{
hash_digest transaction_hash = hash_transaction(transaction);
std::string transaction_hash_repr = pretty_hex(transaction_hash);
// We use special function to insert txs.
// Some blocks contain duplicates. See SQL for more details.
static cppdb::statement statement = sql_.prepare(
"SELECT insert_transaction(decode(?, 'hex'), ?, ?, ?)"
);
statement.reset();
statement.bind(transaction_hash_repr);
statement.bind(transaction.version);
statement.bind(transaction.locktime);
statement.bind(is_coinbase(transaction));
cppdb::result result = statement.row();
size_t transaction_id = result.get<size_t>(0);
if (transaction_id == 0)
{
cppdb::result old_transaction_id = sql_ <<
"SELECT transaction_id \
FROM transactions \
WHERE transaction_hash=decode(?, 'hex')"
<< transaction_hash_repr
<< cppdb::row;
return old_transaction_id.get<size_t>(0);
}
for (size_t i = 0; i < transaction.inputs.size(); ++i)
{
size_t input_id = insert(transaction.inputs[i], transaction_id, i);
input_ids.push_back(input_id);
}
for (size_t i = 0; i < transaction.outputs.size(); ++i)
{
size_t output_id = insert(transaction.outputs[i], transaction_id, i);
output_ids.push_back(output_id);
}
return transaction_id;
}
void postgresql_storage::store(const message::block& block,
store_handler handle_store)
{
strand()->post(std::bind(
&postgresql_storage::do_store_block, shared_from_this(),
block, handle_store));
}
void postgresql_storage::do_store_block(const message::block& block,
store_handler handle_store)
{
hash_digest block_hash = hash_block_header(block);
std::string block_hash_repr = pretty_hex(block_hash),
prev_block_repr = pretty_hex(block.prev_block),
merkle_repr = pretty_hex(block.merkle_root);
cppdb::transaction guard(sql_);
cppdb::result result = sql_ <<
"SELECT block_id FROM blocks WHERE block_hash=decode(?, 'hex')"
<< block_hash_repr << cppdb::row;
if (!result.empty())
{
log_warning() << "Block '" << block_hash_repr << "' already exists";
blockchain_->organizer()->refresh_block(result.get<size_t>(0));
blockchain_->raise_barrier();
handle_store(error::object_already_exists);
return;
}
static cppdb::statement statement = sql_.prepare(
"INSERT INTO blocks( \
block_id, \
block_hash, \
space, \
depth, \
span_left, \
span_right, \
version, \
prev_block_hash, \
merkle, \
when_created, \
bits_head, \
bits_body, \
nonce \
) VALUES ( \
DEFAULT, \
decode(?, 'hex'), \
nextval('blocks_space_sequence'), \
0, \
0, \
0, \
?, \
decode(?, 'hex'), \
decode(?, 'hex'), \
TO_TIMESTAMP(?), \
?, \
?, \
? \
) \
RETURNING block_id"
);
statement.reset();
statement.bind(block_hash_repr);
statement.bind(block.version);
statement.bind(prev_block_repr);
statement.bind(merkle_repr);
statement.bind(block.timestamp);
uint32_t bits_head = extract_bits_head(block.bits),
bits_body = extract_bits_body(block.bits);
statement.bind(bits_head);
statement.bind(bits_body);
statement.bind(block.nonce);
result = statement.row();
pq_block_info block_info;
block_info.block_id = result.get<size_t>(0);
bool buffer_block = true;
for (size_t i = 0; i < block.transactions.size(); ++i)
{
message::transaction transaction = block.transactions[i];
pq_transaction_info tx_info;
tx_info.transaction_id =
insert(transaction, tx_info.input_ids, tx_info.output_ids);
if (tx_info.input_ids.empty())
{
BITCOIN_ASSERT(tx_info.output_ids.empty());
buffer_block = false;
}
// Create block <-> txn mapping
static cppdb::statement link_txs = sql_.prepare(
"INSERT INTO transactions_parents ( \
transaction_id, block_id, index_in_block) \
VALUES (?, ?, ?)"
);
link_txs.reset();
link_txs.bind(tx_info.transaction_id);
link_txs.bind(block_info.block_id);
link_txs.bind(i);
link_txs.exec();
block_info.transactions.push_back(tx_info);
}
if (buffer_block)
blockchain_->buffer_block(std::make_pair(block_info, block));
blockchain_->organizer()->refresh_block(block_info.block_id);
blockchain_->raise_barrier();
guard.commit();
handle_store(std::error_code());
}
void postgresql_storage::fetch_block_locator(
fetch_handler_block_locator handle_fetch)
{
strand()->post(std::bind(
&postgresql_storage::do_fetch_block_locator, shared_from_this(),
handle_fetch));
}
void postgresql_storage::do_fetch_block_locator(
fetch_handler_block_locator handle_fetch)
{
cppdb::result number_blocks_result = sql_ <<
"SELECT depth \
FROM chains \
ORDER BY work DESC \
LIMIT 1"
<< cppdb::row;
if (number_blocks_result.empty())
{
handle_fetch(error::object_doesnt_exist, message::block_locator());
return;
}
// Start at max_depth
int top_depth = number_blocks_result.get<size_t>(0);
std::vector<size_t> indices;
// Push last 10 indices first
size_t step = 1, start = 0;
for (int i = top_depth; i > 0; i -= step, ++start)
{
if (start >= 10)
step *= 2;
indices.push_back(i);
}
indices.push_back(0);
// Now actually fetch the hashes for these blocks
std::stringstream hack_sql;
hack_sql <<
"SELECT encode(block_hash, 'hex') \
FROM main_chain \
WHERE depth IN (";
for (size_t i = 0; i < indices.size(); ++i)
{
if (i != 0)
hack_sql << ", ";
hack_sql << indices[i];
}
hack_sql << ") ORDER BY depth DESC";
// ----------------------------------------------
cppdb::result block_hashes_result = sql_ << hack_sql.str();
message::block_locator locator;
while (block_hashes_result.next())
{
std::string block_hash_repr = block_hashes_result.get<std::string>(0);
locator.push_back(hash_from_bytea(block_hash_repr));
}
BITCOIN_ASSERT(locator.size() == indices.size());
handle_fetch(std::error_code(), locator);
}
void postgresql_storage::fetch_balance(const short_hash& pubkey_hash,
fetch_handler_balance handle_fetch)
{
strand()->post(std::bind(
&postgresql_storage::do_fetch_balance, shared_from_this(),
pubkey_hash, handle_fetch));
}
void postgresql_storage::do_fetch_balance(const short_hash& pubkey_hash,
fetch_handler_balance handle_fetch)
{
std::string total_script = "76 a9 14 " + pretty_hex(pubkey_hash) + " 88 ac";
static cppdb::statement statement = sql_.prepare(
"WITH outs AS ( \
SELECT \
transaction_hash, \
outputs.index_in_parent, \
outputs.value \
FROM \
outputs, \
transactions \
WHERE \
script=decode(?, 'hex') \
AND outputs.transaction_id=transactions.transaction_id \
) \
SELECT \
sql_to_internal(SUM(outs.value)) \
FROM outs \
LEFT JOIN inputs \
ON \
inputs.previous_output_hash=transaction_hash \
AND inputs.previous_output_index=outs.index_in_parent \
WHERE inputs IS NULL"
);
statement.reset();
statement.bind(total_script);
cppdb::result result = statement.row();
uint64_t value = 0;
if (!result.is_null(0))
value = result.get<uint64_t>(0);
handle_fetch(std::error_code(), value);
}
} // libbitcoin
<|endoftext|> |
<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/win/notify_icon.h"
#include "atom/browser/ui/win/notify_icon_host.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace atom {
NotifyIcon::NotifyIcon(NotifyIconHost* host,
UINT id,
HWND window,
UINT message)
: host_(host),
icon_id_(id),
window_(window),
message_id_(message),
menu_model_(NULL) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
// This can happen if the explorer process isn't running when we try to
// create the icon for some reason (for example, at startup).
if (!result)
LOG(WARNING) << "Unable to create status tray icon.";
}
NotifyIcon::~NotifyIcon() {
// Remove our icon.
host_->Remove(this);
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
Shell_NotifyIcon(NIM_DELETE, &icon_data);
}
void NotifyIcon::HandleClickEvent(int modifiers,
bool left_mouse_click,
bool double_button_click) {
gfx::Rect bounds = GetBounds();
if (left_mouse_click) {
if (double_button_click) // double left click
NotifyDoubleClicked(bounds, modifiers);
else // single left click
NotifyClicked(bounds, modifiers);
return;
} else if (!double_button_click) { // single right click
if (menu_model_)
PopUpContextMenu(gfx::Point(), menu_model_);
else
NotifyRightClicked(bounds, modifiers);
}
}
void NotifyIcon::ResetIcon() {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
// Delete any previously existing icon.
Shell_NotifyIcon(NIM_DELETE, &icon_data);
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
icon_data.hIcon = icon_.get();
// If we have an image, then set the NIF_ICON flag, which tells
// Shell_NotifyIcon() to set the image for the status icon it creates.
if (icon_data.hIcon)
icon_data.uFlags |= NIF_ICON;
// Re-add our icon.
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
if (!result)
LOG(WARNING) << "Unable to re-create status tray icon.";
}
void NotifyIcon::SetImage(HICON image) {
icon_ = base::win::ScopedHICON(CopyIcon(image));
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_ICON;
icon_data.hIcon = image;
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Error setting status tray icon image";
}
void NotifyIcon::SetPressedImage(HICON image) {
// Ignore pressed images, since the standard on Windows is to not highlight
// pressed status icons.
}
void NotifyIcon::SetToolTip(const std::string& tool_tip) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_TIP;
wcsncpy_s(icon_data.szTip, base::UTF8ToUTF16(tool_tip).c_str(), _TRUNCATE);
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to set tooltip for status tray icon";
}
void NotifyIcon::DisplayBalloon(HICON icon,
const base::string16& title,
const base::string16& contents) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_INFO;
icon_data.dwInfoFlags = NIIF_INFO;
wcsncpy_s(icon_data.szInfoTitle, title.c_str(), _TRUNCATE);
wcsncpy_s(icon_data.szInfo, contents.c_str(), _TRUNCATE);
icon_data.uTimeout = 0;
icon_data.hBalloonIcon = icon;
icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON;
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to create status tray balloon.";
}
void NotifyIcon::PopUpContextMenu(const gfx::Point& pos,
ui::SimpleMenuModel* menu_model) {
// Returns if context menu isn't set.
if (!menu_model)
return;
// Set our window as the foreground window, so the context menu closes when
// we click away from it.
if (!SetForegroundWindow(window_))
return;
// Show menu at mouse's position by default.
gfx::Rect rect(pos, gfx::Size());
if (pos.IsOrigin())
rect.set_origin(gfx::Screen::GetScreen()->GetCursorScreenPoint());
views::MenuRunner menu_runner(
menu_model,
views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS);
ignore_result(menu_runner.RunMenuAt(
NULL, NULL, rect, views::MENU_ANCHOR_TOPLEFT, ui::MENU_SOURCE_MOUSE));
}
void NotifyIcon::SetContextMenu(ui::SimpleMenuModel* menu_model) {
menu_model_ = menu_model;
}
gfx::Rect NotifyIcon::GetBounds() {
NOTIFYICONIDENTIFIER icon_id;
memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER));
icon_id.uID = icon_id_;
icon_id.hWnd = window_;
icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER);
RECT rect = { 0 };
Shell_NotifyIconGetRect(&icon_id, &rect);
return gfx::Rect(rect);
}
void NotifyIcon::InitIconData(NOTIFYICONDATA* icon_data) {
memset(icon_data, 0, sizeof(NOTIFYICONDATA));
icon_data->cbSize = sizeof(NOTIFYICONDATA);
icon_data->hWnd = window_;
icon_data->uID = icon_id_;
}
} // namespace atom
<commit_msg>win: Use DIP rect for tray icon's bounds<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/win/notify_icon.h"
#include "atom/browser/ui/win/notify_icon_host.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/win/dpi.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace atom {
NotifyIcon::NotifyIcon(NotifyIconHost* host,
UINT id,
HWND window,
UINT message)
: host_(host),
icon_id_(id),
window_(window),
message_id_(message),
menu_model_(NULL) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
// This can happen if the explorer process isn't running when we try to
// create the icon for some reason (for example, at startup).
if (!result)
LOG(WARNING) << "Unable to create status tray icon.";
}
NotifyIcon::~NotifyIcon() {
// Remove our icon.
host_->Remove(this);
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
Shell_NotifyIcon(NIM_DELETE, &icon_data);
}
void NotifyIcon::HandleClickEvent(int modifiers,
bool left_mouse_click,
bool double_button_click) {
gfx::Rect bounds = GetBounds();
if (left_mouse_click) {
if (double_button_click) // double left click
NotifyDoubleClicked(bounds, modifiers);
else // single left click
NotifyClicked(bounds, modifiers);
return;
} else if (!double_button_click) { // single right click
if (menu_model_)
PopUpContextMenu(gfx::Point(), menu_model_);
else
NotifyRightClicked(bounds, modifiers);
}
}
void NotifyIcon::ResetIcon() {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
// Delete any previously existing icon.
Shell_NotifyIcon(NIM_DELETE, &icon_data);
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
icon_data.hIcon = icon_.get();
// If we have an image, then set the NIF_ICON flag, which tells
// Shell_NotifyIcon() to set the image for the status icon it creates.
if (icon_data.hIcon)
icon_data.uFlags |= NIF_ICON;
// Re-add our icon.
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
if (!result)
LOG(WARNING) << "Unable to re-create status tray icon.";
}
void NotifyIcon::SetImage(HICON image) {
icon_ = base::win::ScopedHICON(CopyIcon(image));
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_ICON;
icon_data.hIcon = image;
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Error setting status tray icon image";
}
void NotifyIcon::SetPressedImage(HICON image) {
// Ignore pressed images, since the standard on Windows is to not highlight
// pressed status icons.
}
void NotifyIcon::SetToolTip(const std::string& tool_tip) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_TIP;
wcsncpy_s(icon_data.szTip, base::UTF8ToUTF16(tool_tip).c_str(), _TRUNCATE);
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to set tooltip for status tray icon";
}
void NotifyIcon::DisplayBalloon(HICON icon,
const base::string16& title,
const base::string16& contents) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_INFO;
icon_data.dwInfoFlags = NIIF_INFO;
wcsncpy_s(icon_data.szInfoTitle, title.c_str(), _TRUNCATE);
wcsncpy_s(icon_data.szInfo, contents.c_str(), _TRUNCATE);
icon_data.uTimeout = 0;
icon_data.hBalloonIcon = icon;
icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON;
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to create status tray balloon.";
}
void NotifyIcon::PopUpContextMenu(const gfx::Point& pos,
ui::SimpleMenuModel* menu_model) {
// Returns if context menu isn't set.
if (!menu_model)
return;
// Set our window as the foreground window, so the context menu closes when
// we click away from it.
if (!SetForegroundWindow(window_))
return;
// Show menu at mouse's position by default.
gfx::Rect rect(pos, gfx::Size());
if (pos.IsOrigin())
rect.set_origin(gfx::Screen::GetScreen()->GetCursorScreenPoint());
views::MenuRunner menu_runner(
menu_model,
views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS);
ignore_result(menu_runner.RunMenuAt(
NULL, NULL, rect, views::MENU_ANCHOR_TOPLEFT, ui::MENU_SOURCE_MOUSE));
}
void NotifyIcon::SetContextMenu(ui::SimpleMenuModel* menu_model) {
menu_model_ = menu_model;
}
gfx::Rect NotifyIcon::GetBounds() {
NOTIFYICONIDENTIFIER icon_id;
memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER));
icon_id.uID = icon_id_;
icon_id.hWnd = window_;
icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER);
RECT rect = { 0 };
Shell_NotifyIconGetRect(&icon_id, &rect);
return gfx::win::ScreenToDIPRect(gfx::Rect(rect));
}
void NotifyIcon::InitIconData(NOTIFYICONDATA* icon_data) {
memset(icon_data, 0, sizeof(NOTIFYICONDATA));
icon_data->cbSize = sizeof(NOTIFYICONDATA);
icon_data->hWnd = window_;
icon_data->uID = icon_id_;
}
} // namespace atom
<|endoftext|> |
<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/win/notify_icon.h"
#include "atom/browser/ui/win/notify_icon_host.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace atom {
NotifyIcon::NotifyIcon(NotifyIconHost* host,
UINT id,
HWND window,
UINT message)
: host_(host),
icon_id_(id),
window_(window),
message_id_(message),
menu_model_(NULL) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
// This can happen if the explorer process isn't running when we try to
// create the icon for some reason (for example, at startup).
if (!result)
LOG(WARNING) << "Unable to create status tray icon.";
}
NotifyIcon::~NotifyIcon() {
// Remove our icon.
host_->Remove(this);
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
Shell_NotifyIcon(NIM_DELETE, &icon_data);
}
void NotifyIcon::HandleClickEvent(const gfx::Point& cursor_pos,
bool left_mouse_click) {
// Pass to the observer if appropriate.
if (left_mouse_click) {
NOTIFYICONIDENTIFIER icon_id;
memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER));
icon_id.uID = icon_id_;
icon_id.hWnd = window_;
icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER);
RECT rect;
Shell_NotifyIconGetRect(&icon_id, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
NotifyClicked(gfx::Rect(rect.left, rect.top, width, height));
return;
}
if (!menu_model_)
return;
// Set our window as the foreground window, so the context menu closes when
// we click away from it.
if (!SetForegroundWindow(window_))
return;
views::MenuRunner menu_runner(
menu_model_,
views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS);
ignore_result(menu_runner.RunMenuAt(
NULL,
NULL,
gfx::Rect(cursor_pos, gfx::Size()),
views::MENU_ANCHOR_TOPLEFT,
ui::MENU_SOURCE_MOUSE));
}
void NotifyIcon::ResetIcon() {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
// Delete any previously existing icon.
Shell_NotifyIcon(NIM_DELETE, &icon_data);
InitIconData(&icon_data);
icon_data.uFlags = NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
icon_data.hIcon = icon_.Get();
// If we have an image, then set the NIF_ICON flag, which tells
// Shell_NotifyIcon() to set the image for the status icon it creates.
if (icon_data.hIcon)
icon_data.uFlags |= NIF_ICON;
// Re-add our icon.
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
if (!result)
LOG(WARNING) << "Unable to re-create status tray icon.";
}
void NotifyIcon::SetImage(const gfx::Image& image) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_ICON;
icon_.Set(IconUtil::CreateHICONFromSkBitmap(image.AsBitmap()));
icon_data.hIcon = icon_.Get();
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Error setting status tray icon image";
}
void NotifyIcon::SetPressedImage(const gfx::Image& image) {
// Ignore pressed images, since the standard on Windows is to not highlight
// pressed status icons.
}
void NotifyIcon::SetToolTip(const std::string& tool_tip) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_TIP;
wcscpy_s(icon_data.szTip, base::UTF8ToUTF16(tool_tip).c_str());
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to set tooltip for status tray icon";
}
void NotifyIcon::DisplayBalloon(const gfx::Image& icon,
const base::string16& title,
const base::string16& contents) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_INFO;
icon_data.dwInfoFlags = NIIF_INFO;
wcscpy_s(icon_data.szInfoTitle, title.c_str());
wcscpy_s(icon_data.szInfo, contents.c_str());
icon_data.uTimeout = 0;
base::win::Version win_version = base::win::GetVersion();
if (!icon.IsEmpty() && win_version != base::win::VERSION_PRE_XP) {
balloon_icon_.Set(IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap()));
icon_data.hBalloonIcon = balloon_icon_.Get();
icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON;
}
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to create status tray balloon.";
}
void NotifyIcon::SetContextMenu(ui::SimpleMenuModel* menu_model) {
menu_model_ = menu_model;
}
void NotifyIcon::InitIconData(NOTIFYICONDATA* icon_data) {
memset(icon_data, 0, sizeof(NOTIFYICONDATA));
icon_data->cbSize = sizeof(NOTIFYICONDATA);
icon_data->hWnd = window_;
icon_data->uID = icon_id_;
}
} // namespace atom
<commit_msg>Ow :poop:, where did that extra space come from?<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/win/notify_icon.h"
#include "atom/browser/ui/win/notify_icon_host.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace atom {
NotifyIcon::NotifyIcon(NotifyIconHost* host,
UINT id,
HWND window,
UINT message)
: host_(host),
icon_id_(id),
window_(window),
message_id_(message),
menu_model_(NULL) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
// This can happen if the explorer process isn't running when we try to
// create the icon for some reason (for example, at startup).
if (!result)
LOG(WARNING) << "Unable to create status tray icon.";
}
NotifyIcon::~NotifyIcon() {
// Remove our icon.
host_->Remove(this);
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
Shell_NotifyIcon(NIM_DELETE, &icon_data);
}
void NotifyIcon::HandleClickEvent(const gfx::Point& cursor_pos,
bool left_mouse_click) {
// Pass to the observer if appropriate.
if (left_mouse_click) {
NOTIFYICONIDENTIFIER icon_id;
memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER));
icon_id.uID = icon_id_;
icon_id.hWnd = window_;
icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER);
RECT rect;
Shell_NotifyIconGetRect(&icon_id, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
NotifyClicked(gfx::Rect(rect.left, rect.top, width, height));
return;
}
if (!menu_model_)
return;
// Set our window as the foreground window, so the context menu closes when
// we click away from it.
if (!SetForegroundWindow(window_))
return;
views::MenuRunner menu_runner(
menu_model_,
views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS);
ignore_result(menu_runner.RunMenuAt(
NULL,
NULL,
gfx::Rect(cursor_pos, gfx::Size()),
views::MENU_ANCHOR_TOPLEFT,
ui::MENU_SOURCE_MOUSE));
}
void NotifyIcon::ResetIcon() {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
// Delete any previously existing icon.
Shell_NotifyIcon(NIM_DELETE, &icon_data);
InitIconData(&icon_data);
icon_data.uFlags = NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
icon_data.hIcon = icon_.Get();
// If we have an image, then set the NIF_ICON flag, which tells
// Shell_NotifyIcon() to set the image for the status icon it creates.
if (icon_data.hIcon)
icon_data.uFlags |= NIF_ICON;
// Re-add our icon.
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
if (!result)
LOG(WARNING) << "Unable to re-create status tray icon.";
}
void NotifyIcon::SetImage(const gfx::Image& image) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_ICON;
icon_.Set(IconUtil::CreateHICONFromSkBitmap(image.AsBitmap()));
icon_data.hIcon = icon_.Get();
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Error setting status tray icon image";
}
void NotifyIcon::SetPressedImage(const gfx::Image& image) {
// Ignore pressed images, since the standard on Windows is to not highlight
// pressed status icons.
}
void NotifyIcon::SetToolTip(const std::string& tool_tip) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_TIP;
wcscpy_s(icon_data.szTip, base::UTF8ToUTF16(tool_tip).c_str());
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to set tooltip for status tray icon";
}
void NotifyIcon::DisplayBalloon(const gfx::Image& icon,
const base::string16& title,
const base::string16& contents) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags = NIF_INFO;
icon_data.dwInfoFlags = NIIF_INFO;
wcscpy_s(icon_data.szInfoTitle, title.c_str());
wcscpy_s(icon_data.szInfo, contents.c_str());
icon_data.uTimeout = 0;
base::win::Version win_version = base::win::GetVersion();
if (!icon.IsEmpty() && win_version != base::win::VERSION_PRE_XP) {
balloon_icon_.Set(IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap()));
icon_data.hBalloonIcon = balloon_icon_.Get();
icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON;
}
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to create status tray balloon.";
}
void NotifyIcon::SetContextMenu(ui::SimpleMenuModel* menu_model) {
menu_model_ = menu_model;
}
void NotifyIcon::InitIconData(NOTIFYICONDATA* icon_data) {
memset(icon_data, 0, sizeof(NOTIFYICONDATA));
icon_data->cbSize = sizeof(NOTIFYICONDATA);
icon_data->hWnd = window_;
icon_data->uID = icon_id_;
}
} // namespace atom
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013-2016 Estimation and Control Library (ECL). 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 ECL 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.
*
****************************************************************************/
/**
* @file ecl_yaw_controller.cpp
* Implementation of a simple orthogonal coordinated turn yaw PID controller.
*
* Authors and acknowledgements in header.
*/
#include "ecl_yaw_controller.h"
#include <stdint.h>
#include <float.h>
#include <geo/geo.h>
#include <ecl/ecl.h>
#include <mathlib/mathlib.h>
#include <systemlib/err.h>
#include <ecl/ecl.h>
ECL_YawController::ECL_YawController() :
ECL_Controller("yaw"),
_coordinated_min_speed(1.0f),
_max_rate(0.0f), /* disable by default */
_coordinated_method(0)
{
}
float ECL_YawController::control_attitude(const struct ECL_ControlData &ctl_data)
{
switch (_coordinated_method) {
case COORD_METHOD_OPEN:
return control_attitude_impl_openloop(ctl_data);
case COORD_METHOD_CLOSEACC:
return control_attitude_impl_accclosedloop(ctl_data);
default:
static hrt_abstime last_print = 0;
if (ecl_elapsed_time(&last_print) > 5e6) {
warnx("invalid param setting FW_YCO_METHOD");
last_print = ecl_absolute_time();
}
}
return _rate_setpoint;
}
float ECL_YawController::control_attitude_impl_openloop(const struct ECL_ControlData &ctl_data)
{
/* Do not calculate control signal with bad inputs */
if (!(PX4_ISFINITE(ctl_data.roll) &&
PX4_ISFINITE(ctl_data.pitch) &&
PX4_ISFINITE(ctl_data.speed_body_u) &&
PX4_ISFINITE(ctl_data.speed_body_v) &&
PX4_ISFINITE(ctl_data.speed_body_w) &&
PX4_ISFINITE(ctl_data.roll_rate_setpoint) &&
PX4_ISFINITE(ctl_data.pitch_rate_setpoint))) {
return _rate_setpoint;
}
float constrained_roll;
/* roll is used as feedforward term and inverted flight needs to be considered */
if (fabsf(ctl_data.roll) < math::radians(90.0f)) {
/* not inverted, but numerically still potentially close to infinity */
constrained_roll = math::constrain(ctl_data.roll, math::radians(-80.0f), math::radians(80.0f));
} else {
// inverted flight, constrain on the two extremes of -pi..+pi to avoid infinity
//note: the ranges are extended by 10 deg here to avoid numeric resolution effects
if (ctl_data.roll > 0.0f) {
/* right hemisphere */
constrained_roll = math::constrain(ctl_data.roll, math::radians(100.0f), math::radians(180.0f));
} else {
/* left hemisphere */
constrained_roll = math::constrain(ctl_data.roll, math::radians(-180.0f), math::radians(-100.0f));
}
}
/* Calculate desired yaw rate from coordinated turn constraint / (no side forces) */
_rate_setpoint = tanf(constrained_roll) * cosf(ctl_data.pitch) * 9.81f / (ctl_data.airspeed < ctl_data.airspeed_min ? ctl_data.airspeed_min : ctl_data.airspeed);
/* limit the rate */ //XXX: move to body angluar rates
if (_max_rate > 0.01f) {
_rate_setpoint = (_rate_setpoint > _max_rate) ? _max_rate : _rate_setpoint;
_rate_setpoint = (_rate_setpoint < -_max_rate) ? -_max_rate : _rate_setpoint;
}
if (!PX4_ISFINITE(_rate_setpoint)) {
warnx("yaw rate sepoint not finite");
_rate_setpoint = 0.0f;
}
return _rate_setpoint;
}
float ECL_YawController::control_bodyrate(const struct ECL_ControlData &ctl_data)
{
/* Do not calculate control signal with bad inputs */
if (!(PX4_ISFINITE(ctl_data.roll) && PX4_ISFINITE(ctl_data.pitch) && PX4_ISFINITE(ctl_data.body_y_rate) &&
PX4_ISFINITE(ctl_data.body_z_rate) && PX4_ISFINITE(ctl_data.pitch_rate_setpoint) &&
PX4_ISFINITE(ctl_data.airspeed_min) && PX4_ISFINITE(ctl_data.airspeed_max) &&
PX4_ISFINITE(ctl_data.scaler))) {
return math::constrain(_last_output, -1.0f, 1.0f);
}
/* get the usual dt estimate */
uint64_t dt_micros = ecl_elapsed_time(&_last_run);
_last_run = ecl_absolute_time();
float dt = (float)dt_micros * 1e-6f;
/* lock integral for long intervals */
bool lock_integrator = ctl_data.lock_integrator;
if (dt_micros > 500000) {
lock_integrator = true;
}
/* input conditioning */
float airspeed = ctl_data.airspeed;
if (!PX4_ISFINITE(airspeed)) {
/* airspeed is NaN, +- INF or not available, pick center of band */
airspeed = 0.5f * (ctl_data.airspeed_min + ctl_data.airspeed_max);
} else if (airspeed < ctl_data.airspeed_min) {
airspeed = ctl_data.airspeed_min;
}
/* Close the acceleration loop if _coordinated_method wants this: change body_rate setpoint */
if (_coordinated_method == COORD_METHOD_CLOSEACC) {
// XXX lateral acceleration needs to go into integrator with a gain
//_bodyrate_setpoint -= (ctl_data.acc_body_y / (airspeed * cosf(ctl_data.pitch)));
}
/* Calculate body angular rate error */
_rate_error = _bodyrate_setpoint - ctl_data.body_z_rate; //body angular rate error
if (!lock_integrator && _k_i > 0.0f && airspeed > 0.5f * ctl_data.airspeed_min) {
float id = _rate_error * dt;
/*
* anti-windup: do not allow integrator to increase if actuator is at limit
*/
if (_last_output < -1.0f) {
/* only allow motion to center: increase value */
id = math::max(id, 0.0f);
} else if (_last_output > 1.0f) {
/* only allow motion to center: decrease value */
id = math::min(id, 0.0f);
}
_integrator += id * _k_i;
}
/* integrator limit */
//xxx: until start detection is available: integral part in control signal is limited here
float integrator_constrained = math::constrain(_integrator, -_integrator_max, _integrator_max);
/* Apply PI rate controller and store non-limited output */
_last_output = (_bodyrate_setpoint * _k_ff + _rate_error * _k_p + integrator_constrained) * ctl_data.scaler *
ctl_data.scaler; //scaler is proportional to 1/airspeed
return math::constrain(_last_output, -1.0f, 1.0f);
}
float ECL_YawController::control_attitude_impl_accclosedloop(const struct ECL_ControlData &ctl_data)
{
/* dont set a rate setpoint */
return 0.0f;
}
float ECL_YawController::control_euler_rate(const struct ECL_ControlData &ctl_data)
{
/* Transform setpoint to body angular rates (jacobian) */
_bodyrate_setpoint = -sinf(ctl_data.roll) * ctl_data.pitch_rate_setpoint +
cosf(ctl_data.roll) * cosf(ctl_data.pitch) * _rate_setpoint;
return control_bodyrate(ctl_data);
}
<commit_msg>yaw controller: for now do not do turn compensation when inverted and use the roll setpoint as limit for turn compensation<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2016 Estimation and Control Library (ECL). 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 ECL 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.
*
****************************************************************************/
/**
* @file ecl_yaw_controller.cpp
* Implementation of a simple orthogonal coordinated turn yaw PID controller.
*
* Authors and acknowledgements in header.
*/
#include "ecl_yaw_controller.h"
#include <stdint.h>
#include <float.h>
#include <geo/geo.h>
#include <ecl/ecl.h>
#include <mathlib/mathlib.h>
#include <systemlib/err.h>
#include <ecl/ecl.h>
ECL_YawController::ECL_YawController() :
ECL_Controller("yaw"),
_coordinated_min_speed(1.0f),
_max_rate(0.0f), /* disable by default */
_coordinated_method(0)
{
}
float ECL_YawController::control_attitude(const struct ECL_ControlData &ctl_data)
{
switch (_coordinated_method) {
case COORD_METHOD_OPEN:
return control_attitude_impl_openloop(ctl_data);
case COORD_METHOD_CLOSEACC:
return control_attitude_impl_accclosedloop(ctl_data);
default:
static hrt_abstime last_print = 0;
if (ecl_elapsed_time(&last_print) > 5e6) {
warnx("invalid param setting FW_YCO_METHOD");
last_print = ecl_absolute_time();
}
}
return _rate_setpoint;
}
float ECL_YawController::control_attitude_impl_openloop(const struct ECL_ControlData &ctl_data)
{
/* Do not calculate control signal with bad inputs */
if (!(PX4_ISFINITE(ctl_data.roll) &&
PX4_ISFINITE(ctl_data.pitch) &&
PX4_ISFINITE(ctl_data.speed_body_u) &&
PX4_ISFINITE(ctl_data.speed_body_v) &&
PX4_ISFINITE(ctl_data.speed_body_w) &&
PX4_ISFINITE(ctl_data.roll_rate_setpoint) &&
PX4_ISFINITE(ctl_data.pitch_rate_setpoint))) {
return _rate_setpoint;
}
float constrained_roll;
bool inverted = false;
/* roll is used as feedforward term and inverted flight needs to be considered */
if (fabsf(ctl_data.roll) < math::radians(90.0f)) {
/* not inverted, but numerically still potentially close to infinity */
constrained_roll = math::constrain(ctl_data.roll, math::radians(-80.0f), math::radians(80.0f));
} else {
inverted = true;
// inverted flight, constrain on the two extremes of -pi..+pi to avoid infinity
//note: the ranges are extended by 10 deg here to avoid numeric resolution effects
if (ctl_data.roll > 0.0f) {
/* right hemisphere */
constrained_roll = math::constrain(ctl_data.roll, math::radians(100.0f), math::radians(180.0f));
} else {
/* left hemisphere */
constrained_roll = math::constrain(ctl_data.roll, math::radians(-180.0f), math::radians(-100.0f));
}
}
constrained_roll = math::constrain(constrained_roll, -ctl_data.roll_setpoint, ctl_data.roll_setpoint);
if (!inverted) {
/* Calculate desired yaw rate from coordinated turn constraint / (no side forces) */
_rate_setpoint = tanf(constrained_roll) * cosf(ctl_data.pitch) * 9.81f / (ctl_data.airspeed < ctl_data.airspeed_min ? ctl_data.airspeed_min : ctl_data.airspeed);
}
/* limit the rate */ //XXX: move to body angluar rates
if (_max_rate > 0.01f) {
_rate_setpoint = (_rate_setpoint > _max_rate) ? _max_rate : _rate_setpoint;
_rate_setpoint = (_rate_setpoint < -_max_rate) ? -_max_rate : _rate_setpoint;
}
if (!PX4_ISFINITE(_rate_setpoint)) {
warnx("yaw rate sepoint not finite");
_rate_setpoint = 0.0f;
}
return _rate_setpoint;
}
float ECL_YawController::control_bodyrate(const struct ECL_ControlData &ctl_data)
{
/* Do not calculate control signal with bad inputs */
if (!(PX4_ISFINITE(ctl_data.roll) && PX4_ISFINITE(ctl_data.pitch) && PX4_ISFINITE(ctl_data.body_y_rate) &&
PX4_ISFINITE(ctl_data.body_z_rate) && PX4_ISFINITE(ctl_data.pitch_rate_setpoint) &&
PX4_ISFINITE(ctl_data.airspeed_min) && PX4_ISFINITE(ctl_data.airspeed_max) &&
PX4_ISFINITE(ctl_data.scaler))) {
return math::constrain(_last_output, -1.0f, 1.0f);
}
/* get the usual dt estimate */
uint64_t dt_micros = ecl_elapsed_time(&_last_run);
_last_run = ecl_absolute_time();
float dt = (float)dt_micros * 1e-6f;
/* lock integral for long intervals */
bool lock_integrator = ctl_data.lock_integrator;
if (dt_micros > 500000) {
lock_integrator = true;
}
/* input conditioning */
float airspeed = ctl_data.airspeed;
if (!PX4_ISFINITE(airspeed)) {
/* airspeed is NaN, +- INF or not available, pick center of band */
airspeed = 0.5f * (ctl_data.airspeed_min + ctl_data.airspeed_max);
} else if (airspeed < ctl_data.airspeed_min) {
airspeed = ctl_data.airspeed_min;
}
/* Close the acceleration loop if _coordinated_method wants this: change body_rate setpoint */
if (_coordinated_method == COORD_METHOD_CLOSEACC) {
// XXX lateral acceleration needs to go into integrator with a gain
//_bodyrate_setpoint -= (ctl_data.acc_body_y / (airspeed * cosf(ctl_data.pitch)));
}
/* Calculate body angular rate error */
_rate_error = _bodyrate_setpoint - ctl_data.body_z_rate; // body angular rate error
if (!lock_integrator && _k_i > 0.0f && airspeed > 0.5f * ctl_data.airspeed_min) {
float id = _rate_error * dt;
/*
* anti-windup: do not allow integrator to increase if actuator is at limit
*/
if (_last_output < -1.0f) {
/* only allow motion to center: increase value */
id = math::max(id, 0.0f);
} else if (_last_output > 1.0f) {
/* only allow motion to center: decrease value */
id = math::min(id, 0.0f);
}
_integrator += id * _k_i;
}
/* integrator limit */
//xxx: until start detection is available: integral part in control signal is limited here
float integrator_constrained = math::constrain(_integrator, -_integrator_max, _integrator_max);
/* Apply PI rate controller and store non-limited output */
_last_output = (_bodyrate_setpoint * _k_ff + _rate_error * _k_p + integrator_constrained) * ctl_data.scaler *
ctl_data.scaler; //scaler is proportional to 1/airspeed
return math::constrain(_last_output, -1.0f, 1.0f);
}
float ECL_YawController::control_attitude_impl_accclosedloop(const struct ECL_ControlData &ctl_data)
{
/* dont set a rate setpoint */
return 0.0f;
}
float ECL_YawController::control_euler_rate(const struct ECL_ControlData &ctl_data)
{
/* Transform setpoint to body angular rates (jacobian) */
_bodyrate_setpoint = -sinf(ctl_data.roll) * ctl_data.pitch_rate_setpoint +
cosf(ctl_data.roll) * cosf(ctl_data.pitch) * _rate_setpoint;
return control_bodyrate(ctl_data);
}
<|endoftext|> |
<commit_before>//===-- StraightLineStrengthReduce.cpp - ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements straight-line strength reduction (SLSR). Unlike loop
// strength reduction, this algorithm is designed to reduce arithmetic
// redundancy in straight-line code instead of loops. It has proven to be
// effective in simplifying arithmetic statements derived from an unrolled loop.
// It can also simplify the logic of SeparateConstOffsetFromGEP.
//
// There are many optimizations we can perform in the domain of SLSR. This file
// for now contains only an initial step. Specifically, we look for strength
// reduction candidate in the form of
//
// (B + i) * S
//
// where B and S are integer constants or variables, and i is a constant
// integer. If we found two such candidates
//
// S1: X = (B + i) * S S2: Y = (B + i') * S
//
// and S1 dominates S2, we call S1 a basis of S2, and can replace S2 with
//
// Y = X + (i' - i) * S
//
// where (i' - i) * S is folded to the extent possible. When S2 has multiple
// bases, we pick the one that is closest to S2, or S2's "immediate" basis.
//
// TODO:
//
// - Handle candidates in the form of B + i * S
//
// - Handle candidates in the form of pointer arithmetics. e.g., B[i * S]
//
// - Floating point arithmetics when fast math is enabled.
//
// - SLSR may decrease ILP at the architecture level. Targets that are very
// sensitive to ILP may want to disable it. Having SLSR to consider ILP is
// left as future work.
#include <vector>
#include "llvm/ADT/DenseSet.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
using namespace PatternMatch;
namespace {
class StraightLineStrengthReduce : public FunctionPass {
public:
// SLSR candidate. Such a candidate must be in the form of
// (Base + Index) * Stride
struct Candidate : public ilist_node<Candidate> {
Candidate(Value *B = nullptr, ConstantInt *Idx = nullptr,
Value *S = nullptr, Instruction *I = nullptr)
: Base(B), Index(Idx), Stride(S), Ins(I), Basis(nullptr) {}
Value *Base;
ConstantInt *Index;
Value *Stride;
// The instruction this candidate corresponds to. It helps us to rewrite a
// candidate with respect to its immediate basis. Note that one instruction
// can corresponds to multiple candidates depending on how you associate the
// expression. For instance,
//
// (a + 1) * (b + 2)
//
// can be treated as
//
// <Base: a, Index: 1, Stride: b + 2>
//
// or
//
// <Base: b, Index: 2, Stride: a + 1>
Instruction *Ins;
// Points to the immediate basis of this candidate, or nullptr if we cannot
// find any basis for this candidate.
Candidate *Basis;
};
static char ID;
StraightLineStrengthReduce() : FunctionPass(ID), DT(nullptr) {
initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
// We do not modify the shape of the CFG.
AU.setPreservesCFG();
}
bool runOnFunction(Function &F) override;
private:
// Returns true if Basis is a basis for C, i.e., Basis dominates C and they
// share the same base and stride.
bool isBasisFor(const Candidate &Basis, const Candidate &C);
// Checks whether I is in a candidate form. If so, adds all the matching forms
// to Candidates, and tries to find the immediate basis for each of them.
void allocateCandidateAndFindBasis(Instruction *I);
// Given that I is in the form of "(B + Idx) * S", adds this form to
// Candidates, and finds its immediate basis.
void allocateCandidateAndFindBasis(Value *B, ConstantInt *Idx, Value *S,
Instruction *I);
// Rewrites candidate C with respect to Basis.
void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
DominatorTree *DT;
ilist<Candidate> Candidates;
// Temporarily holds all instructions that are unlinked (but not deleted) by
// rewriteCandidateWithBasis. These instructions will be actually removed
// after all rewriting finishes.
DenseSet<Instruction *> UnlinkedInstructions;
};
} // anonymous namespace
char StraightLineStrengthReduce::ID = 0;
INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
"Straight line strength reduction", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
"Straight line strength reduction", false, false)
FunctionPass *llvm::createStraightLineStrengthReducePass() {
return new StraightLineStrengthReduce();
}
bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
const Candidate &C) {
return (Basis.Ins != C.Ins && // skip the same instruction
// Basis must dominate C in order to rewrite C with respect to Basis.
DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
// They share the same base and stride.
Basis.Base == C.Base &&
Basis.Stride == C.Stride);
}
// TODO: We currently implement an algorithm whose time complexity is linear to
// the number of existing candidates. However, a better algorithm exists. We
// could depth-first search the dominator tree, and maintain a hash table that
// contains all candidates that dominate the node being traversed. This hash
// table is indexed by the base and the stride of a candidate. Therefore,
// finding the immediate basis of a candidate boils down to one hash-table look
// up.
void StraightLineStrengthReduce::allocateCandidateAndFindBasis(Value *B,
ConstantInt *Idx,
Value *S,
Instruction *I) {
Candidate C(B, Idx, S, I);
// Try to compute the immediate basis of C.
unsigned NumIterations = 0;
// Limit the scan radius to avoid running forever.
static const int MaxNumIterations = 50;
for (auto Basis = Candidates.rbegin();
Basis != Candidates.rend() && NumIterations < MaxNumIterations;
++Basis, ++NumIterations) {
if (isBasisFor(*Basis, C)) {
C.Basis = &(*Basis);
break;
}
}
// Regardless of whether we find a basis for C, we need to push C to the
// candidate list.
Candidates.push_back(C);
}
void StraightLineStrengthReduce::allocateCandidateAndFindBasis(Instruction *I) {
Value *B = nullptr;
ConstantInt *Idx = nullptr;
// "(Base + Index) * Stride" must be a Mul instruction at the first hand.
if (I->getOpcode() == Instruction::Mul) {
if (IntegerType *ITy = dyn_cast<IntegerType>(I->getType())) {
Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
for (unsigned Swapped = 0; Swapped < 2; ++Swapped) {
// Only handle the canonical operand ordering.
if (match(LHS, m_Add(m_Value(B), m_ConstantInt(Idx)))) {
// If LHS is in the form of "Base + Index", then I is in the form of
// "(Base + Index) * RHS".
allocateCandidateAndFindBasis(B, Idx, RHS, I);
} else {
// Otherwise, at least try the form (LHS + 0) * RHS.
allocateCandidateAndFindBasis(LHS, ConstantInt::get(ITy, 0), RHS, I);
}
// Swap LHS and RHS so that we also cover the cases where LHS is the
// stride.
if (LHS == RHS)
break;
std::swap(LHS, RHS);
}
}
}
}
void StraightLineStrengthReduce::rewriteCandidateWithBasis(
const Candidate &C, const Candidate &Basis) {
// An instruction can correspond to multiple candidates. Therefore, instead of
// simply deleting an instruction when we rewrite it, we mark its parent as
// nullptr (i.e. unlink it) so that we can skip the candidates whose
// instruction is already rewritten.
if (!C.Ins->getParent())
return;
assert(C.Base == Basis.Base && C.Stride == Basis.Stride);
// Basis = (B + i) * S
// C = (B + i') * S
// ==>
// C = Basis + (i' - i) * S
IRBuilder<> Builder(C.Ins);
ConstantInt *IndexOffset = ConstantInt::get(
C.Ins->getContext(), C.Index->getValue() - Basis.Index->getValue());
Value *Reduced;
// TODO: preserve nsw/nuw in some cases.
if (IndexOffset->isOne()) {
// If (i' - i) is 1, fold C into Basis + S.
Reduced = Builder.CreateAdd(Basis.Ins, C.Stride);
} else if (IndexOffset->isMinusOne()) {
// If (i' - i) is -1, fold C into Basis - S.
Reduced = Builder.CreateSub(Basis.Ins, C.Stride);
} else {
Value *Bump = Builder.CreateMul(C.Stride, IndexOffset);
Reduced = Builder.CreateAdd(Basis.Ins, Bump);
}
Reduced->takeName(C.Ins);
C.Ins->replaceAllUsesWith(Reduced);
C.Ins->dropAllReferences();
// Unlink C.Ins so that we can skip other candidates also corresponding to
// C.Ins. The actual deletion is postponed to the end of runOnFunction.
C.Ins->removeFromParent();
UnlinkedInstructions.insert(C.Ins);
}
bool StraightLineStrengthReduce::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
// Traverse the dominator tree in the depth-first order. This order makes sure
// all bases of a candidate are in Candidates when we process it.
for (auto node = GraphTraits<DominatorTree *>::nodes_begin(DT);
node != GraphTraits<DominatorTree *>::nodes_end(DT); ++node) {
BasicBlock *B = node->getBlock();
for (auto I = B->begin(); I != B->end(); ++I) {
allocateCandidateAndFindBasis(I);
}
}
// Rewrite candidates in the reverse depth-first order. This order makes sure
// a candidate being rewritten is not a basis for any other candidate.
while (!Candidates.empty()) {
const Candidate &C = Candidates.back();
if (C.Basis != nullptr) {
rewriteCandidateWithBasis(C, *C.Basis);
}
Candidates.pop_back();
}
// Delete all unlink instructions.
for (auto I : UnlinkedInstructions) {
delete I;
}
bool Ret = !UnlinkedInstructions.empty();
UnlinkedInstructions.clear();
return Ret;
}
<commit_msg>Fixing a -Wsign-compare warning; NFC<commit_after>//===-- StraightLineStrengthReduce.cpp - ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements straight-line strength reduction (SLSR). Unlike loop
// strength reduction, this algorithm is designed to reduce arithmetic
// redundancy in straight-line code instead of loops. It has proven to be
// effective in simplifying arithmetic statements derived from an unrolled loop.
// It can also simplify the logic of SeparateConstOffsetFromGEP.
//
// There are many optimizations we can perform in the domain of SLSR. This file
// for now contains only an initial step. Specifically, we look for strength
// reduction candidate in the form of
//
// (B + i) * S
//
// where B and S are integer constants or variables, and i is a constant
// integer. If we found two such candidates
//
// S1: X = (B + i) * S S2: Y = (B + i') * S
//
// and S1 dominates S2, we call S1 a basis of S2, and can replace S2 with
//
// Y = X + (i' - i) * S
//
// where (i' - i) * S is folded to the extent possible. When S2 has multiple
// bases, we pick the one that is closest to S2, or S2's "immediate" basis.
//
// TODO:
//
// - Handle candidates in the form of B + i * S
//
// - Handle candidates in the form of pointer arithmetics. e.g., B[i * S]
//
// - Floating point arithmetics when fast math is enabled.
//
// - SLSR may decrease ILP at the architecture level. Targets that are very
// sensitive to ILP may want to disable it. Having SLSR to consider ILP is
// left as future work.
#include <vector>
#include "llvm/ADT/DenseSet.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
using namespace PatternMatch;
namespace {
class StraightLineStrengthReduce : public FunctionPass {
public:
// SLSR candidate. Such a candidate must be in the form of
// (Base + Index) * Stride
struct Candidate : public ilist_node<Candidate> {
Candidate(Value *B = nullptr, ConstantInt *Idx = nullptr,
Value *S = nullptr, Instruction *I = nullptr)
: Base(B), Index(Idx), Stride(S), Ins(I), Basis(nullptr) {}
Value *Base;
ConstantInt *Index;
Value *Stride;
// The instruction this candidate corresponds to. It helps us to rewrite a
// candidate with respect to its immediate basis. Note that one instruction
// can corresponds to multiple candidates depending on how you associate the
// expression. For instance,
//
// (a + 1) * (b + 2)
//
// can be treated as
//
// <Base: a, Index: 1, Stride: b + 2>
//
// or
//
// <Base: b, Index: 2, Stride: a + 1>
Instruction *Ins;
// Points to the immediate basis of this candidate, or nullptr if we cannot
// find any basis for this candidate.
Candidate *Basis;
};
static char ID;
StraightLineStrengthReduce() : FunctionPass(ID), DT(nullptr) {
initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
// We do not modify the shape of the CFG.
AU.setPreservesCFG();
}
bool runOnFunction(Function &F) override;
private:
// Returns true if Basis is a basis for C, i.e., Basis dominates C and they
// share the same base and stride.
bool isBasisFor(const Candidate &Basis, const Candidate &C);
// Checks whether I is in a candidate form. If so, adds all the matching forms
// to Candidates, and tries to find the immediate basis for each of them.
void allocateCandidateAndFindBasis(Instruction *I);
// Given that I is in the form of "(B + Idx) * S", adds this form to
// Candidates, and finds its immediate basis.
void allocateCandidateAndFindBasis(Value *B, ConstantInt *Idx, Value *S,
Instruction *I);
// Rewrites candidate C with respect to Basis.
void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
DominatorTree *DT;
ilist<Candidate> Candidates;
// Temporarily holds all instructions that are unlinked (but not deleted) by
// rewriteCandidateWithBasis. These instructions will be actually removed
// after all rewriting finishes.
DenseSet<Instruction *> UnlinkedInstructions;
};
} // anonymous namespace
char StraightLineStrengthReduce::ID = 0;
INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
"Straight line strength reduction", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
"Straight line strength reduction", false, false)
FunctionPass *llvm::createStraightLineStrengthReducePass() {
return new StraightLineStrengthReduce();
}
bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
const Candidate &C) {
return (Basis.Ins != C.Ins && // skip the same instruction
// Basis must dominate C in order to rewrite C with respect to Basis.
DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
// They share the same base and stride.
Basis.Base == C.Base &&
Basis.Stride == C.Stride);
}
// TODO: We currently implement an algorithm whose time complexity is linear to
// the number of existing candidates. However, a better algorithm exists. We
// could depth-first search the dominator tree, and maintain a hash table that
// contains all candidates that dominate the node being traversed. This hash
// table is indexed by the base and the stride of a candidate. Therefore,
// finding the immediate basis of a candidate boils down to one hash-table look
// up.
void StraightLineStrengthReduce::allocateCandidateAndFindBasis(Value *B,
ConstantInt *Idx,
Value *S,
Instruction *I) {
Candidate C(B, Idx, S, I);
// Try to compute the immediate basis of C.
unsigned NumIterations = 0;
// Limit the scan radius to avoid running forever.
static const unsigned MaxNumIterations = 50;
for (auto Basis = Candidates.rbegin();
Basis != Candidates.rend() && NumIterations < MaxNumIterations;
++Basis, ++NumIterations) {
if (isBasisFor(*Basis, C)) {
C.Basis = &(*Basis);
break;
}
}
// Regardless of whether we find a basis for C, we need to push C to the
// candidate list.
Candidates.push_back(C);
}
void StraightLineStrengthReduce::allocateCandidateAndFindBasis(Instruction *I) {
Value *B = nullptr;
ConstantInt *Idx = nullptr;
// "(Base + Index) * Stride" must be a Mul instruction at the first hand.
if (I->getOpcode() == Instruction::Mul) {
if (IntegerType *ITy = dyn_cast<IntegerType>(I->getType())) {
Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
for (unsigned Swapped = 0; Swapped < 2; ++Swapped) {
// Only handle the canonical operand ordering.
if (match(LHS, m_Add(m_Value(B), m_ConstantInt(Idx)))) {
// If LHS is in the form of "Base + Index", then I is in the form of
// "(Base + Index) * RHS".
allocateCandidateAndFindBasis(B, Idx, RHS, I);
} else {
// Otherwise, at least try the form (LHS + 0) * RHS.
allocateCandidateAndFindBasis(LHS, ConstantInt::get(ITy, 0), RHS, I);
}
// Swap LHS and RHS so that we also cover the cases where LHS is the
// stride.
if (LHS == RHS)
break;
std::swap(LHS, RHS);
}
}
}
}
void StraightLineStrengthReduce::rewriteCandidateWithBasis(
const Candidate &C, const Candidate &Basis) {
// An instruction can correspond to multiple candidates. Therefore, instead of
// simply deleting an instruction when we rewrite it, we mark its parent as
// nullptr (i.e. unlink it) so that we can skip the candidates whose
// instruction is already rewritten.
if (!C.Ins->getParent())
return;
assert(C.Base == Basis.Base && C.Stride == Basis.Stride);
// Basis = (B + i) * S
// C = (B + i') * S
// ==>
// C = Basis + (i' - i) * S
IRBuilder<> Builder(C.Ins);
ConstantInt *IndexOffset = ConstantInt::get(
C.Ins->getContext(), C.Index->getValue() - Basis.Index->getValue());
Value *Reduced;
// TODO: preserve nsw/nuw in some cases.
if (IndexOffset->isOne()) {
// If (i' - i) is 1, fold C into Basis + S.
Reduced = Builder.CreateAdd(Basis.Ins, C.Stride);
} else if (IndexOffset->isMinusOne()) {
// If (i' - i) is -1, fold C into Basis - S.
Reduced = Builder.CreateSub(Basis.Ins, C.Stride);
} else {
Value *Bump = Builder.CreateMul(C.Stride, IndexOffset);
Reduced = Builder.CreateAdd(Basis.Ins, Bump);
}
Reduced->takeName(C.Ins);
C.Ins->replaceAllUsesWith(Reduced);
C.Ins->dropAllReferences();
// Unlink C.Ins so that we can skip other candidates also corresponding to
// C.Ins. The actual deletion is postponed to the end of runOnFunction.
C.Ins->removeFromParent();
UnlinkedInstructions.insert(C.Ins);
}
bool StraightLineStrengthReduce::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
// Traverse the dominator tree in the depth-first order. This order makes sure
// all bases of a candidate are in Candidates when we process it.
for (auto node = GraphTraits<DominatorTree *>::nodes_begin(DT);
node != GraphTraits<DominatorTree *>::nodes_end(DT); ++node) {
BasicBlock *B = node->getBlock();
for (auto I = B->begin(); I != B->end(); ++I) {
allocateCandidateAndFindBasis(I);
}
}
// Rewrite candidates in the reverse depth-first order. This order makes sure
// a candidate being rewritten is not a basis for any other candidate.
while (!Candidates.empty()) {
const Candidate &C = Candidates.back();
if (C.Basis != nullptr) {
rewriteCandidateWithBasis(C, *C.Basis);
}
Candidates.pop_back();
}
// Delete all unlink instructions.
for (auto I : UnlinkedInstructions) {
delete I;
}
bool Ret = !UnlinkedInstructions.empty();
UnlinkedInstructions.clear();
return Ret;
}
<|endoftext|> |
<commit_before>// SPDX-License-Identifier: Apache-2.0
// ----------------------------------------------------------------------------
// Copyright 2020-2021 Arm Limited
//
// 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.
// ----------------------------------------------------------------------------
/**
* @brief Platform-specific function implementations.
*
* This module contains functions for querying the host extended ISA support.
*/
// Include before the defines below to pick up any auto-setup based on compiler
// built-in config, if not being set explicitly by the build system
#include "astcenc_internal.h"
#if (ASTCENC_SSE > 0) || (ASTCENC_AVX > 0) || \
(ASTCENC_POPCNT > 0) || (ASTCENC_F16C > 0)
static bool g_init { false };
/** Does this CPU support SSE 4.1? Set to -1 if not yet initialized. */
static bool g_cpu_has_sse41 { false };
/** Does this CPU support AVX2? Set to -1 if not yet initialized. */
static bool g_cpu_has_avx2 { false };
/** Does this CPU support POPCNT? Set to -1 if not yet initialized. */
static bool g_cpu_has_popcnt { false };
/** Does this CPU support F16C? Set to -1 if not yet initialized. */
static bool g_cpu_has_f16c { false };
/* ============================================================================
Platform code for Visual Studio
============================================================================ */
#if !defined(__clang__) && defined(_MSC_VER)
#include <intrin.h>
/**
* @brief Detect platform CPU ISA support and update global trackers.
*/
static void detect_cpu_isa()
{
int data[4];
__cpuid(data, 0);
int num_id = data[0];
if (num_id >= 1)
{
__cpuidex(data, 1, 0);
// SSE41 = Bank 1, ECX, bit 19
g_cpu_has_sse41 = data[2] & (1 << 19) ? true : false;
// POPCNT = Bank 1, ECX, bit 23
g_cpu_has_popcnt = data[2] & (1 << 23) ? true : false;
// F16C = Bank 1, ECX, bit 29
g_cpu_has_f16c = data[2] & (1 << 29) ? true : false;
}
if (num_id >= 7)
{
__cpuidex(data, 7, 0);
// AVX2 = Bank 7, EBX, bit 5
g_cpu_has_avx2 = data[1] & (1 << 5) ? true : false;
}
g_init = true;
}
/* ============================================================================
Platform code for GCC and Clang
============================================================================ */
#else
#include <cpuid.h>
/**
* @brief Detect platform CPU ISA support and update global trackers.
*/
static void detect_cpu_isa()
{
unsigned int data[4];
if (__get_cpuid_count(1, 0, &data[0], &data[1], &data[2], &data[3]))
{
// SSE41 = Bank 1, ECX, bit 19
g_cpu_has_sse41 = data[2] & (1 << 19) ? true : false;
// POPCNT = Bank 1, ECX, bit 23
g_cpu_has_popcnt = data[2] & (1 << 23) ? true : false;
// F16C = Bank 1, ECX, bit 29
g_cpu_has_f16c = data[2] & (1 << 29) ? true : false;
}
g_cpu_has_avx2 = 0;
if (__get_cpuid_count(7, 0, &data[0], &data[1], &data[2], &data[3]))
{
// AVX2 = Bank 7, EBX, bit 5
g_cpu_has_avx2 = data[1] & (1 << 5) ? true : false;
}
g_init = true;
}
#endif
/* See header for documentation. */
bool cpu_supports_popcnt()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_popcnt;
}
/* See header for documentation. */
bool cpu_supports_f16c()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_f16c;
}
/* See header for documentation. */
bool cpu_supports_sse41()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_sse41;
}
/* See header for documentation. */
bool cpu_supports_avx2()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_avx2;
}
#endif
<commit_msg>Add thread syncs on CPU state tracker updates<commit_after>// SPDX-License-Identifier: Apache-2.0
// ----------------------------------------------------------------------------
// Copyright 2020-2021 Arm Limited
//
// 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.
// ----------------------------------------------------------------------------
/**
* @brief Platform-specific function implementations.
*
* This module contains functions for querying the host extended ISA support.
*/
// Include before the defines below to pick up any auto-setup based on compiler
// built-in config, if not being set explicitly by the build system
#include "astcenc_internal.h"
#if (ASTCENC_SSE > 0) || (ASTCENC_AVX > 0) || \
(ASTCENC_POPCNT > 0) || (ASTCENC_F16C > 0)
static bool g_init { false };
/** Does this CPU support SSE 4.1? Set to -1 if not yet initialized. */
static bool g_cpu_has_sse41 { false };
/** Does this CPU support AVX2? Set to -1 if not yet initialized. */
static bool g_cpu_has_avx2 { false };
/** Does this CPU support POPCNT? Set to -1 if not yet initialized. */
static bool g_cpu_has_popcnt { false };
/** Does this CPU support F16C? Set to -1 if not yet initialized. */
static bool g_cpu_has_f16c { false };
/* ============================================================================
Platform code for Visual Studio
============================================================================ */
#if !defined(__clang__) && defined(_MSC_VER)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <intrin.h>
/**
* @brief Detect platform CPU ISA support and update global trackers.
*/
static void detect_cpu_isa()
{
int data[4];
__cpuid(data, 0);
int num_id = data[0];
if (num_id >= 1)
{
__cpuidex(data, 1, 0);
// SSE41 = Bank 1, ECX, bit 19
g_cpu_has_sse41 = data[2] & (1 << 19) ? true : false;
// POPCNT = Bank 1, ECX, bit 23
g_cpu_has_popcnt = data[2] & (1 << 23) ? true : false;
// F16C = Bank 1, ECX, bit 29
g_cpu_has_f16c = data[2] & (1 << 29) ? true : false;
}
if (num_id >= 7)
{
__cpuidex(data, 7, 0);
// AVX2 = Bank 7, EBX, bit 5
g_cpu_has_avx2 = data[1] & (1 << 5) ? true : false;
}
// Ensure state bits are updated before init flag is updated
MemoryBarrier();
g_init = true;
}
/* ============================================================================
Platform code for GCC and Clang
============================================================================ */
#else
#include <cpuid.h>
/**
* @brief Detect platform CPU ISA support and update global trackers.
*/
static void detect_cpu_isa()
{
unsigned int data[4];
if (__get_cpuid_count(1, 0, &data[0], &data[1], &data[2], &data[3]))
{
// SSE41 = Bank 1, ECX, bit 19
g_cpu_has_sse41 = data[2] & (1 << 19) ? true : false;
// POPCNT = Bank 1, ECX, bit 23
g_cpu_has_popcnt = data[2] & (1 << 23) ? true : false;
// F16C = Bank 1, ECX, bit 29
g_cpu_has_f16c = data[2] & (1 << 29) ? true : false;
}
g_cpu_has_avx2 = 0;
if (__get_cpuid_count(7, 0, &data[0], &data[1], &data[2], &data[3]))
{
// AVX2 = Bank 7, EBX, bit 5
g_cpu_has_avx2 = data[1] & (1 << 5) ? true : false;
}
// Ensure state bits are updated before init flag is updated
__sync_synchronize();
g_init = true;
}
#endif
/* See header for documentation. */
bool cpu_supports_popcnt()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_popcnt;
}
/* See header for documentation. */
bool cpu_supports_f16c()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_f16c;
}
/* See header for documentation. */
bool cpu_supports_sse41()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_sse41;
}
/* See header for documentation. */
bool cpu_supports_avx2()
{
if (!g_init)
{
detect_cpu_isa();
}
return g_cpu_has_avx2;
}
#endif
<|endoftext|> |
<commit_before>#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <functional>
#include <random>
#include <vector>
#include <string>
#include <gauss_multi.h>
#include <gp.h>
using namespace std;
typedef unsigned int uint;
// Random engine to use throughout
default_random_engine gen;
// How many functions to sample at each step
int n_samp = 5;
void to_tikz(vector<vector<double>> X, vector<vector<double>> Y, string fname)
{
assert(X.size() == Y.size());
FILE *f = fopen(fname.c_str(), "w");
// Define colours (TODO-someday: make this parametrised...)
fprintf(f, "\\definecolor{mycolor0}{rgb}{0.00000,0.44700,0.74100}%%\n");
fprintf(f, "\\definecolor{mycolor1}{rgb}{0.85000,0.32500,0.09800}%%\n");
fprintf(f, "\\definecolor{mycolor2}{rgb}{0.92900,0.69400,0.12500}%%\n");
fprintf(f, "\\definecolor{mycolor3}{rgb}{0.49400,0.18400,0.55600}%%\n");
fprintf(f, "\\definecolor{mycolor4}{rgb}{0.46600,0.67400,0.18800}%%\n");
// Begin picture
fprintf(f, "\\begin{tikzpicture}[very thick]\n");
// Begin axis (with all parameters)
fprintf(f, "\\begin{axis}[width=6.028in, height=4.754in,\n");
fprintf(f, "scale only axis, xmin=-1, xmax=1, ymin=-5.0, ymax=5.0,\n");
fprintf(f, "axis background/.style={fill=white}]\n");
// Add plots
for (uint i=0;i<X.size();i++)
{
assert(X[i].size() == Y[i].size());
fprintf(f, "\\addplot[color=mycolor%d, solid] table[row sep=crcr]{%%\n", i);
for (uint j=0;j<X[i].size();j++)
{
fprintf(f, "%.10lf %.10lf\\\\\n", X[i][j], Y[i][j]);
}
fprintf(f, "};\n");
}
fprintf(f, "\\end{axis}\n");
fprintf(f, "\\end{tikzpicture}\n");
fclose(f);
}
int main()
{
// Create a new Gaussian process...
// use zero-mean, squared-exponential covariance (hyperparam l = 1.0), no noise.
auto m = [](double) { return 0; };
auto k = [](double x, double y) { return exp(-(x - y) * (x - y) / (2.0 * 1.0)); };
GP gp(m, k, 0.0);
// points to be used to plot lines
vector<double> xs;
for (double x=-1.0;x<=1.0;x+=0.001) xs.push_back(x);
// Sample the prior
vector<double> mu = gp.get_means(xs);
vector<vector<double>> Sigma = gp.get_covar(xs);
/*for (uint i=0;i<Sigma.size();i++)
{
for (uint j=0;j<Sigma.size();j++)
{
printf("%.2lf ", Sigma[i][j]);
}
printf("\n");
}*/
MultiGaussian N(gen, mu, Sigma);
vector<vector<double>> Xs(n_samp, xs);
vector<vector<double>> Ys(n_samp);
for (int i=0;i<n_samp;i++)
{
Ys[i] = N.sample();
}
to_tikz(Xs, Ys, "test.tex");
return 0;
}
<commit_msg>OK parameters, need to fix posterior<commit_after>#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <functional>
#include <random>
#include <vector>
#include <string>
#include <gauss_multi.h>
#include <gp.h>
using namespace std;
typedef unsigned int uint;
// Random engine to use throughout
default_random_engine gen;
// How many functions to sample at each step
int n_samp = 5;
void to_tikz(vector<vector<double>> X, vector<vector<double>> Y, string fname)
{
assert(X.size() == Y.size());
FILE *f = fopen(fname.c_str(), "w");
// Define colours (TODO-someday: make this parametrised...)
fprintf(f, "\\definecolor{mycolor0}{rgb}{0.00000,0.44700,0.74100}%%\n");
fprintf(f, "\\definecolor{mycolor1}{rgb}{0.85000,0.32500,0.09800}%%\n");
fprintf(f, "\\definecolor{mycolor2}{rgb}{0.92900,0.69400,0.12500}%%\n");
fprintf(f, "\\definecolor{mycolor3}{rgb}{0.49400,0.18400,0.55600}%%\n");
fprintf(f, "\\definecolor{mycolor4}{rgb}{0.46600,0.67400,0.18800}%%\n");
// Begin picture
fprintf(f, "\\begin{tikzpicture}[very thick]\n");
// Begin axis (with all parameters)
fprintf(f, "\\begin{axis}[very thick, width=6.028in, height=4.754in,\n");
fprintf(f, "scale only axis, xmin=-5, xmax=5, ymin=-2, ymax=2,\n");
fprintf(f, "axis background/.style={fill=white}]\n");
// Add plots
for (uint i=0;i<X.size();i++)
{
assert(X[i].size() == Y[i].size());
fprintf(f, "\\addplot[color=mycolor%d, solid, smooth] table[row sep=crcr]{%%\n", i);
for (uint j=0;j<X[i].size();j++)
{
fprintf(f, "%.10lf %.10lf\\\\\n", X[i][j], Y[i][j]);
}
fprintf(f, "};\n");
}
fprintf(f, "\\end{axis}\n");
fprintf(f, "\\end{tikzpicture}\n");
fclose(f);
}
int main()
{
// Create a new Gaussian process...
// use zero-mean, squared-exponential covariance (hyperparam l = 0.5), no noise.
auto m = [](double) { return 0; };
auto k = [](double x, double y) { return exp(-(x - y) * (x - y) / (2.0 * 0.5 * 0.5)); };
GP gp(m, k, 0.0);
// points to be used to plot lines
vector<double> xs;
for (double x=-5.0;x<=5.0;x+=0.02) xs.push_back(x);
// Sample the prior
vector<double> mu = gp.get_means(xs);
vector<vector<double>> Sigma = gp.get_covar(xs);
/*for (uint i=0;i<Sigma.size();i++)
{
for (uint j=0;j<Sigma.size();j++)
{
printf("%.2lf ", Sigma[i][j]);
}
printf("\n");
}*/
MultiGaussian N(gen, mu, Sigma);
vector<vector<double>> Xs(n_samp, xs);
vector<vector<double>> Ys(n_samp);
for (int i=0;i<n_samp;i++)
{
Ys[i] = N.sample();
}
to_tikz(Xs, Ys, "test.tex");
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessiblePresentationShape.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:27: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
*
************************************************************************/
#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX
#include "AccessiblePresentationShape.hxx"
#endif
#include "SdShapeTypes.hxx"
#include <svx/DescriptionGenerator.hxx>
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
namespace accessibility {
//===== internal ============================================================
AccessiblePresentationShape::AccessiblePresentationShape (
const AccessibleShapeInfo& rShapeInfo,
const AccessibleShapeTreeInfo& rShapeTreeInfo)
: AccessibleShape (rShapeInfo, rShapeTreeInfo)
{
}
AccessiblePresentationShape::~AccessiblePresentationShape (void)
{
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
AccessiblePresentationShape::getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessiblePresentationShape"));
}
/// Set this object's name if is different to the current name.
::rtl::OUString
AccessiblePresentationShape::CreateAccessibleBaseName (void)
throw (::com::sun::star::uno::RuntimeException)
{
::rtl::OUString sName;
ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
switch (nShapeType)
{
case PRESENTATION_TITLE:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressTitle"));
break;
case PRESENTATION_OUTLINER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressOutliner"));
break;
case PRESENTATION_SUBTITLE:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressSubtitle"));
break;
case PRESENTATION_PAGE:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPage"));
break;
case PRESENTATION_NOTES:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressNotes"));
break;
case PRESENTATION_HANDOUT:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHandout"));
break;
case PRESENTATION_HEADER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHeader"));
break;
case PRESENTATION_FOOTER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressFooter"));
break;
case PRESENTATION_DATETIME:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressDateAndTime"));
break;
case PRESENTATION_PAGENUMBER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPageNumber"));
break;
default:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleImpressShape"));
uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
if (xDescriptor.is())
sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": "))
+ xDescriptor->getShapeType();
}
return sName;
}
::rtl::OUString
AccessiblePresentationShape::CreateAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
// return createAccessibleName ();
DescriptionGenerator aDG (mxShape);
ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
switch (nShapeType)
{
case PRESENTATION_TITLE:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationTitleShape"));
break;
case PRESENTATION_OUTLINER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationOutlinerShape"));
break;
case PRESENTATION_SUBTITLE:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationSubtitleShape"));
break;
case PRESENTATION_PAGE:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageShape"));
break;
case PRESENTATION_NOTES:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationNotesShape"));
break;
case PRESENTATION_HANDOUT:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHandoutShape"));
break;
case PRESENTATION_HEADER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHeaderShape"));
break;
case PRESENTATION_FOOTER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationFooterShape"));
break;
case PRESENTATION_DATETIME:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationDateAndTimeShape"));
break;
case PRESENTATION_PAGENUMBER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageNumberShape"));
break;
default:
aDG.Initialize (::rtl::OUString::createFromAscii ("Unknown accessible presentation shape"));
uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
if (xDescriptor.is())
{
aDG.AppendString (::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("service name=")));
aDG.AppendString (xDescriptor->getShapeType());
}
}
return aDG();
}
} // end of namespace accessibility
<commit_msg>INTEGRATION: CWS pchfix02 (1.16.282); FILE MERGED 2006/09/01 17:36:50 kaib 1.16.282.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessiblePresentationShape.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:25:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX
#include "AccessiblePresentationShape.hxx"
#endif
#include "SdShapeTypes.hxx"
#include <svx/DescriptionGenerator.hxx>
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
namespace accessibility {
//===== internal ============================================================
AccessiblePresentationShape::AccessiblePresentationShape (
const AccessibleShapeInfo& rShapeInfo,
const AccessibleShapeTreeInfo& rShapeTreeInfo)
: AccessibleShape (rShapeInfo, rShapeTreeInfo)
{
}
AccessiblePresentationShape::~AccessiblePresentationShape (void)
{
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
AccessiblePresentationShape::getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessiblePresentationShape"));
}
/// Set this object's name if is different to the current name.
::rtl::OUString
AccessiblePresentationShape::CreateAccessibleBaseName (void)
throw (::com::sun::star::uno::RuntimeException)
{
::rtl::OUString sName;
ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
switch (nShapeType)
{
case PRESENTATION_TITLE:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressTitle"));
break;
case PRESENTATION_OUTLINER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressOutliner"));
break;
case PRESENTATION_SUBTITLE:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressSubtitle"));
break;
case PRESENTATION_PAGE:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPage"));
break;
case PRESENTATION_NOTES:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressNotes"));
break;
case PRESENTATION_HANDOUT:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHandout"));
break;
case PRESENTATION_HEADER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHeader"));
break;
case PRESENTATION_FOOTER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressFooter"));
break;
case PRESENTATION_DATETIME:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressDateAndTime"));
break;
case PRESENTATION_PAGENUMBER:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPageNumber"));
break;
default:
sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleImpressShape"));
uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
if (xDescriptor.is())
sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": "))
+ xDescriptor->getShapeType();
}
return sName;
}
::rtl::OUString
AccessiblePresentationShape::CreateAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
// return createAccessibleName ();
DescriptionGenerator aDG (mxShape);
ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
switch (nShapeType)
{
case PRESENTATION_TITLE:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationTitleShape"));
break;
case PRESENTATION_OUTLINER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationOutlinerShape"));
break;
case PRESENTATION_SUBTITLE:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationSubtitleShape"));
break;
case PRESENTATION_PAGE:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageShape"));
break;
case PRESENTATION_NOTES:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationNotesShape"));
break;
case PRESENTATION_HANDOUT:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHandoutShape"));
break;
case PRESENTATION_HEADER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHeaderShape"));
break;
case PRESENTATION_FOOTER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationFooterShape"));
break;
case PRESENTATION_DATETIME:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationDateAndTimeShape"));
break;
case PRESENTATION_PAGENUMBER:
aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageNumberShape"));
break;
default:
aDG.Initialize (::rtl::OUString::createFromAscii ("Unknown accessible presentation shape"));
uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
if (xDescriptor.is())
{
aDG.AppendString (::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("service name=")));
aDG.AppendString (xDescriptor->getShapeType());
}
}
return aDG();
}
} // end of namespace accessibility
<|endoftext|> |
<commit_before>
#include <iostream>
//#include <boost/bind.hpp>
//
//#include <boost/test/included/unit_test.hpp>
#include <FFLLAPI.h>
#include <DefuzzVarObj.h>
#include <FFLLBase.h>
#include <FuzzyModelBase.h>
#include <FuzzyVariableBase.h>
#include <FuzzyOutVariable.h>
#include <RuleArray.h>
#include <MemberFuncTrap.h>
#include <MemberFuncTri.h>
#include <MemberFuncSCurve.h>
#include <MemberFuncSingle.h>
#include <FuzzySetBase.h>
int main( int argc, char* argv[] )
{
FuzzyModelBase* testModel = new FuzzyModelBase();// = new FuzzyModelBase();
testModel->init(); //create model with empty rule array
//const Char* c = model->get_model_name();
testModel->FuzzyModelBase::set_defuzz_method(0); // set DEFUZZ_COG method
testModel->FuzzyModelBase::set_inference_method(0);
testModel->FuzzyModelBase::set_composition_method(0);
//FuzzyModelBase* pmodel = &model;
std::wstring name1(L"inputVariable1");
const wchar_t* szInputVariable1 = name1.c_str();
std::wstring name2(L"outVariable1");
const wchar_t* szOutVariable1 = name2.c_str();
std::wstring name3(L"inputVariable2");
const wchar_t* szInputVariable2 = name3.c_str();
std::wstring nameSet(L"set1Var1");
wchar_t* wset_name1 = convert_to_wide_char("set1Var1");
FuzzyVariableBase* inputVar1 = new FuzzyVariableBase(testModel);// create new inputVar
int i = inputVar1->init(szInputVariable1, 34.5, 45.3, true);//left x value, right x value? // if no name is passed in name it "Variable 0"
inputVar1->add_set(inputVar1->new_set(wset_name1,25,inputVar1,0,30,2));
inputVar1->set_x_array_count(100);
// inputVar1->set_right_x(25);
// inputVar1->set_ramp(1,0,0);
//inputVar1->set_dom_array_count(20);
// inputVar1->set_left_x(0);
// ASSERT(i == -1);
FuzzyVariableBase* inputVar2 = new FuzzyVariableBase(testModel);
int k = inputVar2->init(szInputVariable2, 34.5, 45.3, true);
// ASSERT(k == -1);
FuzzyOutVariable* outVariable1 = new FuzzyOutVariable(testModel); // create new outVar
int j = outVariable1->init(szOutVariable1, 23.4, 56.5, true); //return 0 if success
// ASSERT(j == -1);
testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
testModel->add_output_variable(szOutVariable1, 23.4, 56.5, true);
// set atributes for InputVariable1
inputVar1->set_dom_array_count(100); // discrete y
inputVar1->set_x_array_count(100); //discrete x
inputVar1->set_index(0);
// FuzzySets for InputVariable1
FuzzySetBase* set1Var1 = new FuzzySetBase(inputVar1);
// Set attributes for set1Var1
FuzzySetBase* set2Var1 = new FuzzySetBase(inputVar1);
FuzzySetBase* set3Var1 = new FuzzySetBase(inputVar1);
// FuzzySets for InputVariable2
FuzzySetBase* set1Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set2Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set3Var2 = new FuzzySetBase(inputVar2);
// Membership functions for sets in InputVariable1
MemberFuncTrap* functionTrap1 = new MemberFuncTrap(set1Var1);
functionTrap1->init();
functionTrap1->set_ramp(1,0); // RAMP_NA
functionTrap1->init();
functionTrap1->set_node(0,25,0);
functionTrap1->set_node(1,27,1); // 4 point for trap
functionTrap1->set_node(2,30,1);
functionTrap1->set_node(3,32,0);
wchar_t* wset_name = convert_to_wide_char("Set1Var1");
// FuzzySetBase* set = new_set(wset_name, 0, inputVar1, 3, 0, 2);
functionTrap1->get_start_x();
functionTrap1->get_end_x();
functionTrap1->get_node_x(2);
functionTrap1->get_node_y(2);
functionTrap1->get_ramp();
functionTrap1->get_center_x();
// functionTrap1->get_dom();
// functionTrap1->get_value();
DOMType* arrayDegreeOfMembership = new DOMType[];
// arrayDegreeOfMembership = (1,2,4,5,6,7,8,9,8,7,6,5,4,3,2,1);
//FuzzyVariableBase *var = testModel->get_var(OUTPUT_IDX);
// this code used for automaic create model from api
}<commit_msg> - тест<commit_after>
#include <iostream>
//#include <boost/bind.hpp>
//
//#include <boost/test/included/unit_test.hpp>
#include <FFLLAPI.h>
#include <DefuzzVarObj.h>
#include <FFLLBase.h>
#include <FuzzyModelBase.h>
#include <FuzzyVariableBase.h>
#include <FuzzyOutVariable.h>
#include <RuleArray.h>
#include <MemberFuncTrap.h>
#include <MemberFuncTri.h>
#include <MemberFuncSCurve.h>
#include <MemberFuncSingle.h>
#include <FuzzySetBase.h>
int main( int argc, char* argv[] )
{
FuzzyModelBase* testModel = new FuzzyModelBase();// = new FuzzyModelBase();
// testModel->init(); //create model with empty rule array
RuleArray* ruleArray = new RuleArray(testModel);
ruleArray->alloc(10); // number of rules;
// testModel->get_num_of_rules();
//const Char* c = model->get_model_name();
testModel->FuzzyModelBase::set_defuzz_method(0); // set DEFUZZ_COG method
testModel->FuzzyModelBase::set_inference_method(0);
testModel->FuzzyModelBase::set_composition_method(0);
//FuzzyModelBase* pmodel = &model;
std::wstring name1(L"inputVariable1");
const wchar_t* szInputVariable1 = name1.c_str();
std::wstring name2(L"outVariable1");
const wchar_t* szOutVariable1 = name2.c_str();
std::wstring name3(L"inputVariable2");
const wchar_t* szInputVariable2 = name3.c_str();
std::wstring nameSet(L"set1Var1");
wchar_t* wset_name1 = convert_to_wide_char("set1Var1");
FuzzyVariableBase* inputVar1 = new FuzzyVariableBase(testModel);// create new inputVar
int i = inputVar1->init(szInputVariable1, 34.5, 45.3, true);//left x value, right x value? // if no name is passed in name it "Variable 0"
inputVar1->add_set(inputVar1->new_set(wset_name1,25,inputVar1,0,30,2));
inputVar1->set_x_array_count(100);
// inputVar1->set_right_x(25);
// inputVar1->set_ramp(1,0,0);
//inputVar1->set_dom_array_count(20);
// inputVar1->set_left_x(0);
// ASSERT(i == -1);
FuzzyVariableBase* inputVar2 = new FuzzyVariableBase(testModel);
int k = inputVar2->init(szInputVariable2, 40, 55, true);
// ASSERT(k == -1);
FuzzyOutVariable* outVariable1 = new FuzzyOutVariable(testModel); // create new outVar
int j = outVariable1->init(szOutVariable1, 23.4, 56.5, true); //return 0 if success
// ASSERT(j == -1);
testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
testModel->add_input_variable(szInputVariable2, 40, 55, true);
testModel->add_output_variable(szOutVariable1, 23.4, 56.5, true);
// set atributes for InputVariable1
inputVar1->set_dom_array_count(100); // discrete y
inputVar1->set_x_array_count(100); //discrete x
inputVar1->set_index(0);
// FuzzySets for InputVariable1
FuzzySetBase* set1Var1 = new FuzzySetBase(inputVar1);
// Set attributes for set1Var1
FuzzySetBase* set2Var1 = new FuzzySetBase(inputVar1);
FuzzySetBase* set3Var1 = new FuzzySetBase(inputVar1);
// FuzzySets for InputVariable2
FuzzySetBase* set1Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set2Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set3Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* outSet1 = new FuzzySetBase(outVariable1);
FuzzySetBase* outSet2 = new FuzzySetBase(outVariable1);
FuzzySetBase* outSet3 = new FuzzySetBase(outVariable1);
outSet1->set_index(0);
outSet2->set_index(1);
outSet2->set_index(2);
// Membership functions for sets in InputVariable1
MemberFuncTrap* functionTrap1 = new MemberFuncTrap(set1Var1);
functionTrap1->init();
functionTrap1->set_ramp(1,0); // RAMP_NA
functionTrap1->init();
functionTrap1->set_node(0,25,0);
functionTrap1->set_node(1,27,1); // 4 point for trap
functionTrap1->set_node(2,30,1);
functionTrap1->set_node(3,32,0);
wchar_t* wset_name = convert_to_wide_char("Set1Var1");
// FuzzySetBase* set = new_set(wset_name, 0, inputVar1, 3, 0, 2);
functionTrap1->get_start_x();
functionTrap1->get_end_x();
functionTrap1->get_node_x(2);
functionTrap1->get_node_y(2);
functionTrap1->get_ramp();
functionTrap1->get_center_x();
// functionTrap1->get_dom();
// functionTrap1->get_value();
int o = testModel->get_input_var_count();
//if inputVar1 term1 and inputVar2 term1 then outputVar term1
//if inputVar1 term1 and inputVar2 term2 then outputVar term2
//if inputVar1 term1 and inputVar2 term3 then outputVar term3
//if inputVar1 term2 and inputVar2 term1 then outputVar term1
//if inputVar1 term2 and inputVar2 term2 then outputVar term2
//if inputVar1 term2 and inputVar2 term3 then outputVar term3
//if inputVar1 term3 and inputVar2 term1 then outputVar term1
//if inputVar1 term3 and inputVar2 term2 then outputVar term2
//if inputVar1 term3 and inputVar2 term3 then outputVar term3
int oo = testModel->get_input_var_count()+1;
std::string* rule_components = new std::string[oo + 1]; // +1 for output var
testModel->add_rule(0, outSet1->get_index());
testModel->add_rule(1, outSet2->get_index());
testModel->add_rule(2, outSet3->get_index());
testModel->add_rule(3, outSet1->get_index());
testModel->add_rule(4, outSet2->get_index());
testModel->add_rule(5, outSet3->get_index());
testModel->add_rule(6, outSet1->get_index());
testModel->add_rule(7, outSet2->get_index());
testModel->add_rule(8, outSet3->get_index());
DOMType* arrayDegreeOfMembership = new DOMType[];
// arrayDegreeOfMembership = (1,2,4,5,6,7,8,9,8,7,6,5,4,3,2,1);
//FuzzyVariableBase *var = testModel->get_var(OUTPUT_IDX);
// this code used for automaic create model from api
}<|endoftext|> |
<commit_before>//
// ByteOrder.cpp
//
// Copyright (c) 2001 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//
#include <stdio.h>
#include <stdlib.h> /* For abort() */
#include "ByteOrder.h"
static int GetDataTypeSize( DataType type )
{
int tsize;
switch ( type )
{
case DT_SHORT : tsize = sizeof(short) ; break;
case DT_INT : tsize = sizeof(int) ; break;
case DT_LONG : tsize = sizeof(long) ; break;
case DT_FLOAT : tsize = sizeof(float) ; break;
case DT_DOUBLE : tsize = sizeof(double); break;
/* FIXME: What is the appropriate VTP code bug reporting method? */
default: abort();
}
return tsize;
}
/**
* If the byte orders differ, swap bytes; if not, don't; return the result.
* This is the memory buffer version of the SwapBytes() macros, and as such
* supports an array of data. It also parametizes the element type to avoid
* function explosion.
* \param items the data items to order
* \param type the type of each item in the array
* \param nitems the number if items in the array
* \param data_order the byte order of the data
* \param desired_order the desired byte ordering
*
*/
void SwapMemBytes( void *items, DataType type, size_t nitems,
ByteOrder data_order, ByteOrder desired_order )
{
size_t tsize;
char *base = (char *) items,
*p;
if ( data_order == BO_MACHINE ) data_order = NativeByteOrder();
if ( desired_order == BO_MACHINE ) desired_order = NativeByteOrder();
if ( data_order == desired_order )
return;
tsize = GetDataTypeSize( type );
switch ( type )
{
case DT_SHORT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(short *)p = SwapShort( *(short *)p );
break;
case DT_INT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(int *)p = SwapInt( *(int *)p );
break;
case DT_LONG :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(long *)p = SwapLong( *(long *)p );
break;
case DT_FLOAT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(float *)p = SwapFloat( *(float *)p );
break;
case DT_DOUBLE :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(double *)p = SwapDouble( *(double *)p );
break;
/* FIXME: What is the appropriate VTP code bug reporting method? */
default: abort();
}
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (num items read, or negative for error)
*
*/
size_t FRead( void *ptr, DataType type, size_t nitems, FILE *stream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
size_t ret = fread( ptr, tsize, nitems, stream );
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret, file_order, desired_order );
return ret;
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read. File access is done via zlib's gzip IO routines to
* be compatible with gzopen(), etc.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (num items read, or negative for error)
*
*/
size_t GZFRead( void *ptr, DataType type, size_t nitems, gzFile gzstream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
size_t ret = gzread(gzstream, ptr, tsize * nitems);
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret, file_order, desired_order );
return ret;
}
<commit_msg>fixed length bug which caused crash on non-Intel machines<commit_after>//
// ByteOrder.cpp
//
// Copyright (c) 2001-2004 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//
#include "ByteOrder.h"
static int GetDataTypeSize( DataType type )
{
int tsize;
switch ( type )
{
case DT_SHORT: tsize = sizeof(short); break;
case DT_INT: tsize = sizeof(int); break;
case DT_LONG: tsize = sizeof(long); break;
case DT_FLOAT: tsize = sizeof(float); break;
case DT_DOUBLE: tsize = sizeof(double); break;
default: assert(false);
}
return tsize;
}
/**
* If the byte orders differ, swap bytes; if not, don't; return the result.
* This is the memory buffer version of the SwapBytes() macros, and as such
* supports an array of data. It also parametizes the element type to avoid
* function explosion.
* \param items the data items to order
* \param type the type of each item in the array
* \param nitems the number if items in the array
* \param data_order the byte order of the data
* \param desired_order the desired byte ordering
*
*/
void SwapMemBytes( void *items, DataType type, size_t nitems,
ByteOrder data_order, ByteOrder desired_order )
{
size_t tsize;
char *base = (char *) items,
*p;
if ( data_order == BO_MACHINE ) data_order = NativeByteOrder();
if ( desired_order == BO_MACHINE ) desired_order = NativeByteOrder();
if ( data_order == desired_order )
return;
tsize = GetDataTypeSize( type );
switch ( type )
{
case DT_SHORT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(short *)p = SwapShort( *(short *)p );
break;
case DT_INT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(int *)p = SwapInt( *(int *)p );
break;
case DT_LONG :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(long *)p = SwapLong( *(long *)p );
break;
case DT_FLOAT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(float *)p = SwapFloat( *(float *)p );
break;
case DT_DOUBLE :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(double *)p = SwapDouble( *(double *)p );
break;
default:
assert(false);
}
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (num items read, or negative for error)
*
*/
size_t FRead( void *ptr, DataType type, size_t nitems, FILE *stream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
size_t ret = fread( ptr, tsize, nitems, stream );
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret/tsize, file_order, desired_order );
return ret;
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read. File access is done via zlib's gzip IO routines to
* be compatible with gzopen(), etc.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (num items read, or negative for error)
*
*/
size_t GZFRead( void *ptr, DataType type, size_t nitems, gzFile gzstream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
size_t ret = gzread(gzstream, ptr, tsize * nitems);
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret/tsize, file_order, desired_order );
return ret;
}
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/searchcore/proton/matching/fakesearchcontext.h>
#include <vespa/searchcorespi/index/warmupindexcollection.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/testclock.h>
#include <vespa/log/log.h>
LOG_SETUP("indexcollection_test");
using namespace proton;
using namespace searchcorespi;
using search::FixedSourceSelector;
using search::index::FieldLengthInfo;
using search::queryeval::FakeSearchable;
using search::queryeval::ISourceSelector;
using searchcorespi::index::WarmupConfig;
class MockIndexSearchable : public FakeIndexSearchable {
private:
FieldLengthInfo _field_length_info;
public:
MockIndexSearchable()
: _field_length_info()
{}
explicit MockIndexSearchable(const FieldLengthInfo& field_length_info)
: _field_length_info(field_length_info)
{}
FieldLengthInfo get_field_length_info(const vespalib::string& field_name) const override {
(void) field_name;
return _field_length_info;
}
};
class IndexCollectionTest : public ::testing::Test,
public IWarmupDone
{
public:
std::shared_ptr<ISourceSelector> _selector;
std::shared_ptr<IndexSearchable> _source1;
std::shared_ptr<IndexSearchable> _source2;
std::shared_ptr<IndexSearchable> _fusion_source;
vespalib::ThreadStackExecutor _executor;
vespalib::TestClock _clock;
std::shared_ptr<IndexSearchable> _warmup;
void expect_searchable_can_be_appended(IndexCollection::UP collection) {
const uint32_t id = 42;
collection->append(id, _source1);
EXPECT_EQ(1u, collection->getSourceCount());
EXPECT_EQ(id, collection->getSourceId(0));
}
void expect_searchable_can_be_replaced(IndexCollection::UP collection) {
const uint32_t id = 42;
collection->append(id, _source1);
EXPECT_EQ(1u, collection->getSourceCount());
EXPECT_EQ(id, collection->getSourceId(0));
EXPECT_EQ(_source1.get(), &collection->getSearchable(0));
collection->replace(id, _source2);
EXPECT_EQ(1u, collection->getSourceCount());
EXPECT_EQ(id, collection->getSourceId(0));
EXPECT_EQ(_source2.get(), &collection->getSearchable(0));
}
IndexCollection::UP make_unique_collection() const {
return std::make_unique<IndexCollection>(_selector);
}
IndexCollection::SP make_shared_collection() const {
return std::make_shared<IndexCollection>(_selector);
}
IndexCollection::UP create_warmup(const IndexCollection::SP& prev, const IndexCollection::SP& next) {
return std::make_unique<WarmupIndexCollection>(WarmupConfig(1s, false), prev, next, *_warmup, _executor, _clock.clock(), *this);
}
void warmupDone(std::shared_ptr<WarmupIndexCollection> current) override {
(void) current;
}
IndexCollectionTest()
: _selector(std::make_shared<FixedSourceSelector>(0, "fs1")),
_source1(std::make_shared<MockIndexSearchable>(FieldLengthInfo(3, 5))),
_source2(std::make_shared<MockIndexSearchable>(FieldLengthInfo(7, 11))),
_fusion_source(std::make_shared<FakeIndexSearchable>()),
_executor(1, 128_Ki),
_warmup(std::make_shared<FakeIndexSearchable>())
{}
~IndexCollectionTest() = default;
};
TEST_F(IndexCollectionTest, searchable_can_be_appended_to_normal_collection)
{
expect_searchable_can_be_appended(make_unique_collection());
}
TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_normal_collection)
{
expect_searchable_can_be_replaced(make_unique_collection());
}
TEST_F(IndexCollectionTest, searchable_can_be_appended_to_warmup_collection)
{
auto prev = make_shared_collection();
auto next = make_shared_collection();
expect_searchable_can_be_appended(create_warmup(prev, next));
EXPECT_EQ(0u, prev->getSourceCount());
EXPECT_EQ(1u, next->getSourceCount());
}
TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_warmup_collection)
{
auto prev = make_shared_collection();
auto next = make_shared_collection();
expect_searchable_can_be_replaced(create_warmup(prev, next));
EXPECT_EQ(0u, prev->getSourceCount());
EXPECT_EQ(1u, next->getSourceCount());
}
TEST_F(IndexCollectionTest, replace_and_renumber_updates_collection_after_fusion)
{
IndexCollection fsc(_selector);
fsc.append(0, _source1);
fsc.append(1, _source1);
fsc.append(2, _source1);
fsc.append(3, _source2);
EXPECT_EQ(4u, fsc.getSourceCount());
const uint32_t id_diff = 2;
auto new_fsc = IndexCollection::replaceAndRenumber(_selector, fsc, id_diff, _fusion_source);
EXPECT_EQ(2u, new_fsc->getSourceCount());
EXPECT_EQ(0u, new_fsc->getSourceId(0));
EXPECT_EQ(_fusion_source.get(), &new_fsc->getSearchable(0));
EXPECT_EQ(1u, new_fsc->getSourceId(1));
EXPECT_EQ(_source2.get(), &new_fsc->getSearchable(1));
}
TEST_F(IndexCollectionTest, returns_field_length_info_for_last_added_searchable)
{
auto collection = make_unique_collection();
collection->append(3, _source1);
collection->append(4, _source2);
EXPECT_DOUBLE_EQ(7, collection->get_field_length_info("foo").get_average_field_length());
EXPECT_EQ(11, collection->get_field_length_info("foo").get_num_samples());
}
TEST_F(IndexCollectionTest, returns_empty_field_length_info_when_no_searchables_exists)
{
auto collection = make_unique_collection();
EXPECT_DOUBLE_EQ(0, collection->get_field_length_info("foo").get_average_field_length());
EXPECT_EQ(0, collection->get_field_length_info("foo").get_num_samples());
}
GTEST_MAIN_RUN_ALL_TESTS()
<commit_msg>Ensure that we can create blueprint for warmup collections too.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/searchcore/proton/matching/fakesearchcontext.h>
#include <vespa/searchlib/queryeval/fake_requestcontext.h>
#include <vespa/searchlib/query/tree/simplequery.h>
#include <vespa/searchcorespi/index/warmupindexcollection.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/testclock.h>
#include <vespa/log/log.h>
LOG_SETUP("indexcollection_test");
using namespace proton;
using namespace searchcorespi;
using search::FixedSourceSelector;
using search::index::FieldLengthInfo;
using search::queryeval::FakeSearchable;
using search::queryeval::ISourceSelector;
using search::queryeval::FakeRequestContext;
using search::queryeval::FieldSpecList;
using search::queryeval::FieldSpec;
using searchcorespi::index::WarmupConfig;
class MockIndexSearchable : public FakeIndexSearchable {
private:
FieldLengthInfo _field_length_info;
public:
MockIndexSearchable()
: _field_length_info()
{}
explicit MockIndexSearchable(const FieldLengthInfo& field_length_info)
: _field_length_info(field_length_info)
{}
FieldLengthInfo get_field_length_info(const vespalib::string& field_name) const override {
(void) field_name;
return _field_length_info;
}
};
class IndexCollectionTest : public ::testing::Test,
public IWarmupDone
{
public:
std::shared_ptr<ISourceSelector> _selector;
std::shared_ptr<IndexSearchable> _source1;
std::shared_ptr<IndexSearchable> _source2;
std::shared_ptr<IndexSearchable> _fusion_source;
vespalib::ThreadStackExecutor _executor;
vespalib::TestClock _clock;
std::shared_ptr<IndexSearchable> _warmup;
void expect_searchable_can_be_appended(ISearchableIndexCollection & collection) {
const uint32_t id = 42;
collection.append(id, _source1);
EXPECT_EQ(1u, collection.getSourceCount());
EXPECT_EQ(id, collection.getSourceId(0));
}
void expect_searchable_can_be_replaced(ISearchableIndexCollection & collection) {
const uint32_t id = 42;
collection.append(id, _source1);
EXPECT_EQ(1u, collection.getSourceCount());
EXPECT_EQ(id, collection.getSourceId(0));
EXPECT_EQ(_source1.get(), &collection.getSearchable(0));
collection.replace(id, _source2);
EXPECT_EQ(1u, collection.getSourceCount());
EXPECT_EQ(id, collection.getSourceId(0));
EXPECT_EQ(_source2.get(), &collection.getSearchable(0));
}
std::unique_ptr<IndexCollection>
make_unique_collection() const {
return std::make_unique<IndexCollection>(_selector);
}
std::shared_ptr<IndexCollection>
make_shared_collection() const {
return std::make_shared<IndexCollection>(_selector);
}
std::shared_ptr<WarmupIndexCollection>
create_warmup(const IndexCollection::SP& prev, const IndexCollection::SP& next) {
return std::make_shared<WarmupIndexCollection>(WarmupConfig(1s, false), prev, next, *_warmup, _executor, _clock.clock(), *this);
}
void warmupDone(std::shared_ptr<WarmupIndexCollection> current) override {
(void) current;
}
IndexCollectionTest()
: _selector(std::make_shared<FixedSourceSelector>(0, "fs1")),
_source1(std::make_shared<MockIndexSearchable>(FieldLengthInfo(3, 5))),
_source2(std::make_shared<MockIndexSearchable>(FieldLengthInfo(7, 11))),
_fusion_source(std::make_shared<FakeIndexSearchable>()),
_executor(1, 128_Ki),
_warmup(std::make_shared<FakeIndexSearchable>())
{}
~IndexCollectionTest() = default;
};
TEST_F(IndexCollectionTest, searchable_can_be_appended_to_normal_collection)
{
expect_searchable_can_be_appended(*make_unique_collection());
}
TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_normal_collection)
{
expect_searchable_can_be_replaced(*make_unique_collection());
}
TEST_F(IndexCollectionTest, searchable_can_be_appended_to_warmup_collection)
{
auto prev = make_shared_collection();
auto next = make_shared_collection();
expect_searchable_can_be_appended(*create_warmup(prev, next));
EXPECT_EQ(0u, prev->getSourceCount());
EXPECT_EQ(1u, next->getSourceCount());
}
TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_warmup_collection)
{
auto prev = make_shared_collection();
auto next = make_shared_collection();
expect_searchable_can_be_replaced(*create_warmup(prev, next));
EXPECT_EQ(0u, prev->getSourceCount());
EXPECT_EQ(1u, next->getSourceCount());
}
TEST_F(IndexCollectionTest, replace_and_renumber_updates_collection_after_fusion)
{
IndexCollection fsc(_selector);
fsc.append(0, _source1);
fsc.append(1, _source1);
fsc.append(2, _source1);
fsc.append(3, _source2);
EXPECT_EQ(4u, fsc.getSourceCount());
const uint32_t id_diff = 2;
auto new_fsc = IndexCollection::replaceAndRenumber(_selector, fsc, id_diff, _fusion_source);
EXPECT_EQ(2u, new_fsc->getSourceCount());
EXPECT_EQ(0u, new_fsc->getSourceId(0));
EXPECT_EQ(_fusion_source.get(), &new_fsc->getSearchable(0));
EXPECT_EQ(1u, new_fsc->getSourceId(1));
EXPECT_EQ(_source2.get(), &new_fsc->getSearchable(1));
}
TEST_F(IndexCollectionTest, returns_field_length_info_for_last_added_searchable)
{
auto collection = make_unique_collection();
collection->append(3, _source1);
collection->append(4, _source2);
EXPECT_DOUBLE_EQ(7, collection->get_field_length_info("foo").get_average_field_length());
EXPECT_EQ(11, collection->get_field_length_info("foo").get_num_samples());
}
TEST_F(IndexCollectionTest, returns_empty_field_length_info_when_no_searchables_exists)
{
auto collection = make_unique_collection();
EXPECT_DOUBLE_EQ(0, collection->get_field_length_info("foo").get_average_field_length());
EXPECT_EQ(0, collection->get_field_length_info("foo").get_num_samples());
}
TEST_F(IndexCollectionTest, warmup_can_create_blueprint)
{
auto prev = make_shared_collection();
auto next = make_shared_collection();
auto indexcollection = create_warmup(prev, next);
const uint32_t id = 42;
indexcollection->append(id, _source1);
FakeRequestContext requestContext;
FieldSpecList fields;
fields.add(FieldSpec("dummy", 1, search::fef::IllegalHandle));
search::query::SimpleStringTerm term("what", "dummy", 1, search::query::Weight(100));
auto blueprint = indexcollection->createBlueprint(requestContext, fields, term);
EXPECT_TRUE(blueprint);
}
GTEST_MAIN_RUN_ALL_TESTS()
<|endoftext|> |
<commit_before>/*
* DbgTracePort.cpp
*
* Created on: 16.03.2015
* Author: niklausd
*/
#include "DbgTraceContext.h"
#include "DbgTraceOut.h"
#include "DbgTracePort.h"
#include "DbgCliCommand.h"
#ifdef ARDUINO
#include <Arduino.h>
#else
#include <time.h>
#endif
#include <stdio.h>
#include <string.h>
//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeOut
//-----------------------------------------------------------------------------
class DbgCli_Command_ChangeOut : public DbgCli_Command
{
private:
DbgTrace_Port* m_tracePort;
public:
DbgCli_Command_ChangeOut(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
: DbgCli_Command(parentNode, nodeName, helpText)
, m_tracePort(port)
{ }
void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
{
const char* cmd = args[idxToFirstArgToHandle];
DbgTrace_Context* context = DbgTrace_Context::getContext();
if(0 == strncmp(cmd, "get", 4))
{
if((0 != m_tracePort) && (0 != m_tracePort->getOut()))
{
char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
snprintf(buf, sizeof(buf), "Out: \"%s\"" , m_tracePort->getOut()->getName());
#ifdef ARDUINO
Serial.print(buf);
#else
println(buf);
#endif
}
}
else if(0 == strncmp(cmd, "set", 4))
{
if((0 != m_tracePort) && (0 != m_tracePort->getOut()) && (0 != context))
{
DbgTrace_Out* newOut = context->getTraceOut(args[idxToFirstArgToHandle+1]);
char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
if(0 != newOut)
{
m_tracePort->setOut(newOut);
snprintf(buf, sizeof(buf),"OK! Out: \"%s\"" , m_tracePort->getOut()->getName());
}
else
{
snprintf(buf, sizeof(buf), "Fail! Out: \"%s\"" , m_tracePort->getOut()->getName());
}
#ifdef ARDUINO
Serial.print(buf);
#else
println(buf);
#endif
}
}
else if((0 == strncmp(cmd, "list", 5)) && (0 != context))
{
DbgTrace_Out* tmpOut = context->getFirstTraceOut();
if((0 != m_tracePort) && (0 != m_tracePort->getOut()))
{
char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
while(0 != tmpOut)
{
if((0 != m_tracePort->getOut()) &&
(0 == strncmp(tmpOut->getName(), m_tracePort->getOut()->getName(), DbgTrace_Out::s_cMaxOutNameLength)))
{
// mark currently used out
snprintf(buf, sizeof(buf),">%s" , tmpOut->getName());
}
else
{
snprintf(buf, sizeof(buf), " %s" , tmpOut->getName());
}
#ifdef ARDUINO
Serial.println(buf);
#else
println(buf);
#endif
tmpOut = tmpOut->getNextOut();
}
}
}
else
{
#ifdef ARDUINO
Serial.print(F("Unknown command: "));
Serial.println(cmd);
Serial.println(this->getHelpText());
#else
println("Unknown command: %s", cmd);
printf(this->getHelpText());
#endif
}
}
private:
DbgCli_Command_ChangeOut();
};
//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeLevel
//-----------------------------------------------------------------------------
class DbgCli_Command_ChangeLevel : public DbgCli_Command
{
private:
DbgTrace_Port* m_tracePort;
public:
DbgCli_Command_ChangeLevel(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
: DbgCli_Command(parentNode, nodeName, helpText)
, m_tracePort(port)
{ }
void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
{
const char* cmd = args[idxToFirstArgToHandle];
if(0 == strncmp(cmd, "get", 4))
{
if(0 != m_tracePort)
{
char buf[20 + DbgTrace_Level::s_cMaxLevelLength];
snprintf(buf, sizeof(buf), "Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
#ifdef ARDUINO
Serial.println(buf);
#else
printfln(buf);
#endif
}
}
else if(0 == strncmp(cmd, "set", 4))
{
if(0 != m_tracePort)
{
char buf[20 + DbgTrace_Level::s_cMaxLevelLength];
DbgTrace_Level::Level newLevel = DbgTrace_Level::stringToLevel(args[idxToFirstArgToHandle+1]);
if(DbgTrace_Level::none != newLevel)
{
m_tracePort->setLevel(newLevel);
snprintf(buf, sizeof(buf),"OK! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
}
else
{
snprintf(buf, sizeof(buf), "Fail! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
}
#ifdef ARDUINO
Serial.print(buf);
#else
printfln(buf);
#endif
}
}
else if(0 == strncmp(cmd, "list", 5))
{
if(0 != m_tracePort)
{
unsigned int level = 0;
char buf[4 + DbgTrace_Level::s_cMaxLevelLength];
while(DbgTrace_Level::LEVEL_ENUM_LIMIT != level)
{
if(level == m_tracePort->getLevel())
{
// mark currently used out
snprintf(buf, sizeof(buf),">%s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
}
else
{
snprintf(buf, sizeof(buf)," %s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
}
#ifdef ARDUINO
Serial.println(buf);
#else
println(buf);
#endif
level++;
}
}
}
else
{
#ifdef ARDUINO
Serial.print(F("Unknown command: "));
Serial.println(cmd);
Serial.println(this->getHelpText());
#else
println("Unknown command: %s", cmd);
printf(this->getHelpText());
#endif
}
}
private:
DbgCli_Command_ChangeLevel();
};
//-----------------------------------------------------------------------------
// Class DbgTrace_Port
//-----------------------------------------------------------------------------
DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const char* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(tag)
{
if(0 != context)
{
context->addTracePort(this);
}
}
#ifdef ARDUINO
DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const __FlashStringHelper* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(reinterpret_cast<const char*>(tag))
{
if(0 != context)
{
context->addTracePort(this);
}
}
#endif
DbgTrace_Port::~DbgTrace_Port()
{
//Delete tracePort in single linked list
DbgTrace_Context* context = DbgTrace_Context::getContext();
if(0 != context)
{
context->deleteTracePort(m_tag);
}
}
void DbgTrace_Port::printStr(const char* str)
{
if(0 != m_out)
{
#ifdef ARDUINO
char timeStr[s_cArduinoTimeStamp];
#else
char timeStr[s_cTestTimeStamp];
#endif
char stream[s_cTraceBufSize];
getTime(timeStr);
snprintf(stream, sizeof(stream), "%s - %s: %s", timeStr, getTag(), str);
m_out->print(stream);
}
}
void DbgTrace_Port::printLong(long num)
{
if(0 != m_out)
{
#ifdef ARDUINO
char timeStr[s_cArduinoTimeStamp];
#else
char timeStr[s_cTestTimeStamp];
#endif
char stream[s_cTraceBufSize];
getTime(timeStr);
snprintf(stream, sizeof(stream), "%s - %s: %ld", timeStr, getTag(), num);
m_out->print(stream);
}
}
void DbgTrace_Port::printDbl(double val)
{
if(0 != m_out)
{
#ifdef ARDUINO
char timeStr[s_cArduinoTimeStamp];
#else
char timeStr[s_cTestTimeStamp];
#endif
getTime(timeStr);
char stream[s_cTraceBufSize];
snprintf(stream, sizeof(stream), "%s - %s: %f", timeStr, getTag(), val);
m_out->print(stream);
}
}
void DbgTrace_Port::getTime(char* timeStr)
{
#ifdef ARDUINO
sprintf(timeStr,"%ld", millis());
#else
_strtime(timeStr);
#endif
}
void DbgTrace_Port::createCliNodes(DbgCli_Topic* contextTopic)
{
DbgCli_Topic* portTopic = new DbgCli_Topic(contextTopic, m_tag, "Offers get/set access to output and level");
if(0 != m_out)
{
// Create DbgCli commands for out and level of this port
new DbgCli_Command_ChangeOut(this, portTopic, "outCmd", "Cmd's: get, set outName, list");
new DbgCli_Command_ChangeLevel(this, portTopic, "levelCmd", "Cmd's: get, set levelName, list");
}
}
<commit_msg>Shorter lvlCmd<commit_after>/*
* DbgTracePort.cpp
*
* Created on: 16.03.2015
* Author: niklausd
*/
#include "DbgTraceContext.h"
#include "DbgTraceOut.h"
#include "DbgTracePort.h"
#include "DbgCliCommand.h"
#ifdef ARDUINO
#include <Arduino.h>
#else
#include <time.h>
#endif
#include <stdio.h>
#include <string.h>
//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeOut
//-----------------------------------------------------------------------------
class DbgCli_Command_ChangeOut : public DbgCli_Command
{
private:
DbgTrace_Port* m_tracePort;
public:
DbgCli_Command_ChangeOut(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
: DbgCli_Command(parentNode, nodeName, helpText)
, m_tracePort(port)
{ }
void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
{
const char* cmd = args[idxToFirstArgToHandle];
DbgTrace_Context* context = DbgTrace_Context::getContext();
if(0 == strncmp(cmd, "get", 4))
{
if((0 != m_tracePort) && (0 != m_tracePort->getOut()))
{
char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
snprintf(buf, sizeof(buf), "Out: \"%s\"" , m_tracePort->getOut()->getName());
#ifdef ARDUINO
Serial.print(buf);
#else
println(buf);
#endif
}
}
else if(0 == strncmp(cmd, "set", 4))
{
if((0 != m_tracePort) && (0 != m_tracePort->getOut()) && (0 != context))
{
DbgTrace_Out* newOut = context->getTraceOut(args[idxToFirstArgToHandle+1]);
char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
if(0 != newOut)
{
m_tracePort->setOut(newOut);
snprintf(buf, sizeof(buf),"OK! Out: \"%s\"" , m_tracePort->getOut()->getName());
}
else
{
snprintf(buf, sizeof(buf), "Fail! Out: \"%s\"" , m_tracePort->getOut()->getName());
}
#ifdef ARDUINO
Serial.print(buf);
#else
println(buf);
#endif
}
}
else if((0 == strncmp(cmd, "list", 5)) && (0 != context))
{
DbgTrace_Out* tmpOut = context->getFirstTraceOut();
if((0 != m_tracePort) && (0 != m_tracePort->getOut()))
{
char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
while(0 != tmpOut)
{
if((0 != m_tracePort->getOut()) &&
(0 == strncmp(tmpOut->getName(), m_tracePort->getOut()->getName(), DbgTrace_Out::s_cMaxOutNameLength)))
{
// mark currently used out
snprintf(buf, sizeof(buf),">%s" , tmpOut->getName());
}
else
{
snprintf(buf, sizeof(buf), " %s" , tmpOut->getName());
}
#ifdef ARDUINO
Serial.println(buf);
#else
println(buf);
#endif
tmpOut = tmpOut->getNextOut();
}
}
}
else
{
#ifdef ARDUINO
Serial.print(F("Unknown command: "));
Serial.println(cmd);
Serial.println(this->getHelpText());
#else
println("Unknown command: %s", cmd);
printf(this->getHelpText());
#endif
}
}
private:
DbgCli_Command_ChangeOut();
};
//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeLevel
//-----------------------------------------------------------------------------
class DbgCli_Command_ChangeLevel : public DbgCli_Command
{
private:
DbgTrace_Port* m_tracePort;
public:
DbgCli_Command_ChangeLevel(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
: DbgCli_Command(parentNode, nodeName, helpText)
, m_tracePort(port)
{ }
void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
{
const char* cmd = args[idxToFirstArgToHandle];
if(0 == strncmp(cmd, "get", 4))
{
if(0 != m_tracePort)
{
char buf[20 + DbgTrace_Level::s_cMaxLevelLength];
snprintf(buf, sizeof(buf), "Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
#ifdef ARDUINO
Serial.println(buf);
#else
printfln(buf);
#endif
}
}
else if(0 == strncmp(cmd, "set", 4))
{
if(0 != m_tracePort)
{
char buf[20 + DbgTrace_Level::s_cMaxLevelLength];
DbgTrace_Level::Level newLevel = DbgTrace_Level::stringToLevel(args[idxToFirstArgToHandle+1]);
if(DbgTrace_Level::none != newLevel)
{
m_tracePort->setLevel(newLevel);
snprintf(buf, sizeof(buf),"OK! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
}
else
{
snprintf(buf, sizeof(buf), "Fail! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
}
#ifdef ARDUINO
Serial.print(buf);
#else
printfln(buf);
#endif
}
}
else if(0 == strncmp(cmd, "list", 5))
{
if(0 != m_tracePort)
{
unsigned int level = 0;
char buf[4 + DbgTrace_Level::s_cMaxLevelLength];
while(DbgTrace_Level::LEVEL_ENUM_LIMIT != level)
{
if(level == m_tracePort->getLevel())
{
// mark currently used out
snprintf(buf, sizeof(buf),">%s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
}
else
{
snprintf(buf, sizeof(buf)," %s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
}
#ifdef ARDUINO
Serial.println(buf);
#else
println(buf);
#endif
level++;
}
}
}
else
{
#ifdef ARDUINO
Serial.print(F("Unknown command: "));
Serial.println(cmd);
Serial.println(this->getHelpText());
#else
println("Unknown command: %s", cmd);
printf(this->getHelpText());
#endif
}
}
private:
DbgCli_Command_ChangeLevel();
};
//-----------------------------------------------------------------------------
// Class DbgTrace_Port
//-----------------------------------------------------------------------------
DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const char* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(tag)
{
if(0 != context)
{
context->addTracePort(this);
}
}
#ifdef ARDUINO
DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const __FlashStringHelper* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(reinterpret_cast<const char*>(tag))
{
if(0 != context)
{
context->addTracePort(this);
}
}
#endif
DbgTrace_Port::~DbgTrace_Port()
{
//Delete tracePort in single linked list
DbgTrace_Context* context = DbgTrace_Context::getContext();
if(0 != context)
{
context->deleteTracePort(m_tag);
}
}
void DbgTrace_Port::printStr(const char* str)
{
if(0 != m_out)
{
#ifdef ARDUINO
char timeStr[s_cArduinoTimeStamp];
#else
char timeStr[s_cTestTimeStamp];
#endif
char stream[s_cTraceBufSize];
getTime(timeStr);
snprintf(stream, sizeof(stream), "%s - %s: %s", timeStr, getTag(), str);
m_out->print(stream);
}
}
void DbgTrace_Port::printLong(long num)
{
if(0 != m_out)
{
#ifdef ARDUINO
char timeStr[s_cArduinoTimeStamp];
#else
char timeStr[s_cTestTimeStamp];
#endif
char stream[s_cTraceBufSize];
getTime(timeStr);
snprintf(stream, sizeof(stream), "%s - %s: %ld", timeStr, getTag(), num);
m_out->print(stream);
}
}
void DbgTrace_Port::printDbl(double val)
{
if(0 != m_out)
{
#ifdef ARDUINO
char timeStr[s_cArduinoTimeStamp];
#else
char timeStr[s_cTestTimeStamp];
#endif
getTime(timeStr);
char stream[s_cTraceBufSize];
snprintf(stream, sizeof(stream), "%s - %s: %f", timeStr, getTag(), val);
m_out->print(stream);
}
}
void DbgTrace_Port::getTime(char* timeStr)
{
#ifdef ARDUINO
sprintf(timeStr,"%ld", millis());
#else
_strtime(timeStr);
#endif
}
void DbgTrace_Port::createCliNodes(DbgCli_Topic* contextTopic)
{
DbgCli_Topic* portTopic = new DbgCli_Topic(contextTopic, m_tag, "Offers get/set access to output and level");
if(0 != m_out)
{
// Create DbgCli commands for out and level of this port
new DbgCli_Command_ChangeOut(this, portTopic, "outCmd", "Cmds: get, set <outName>, list");
new DbgCli_Command_ChangeLevel(this, portTopic, "lvlCmd", "Cmds: get, set <levelName>, list");
}
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2003-2012
\file WordListUtil.cpp
\author ([email protected])
\date 29.09.2012
\brief
\indent 4T
*/
#include <vector>
#include <map>
#include <boost\algorithm\string.hpp>
#include "utils\rdotypes.h"
#include "WordListUtil.h"
WordListUtil::WordListUtil(const WordList& wordlist)
: wl(wordlist)
{}
//tstring WordListUtil::GetNearestWord (const char *wordStart, int searchLen) const
//{
//}
std::vector<tstring> WordListUtil::GetNearestWords(const char *wordStart) const
{
struct keyword
{
tstring value;
int priority;
keyword()
: priority(0)
{}
keyword(const tstring& value, int priority)
: value (value )
, priority(priority)
{}
rbool operator< (const keyword& other) const
{
return priority < other.priority;
}
};
int start = 0;
int end = wl.len - 1;
std::vector<tstring> res;
std::vector<keyword> pres;
if (0 == wl.words)
{
res.push_back("");
return res;
}
if( boost::iequals(wordStart, ""))
{
for(int i = start; i < end; i++)
{
res.push_back(wl.words[i]);
}
return res;
}
for (int i = start; i < end; i++)
{
if (boost::ifind_first(wl.words[i], wordStart))
{
pres.push_back(keyword(wl.words[i], tstring(wl.words[i]).length()));
}
}
std::sort(pres.begin(), pres.end());
std::vector<keyword>::iterator it;
for (it = pres.begin(); it != pres.end(); ++it)
{
res.push_back(it->value);
}
return res;
}<commit_msg> - приоритет должен быть float<commit_after>/*!
\copyright (c) RDO-Team, 2003-2012
\file WordListUtil.cpp
\author ([email protected])
\date 29.09.2012
\brief
\indent 4T
*/
#include <vector>
#include <map>
#include <boost\algorithm\string.hpp>
#include "utils\rdotypes.h"
#include "WordListUtil.h"
WordListUtil::WordListUtil(const WordList& wordlist)
: wl(wordlist)
{}
//tstring WordListUtil::GetNearestWord (const char *wordStart, int searchLen) const
//{
//}
std::vector<tstring> WordListUtil::GetNearestWords(const char *wordStart) const
{
struct keyword
{
tstring value;
float priority;
keyword()
: priority(0.0)
{}
keyword(const tstring& value, float priority)
: value (value )
, priority(priority)
{}
rbool operator< (const keyword& other) const
{
return priority < other.priority;
}
};
int start = 0;
int end = wl.len - 1;
std::vector<tstring> res;
std::vector<keyword> pres;
if (0 == wl.words)
{
res.push_back("");
return res;
}
if( boost::iequals(wordStart, ""))
{
for(int i = start; i < end; i++)
{
res.push_back(wl.words[i]);
}
return res;
}
for (int i = start; i < end; i++)
{
if (boost::ifind_first(wl.words[i], wordStart))
{
pres.push_back(keyword(wl.words[i], tstring(wl.words[i]).length()));
}
}
std::sort(pres.begin(), pres.end());
std::vector<keyword>::iterator it;
for (it = pres.begin(); it != pres.end(); ++it)
{
res.push_back(it->value);
}
return res;
}<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "attributenode.h"
#include <vespa/searchlib/attribute/singleenumattribute.h>
namespace search::expression {
using namespace vespalib;
using search::attribute::IAttributeContext;
using search::attribute::IAttributeVector;
using search::attribute::BasicType;
IMPLEMENT_EXPRESSIONNODE(AttributeNode, FunctionNode);
IMPLEMENT_RESULTNODE(AttributeResult, ResultNode);
namespace {
class EnumAttributeResult : public AttributeResult
{
public:
DECLARE_RESULTNODE(EnumAttributeResult);
EnumAttributeResult(const attribute::IAttributeVector * attribute, DocId docId) :
AttributeResult(attribute, docId),
_enumAttr(dynamic_cast<const SingleValueEnumAttributeBase *>(attribute))
{
}
private:
EnumAttributeResult() :
AttributeResult(),
_enumAttr(NULL)
{ }
int64_t onGetEnum(size_t index) const override { (void) index; return (static_cast<int64_t>(_enumAttr->getE(getDocId()))); }
const SingleValueEnumAttributeBase * _enumAttr;
};
IMPLEMENT_RESULTNODE(EnumAttributeResult, AttributeResult);
std::unique_ptr<AttributeResult> createResult(const IAttributeVector * attribute)
{
return (dynamic_cast<const SingleValueEnumAttributeBase *>(attribute) != NULL)
? std::make_unique<EnumAttributeResult>(attribute, 0)
: std::make_unique<AttributeResult>(attribute, 0);
}
}
AttributeNode::AttributeNode() :
FunctionNode(),
_scratchResult(new AttributeResult()),
_hasMultiValue(false),
_useEnumOptimization(false),
_handler(),
_attributeName()
{}
AttributeNode::~AttributeNode() {}
AttributeNode::AttributeNode(vespalib::stringref name) :
FunctionNode(),
_scratchResult(new AttributeResult()),
_hasMultiValue(false),
_useEnumOptimization(false),
_handler(),
_attributeName(name)
{}
AttributeNode::AttributeNode(const IAttributeVector & attribute) :
FunctionNode(),
_scratchResult(createResult(&attribute)),
_hasMultiValue(attribute.hasMultiValue()),
_useEnumOptimization(false),
_handler(),
_attributeName(attribute.getName())
{}
AttributeNode::AttributeNode(const AttributeNode & attribute) :
FunctionNode(attribute),
_scratchResult(attribute._scratchResult->clone()),
_hasMultiValue(attribute._hasMultiValue),
_useEnumOptimization(attribute._useEnumOptimization),
_handler(),
_attributeName(attribute._attributeName)
{
_scratchResult->setDocId(0);
}
AttributeNode & AttributeNode::operator = (const AttributeNode & attr)
{
if (this != &attr) {
FunctionNode::operator = (attr);
_attributeName = attr._attributeName;
_hasMultiValue = attr._hasMultiValue;
_useEnumOptimization = attr._useEnumOptimization;
_scratchResult.reset(attr._scratchResult->clone());
_scratchResult->setDocId(0);
}
return *this;
}
void AttributeNode::onPrepare(bool preserveAccurateTypes)
{
const IAttributeVector * attribute = _scratchResult->getAttribute();
if (attribute != NULL) {
BasicType::Type basicType = attribute->getBasicType();
if (attribute->isIntegerType()) {
if (_hasMultiValue) {
if (preserveAccurateTypes) {
switch (basicType) {
case BasicType::INT8:
setResultType(std::make_unique<Int8ResultNodeVector>());
break;
case BasicType::INT16:
setResultType(std::make_unique<Int16ResultNodeVector>());
break;
case BasicType::INT32:
setResultType(std::make_unique<Int32ResultNodeVector>());
break;
case BasicType::INT64:
setResultType(std::make_unique<Int64ResultNodeVector>());
break;
default:
throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
break;
}
} else {
setResultType(std::make_unique<IntegerResultNodeVector>());
}
_handler = std::make_unique<IntegerHandler>(updateResult());
} else {
if (preserveAccurateTypes) {
switch (basicType) {
case BasicType::INT8:
setResultType(std::make_unique<Int8ResultNode>());
break;
case BasicType::INT16:
setResultType(std::make_unique<Int16ResultNode>());
break;
case BasicType::INT32:
setResultType(std::make_unique<Int32ResultNode>());
break;
case BasicType::INT64:
setResultType(std::make_unique<Int64ResultNode>());
break;
default:
throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
break;
}
} else {
setResultType(std::make_unique<Int64ResultNode>());
}
}
} else if (attribute->isFloatingPointType()) {
if (_hasMultiValue) {
setResultType(std::make_unique<FloatResultNodeVector>());
_handler = std::make_unique<FloatHandler>(updateResult());
} else {
setResultType(std::make_unique<FloatResultNode>());
}
} else if (attribute->isStringType()) {
if (_hasMultiValue) {
if (_useEnumOptimization) {
setResultType(std::make_unique<EnumResultNodeVector>());
_handler = std::make_unique<EnumHandler>(updateResult());
} else {
setResultType(std::make_unique<StringResultNodeVector>());
_handler = std::make_unique<StringHandler>(updateResult());
}
} else {
if (_useEnumOptimization) {
setResultType(std::make_unique<EnumResultNode>());
} else {
setResultType(std::make_unique<StringResultNode>());
}
}
} else {
throw std::runtime_error(make_string("Can not deduce correct resultclass for attribute vector '%s'",
attribute->getName().c_str()));
}
}
}
void AttributeNode::IntegerHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
void AttributeNode::FloatHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
void AttributeNode::StringHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
void AttributeNode::EnumHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
bool AttributeNode::onExecute() const
{
if (_hasMultiValue) {
_handler->handle(*_scratchResult);
} else {
updateResult().set(*_scratchResult);
}
return true;
}
void AttributeNode::wireAttributes(const IAttributeContext & attrCtx)
{
const IAttributeVector * attribute(_scratchResult ? _scratchResult->getAttribute() : nullptr);
if (attribute == NULL) {
if (_useEnumOptimization) {
attribute = attrCtx.getAttributeStableEnum(_attributeName);
} else {
attribute = attrCtx.getAttribute(_attributeName);
}
if (attribute == NULL) {
throw std::runtime_error(make_string("Failed locating attribute vector '%s'", _attributeName.c_str()));
}
_hasMultiValue = attribute->hasMultiValue();
_scratchResult = createResult(attribute);
}
}
void AttributeNode::cleanup()
{
_scratchResult.reset();
}
Serializer & AttributeNode::onSerialize(Serializer & os) const
{
FunctionNode::onSerialize(os);
return os << _attributeName;
}
Deserializer & AttributeNode::onDeserialize(Deserializer & is)
{
FunctionNode::onDeserialize(is);
return is >> _attributeName;
}
void
AttributeNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
visit(visitor, "attributeName", _attributeName);
}
}
// this function was added by ../../forcelink.sh
void forcelink_file_searchlib_expression_attributenode() {}
<commit_msg>Use Handler in AttributeNode when present to update values.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "attributenode.h"
#include <vespa/searchlib/attribute/singleenumattribute.h>
namespace search::expression {
using namespace vespalib;
using search::attribute::IAttributeContext;
using search::attribute::IAttributeVector;
using search::attribute::BasicType;
IMPLEMENT_EXPRESSIONNODE(AttributeNode, FunctionNode);
IMPLEMENT_RESULTNODE(AttributeResult, ResultNode);
namespace {
class EnumAttributeResult : public AttributeResult
{
public:
DECLARE_RESULTNODE(EnumAttributeResult);
EnumAttributeResult(const attribute::IAttributeVector * attribute, DocId docId) :
AttributeResult(attribute, docId),
_enumAttr(dynamic_cast<const SingleValueEnumAttributeBase *>(attribute))
{
}
private:
EnumAttributeResult() :
AttributeResult(),
_enumAttr(NULL)
{ }
int64_t onGetEnum(size_t index) const override { (void) index; return (static_cast<int64_t>(_enumAttr->getE(getDocId()))); }
const SingleValueEnumAttributeBase * _enumAttr;
};
IMPLEMENT_RESULTNODE(EnumAttributeResult, AttributeResult);
std::unique_ptr<AttributeResult> createResult(const IAttributeVector * attribute)
{
return (dynamic_cast<const SingleValueEnumAttributeBase *>(attribute) != NULL)
? std::make_unique<EnumAttributeResult>(attribute, 0)
: std::make_unique<AttributeResult>(attribute, 0);
}
}
AttributeNode::AttributeNode() :
FunctionNode(),
_scratchResult(new AttributeResult()),
_hasMultiValue(false),
_useEnumOptimization(false),
_handler(),
_attributeName()
{}
AttributeNode::~AttributeNode() {}
AttributeNode::AttributeNode(vespalib::stringref name) :
FunctionNode(),
_scratchResult(new AttributeResult()),
_hasMultiValue(false),
_useEnumOptimization(false),
_handler(),
_attributeName(name)
{}
AttributeNode::AttributeNode(const IAttributeVector & attribute) :
FunctionNode(),
_scratchResult(createResult(&attribute)),
_hasMultiValue(attribute.hasMultiValue()),
_useEnumOptimization(false),
_handler(),
_attributeName(attribute.getName())
{}
AttributeNode::AttributeNode(const AttributeNode & attribute) :
FunctionNode(attribute),
_scratchResult(attribute._scratchResult->clone()),
_hasMultiValue(attribute._hasMultiValue),
_useEnumOptimization(attribute._useEnumOptimization),
_handler(),
_attributeName(attribute._attributeName)
{
_scratchResult->setDocId(0);
}
AttributeNode & AttributeNode::operator = (const AttributeNode & attr)
{
if (this != &attr) {
FunctionNode::operator = (attr);
_attributeName = attr._attributeName;
_hasMultiValue = attr._hasMultiValue;
_useEnumOptimization = attr._useEnumOptimization;
_scratchResult.reset(attr._scratchResult->clone());
_scratchResult->setDocId(0);
}
return *this;
}
void AttributeNode::onPrepare(bool preserveAccurateTypes)
{
const IAttributeVector * attribute = _scratchResult->getAttribute();
if (attribute != NULL) {
BasicType::Type basicType = attribute->getBasicType();
if (attribute->isIntegerType()) {
if (_hasMultiValue) {
if (preserveAccurateTypes) {
switch (basicType) {
case BasicType::INT8:
setResultType(std::make_unique<Int8ResultNodeVector>());
break;
case BasicType::INT16:
setResultType(std::make_unique<Int16ResultNodeVector>());
break;
case BasicType::INT32:
setResultType(std::make_unique<Int32ResultNodeVector>());
break;
case BasicType::INT64:
setResultType(std::make_unique<Int64ResultNodeVector>());
break;
default:
throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
break;
}
} else {
setResultType(std::make_unique<IntegerResultNodeVector>());
}
_handler = std::make_unique<IntegerHandler>(updateResult());
} else {
if (preserveAccurateTypes) {
switch (basicType) {
case BasicType::INT8:
setResultType(std::make_unique<Int8ResultNode>());
break;
case BasicType::INT16:
setResultType(std::make_unique<Int16ResultNode>());
break;
case BasicType::INT32:
setResultType(std::make_unique<Int32ResultNode>());
break;
case BasicType::INT64:
setResultType(std::make_unique<Int64ResultNode>());
break;
default:
throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
break;
}
} else {
setResultType(std::make_unique<Int64ResultNode>());
}
}
} else if (attribute->isFloatingPointType()) {
if (_hasMultiValue) {
setResultType(std::make_unique<FloatResultNodeVector>());
_handler = std::make_unique<FloatHandler>(updateResult());
} else {
setResultType(std::make_unique<FloatResultNode>());
}
} else if (attribute->isStringType()) {
if (_hasMultiValue) {
if (_useEnumOptimization) {
setResultType(std::make_unique<EnumResultNodeVector>());
_handler = std::make_unique<EnumHandler>(updateResult());
} else {
setResultType(std::make_unique<StringResultNodeVector>());
_handler = std::make_unique<StringHandler>(updateResult());
}
} else {
if (_useEnumOptimization) {
setResultType(std::make_unique<EnumResultNode>());
} else {
setResultType(std::make_unique<StringResultNode>());
}
}
} else {
throw std::runtime_error(make_string("Can not deduce correct resultclass for attribute vector '%s'",
attribute->getName().c_str()));
}
}
}
void AttributeNode::IntegerHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
void AttributeNode::FloatHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
void AttributeNode::StringHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
void AttributeNode::EnumHandler::handle(const AttributeResult & r)
{
size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
_vector.resize(numValues);
_wVector.resize(numValues);
r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
for(size_t i(0); i < numValues; i++) {
_vector[i] = _wVector[i].getValue();
}
}
bool AttributeNode::onExecute() const
{
if (_handler) {
_handler->handle(*_scratchResult);
} else {
updateResult().set(*_scratchResult);
}
return true;
}
void AttributeNode::wireAttributes(const IAttributeContext & attrCtx)
{
const IAttributeVector * attribute(_scratchResult ? _scratchResult->getAttribute() : nullptr);
if (attribute == NULL) {
if (_useEnumOptimization) {
attribute = attrCtx.getAttributeStableEnum(_attributeName);
} else {
attribute = attrCtx.getAttribute(_attributeName);
}
if (attribute == NULL) {
throw std::runtime_error(make_string("Failed locating attribute vector '%s'", _attributeName.c_str()));
}
_hasMultiValue = attribute->hasMultiValue();
_scratchResult = createResult(attribute);
}
}
void AttributeNode::cleanup()
{
_scratchResult.reset();
}
Serializer & AttributeNode::onSerialize(Serializer & os) const
{
FunctionNode::onSerialize(os);
return os << _attributeName;
}
Deserializer & AttributeNode::onDeserialize(Deserializer & is)
{
FunctionNode::onDeserialize(is);
return is >> _attributeName;
}
void
AttributeNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
visit(visitor, "attributeName", _attributeName);
}
}
// this function was added by ../../forcelink.sh
void forcelink_file_searchlib_expression_attributenode() {}
<|endoftext|> |
<commit_before>/// \file ROOT/TText.hxx
/// \ingroup Graf ROOT7
/// \author Olivier Couet <[email protected]>
/// \date 2017-10-16
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TText
#define ROOT7_TText
#include <ROOT/TDrawable.hxx>
#include <ROOT/TDrawingAttr.hxx>
#include <ROOT/TDrawingOptsBase.hxx>
#include <ROOT/TPad.hxx>
#include <ROOT/TVirtualCanvasPainter.hxx>
#include <initializer_list>
#include <memory>
#include <string>
namespace ROOT {
namespace Experimental {
/** \class ROOT::Experimental::TText
A text.
*/
class TText {
private:
std::string fText{};
/// Text's X position
double fX{0.};
/// Text's Y position
double fY{0.};
public:
TText() = default;
TText(const std::string &str) : fText(str) {}
void SetText(const std::string &txt) { fText = txt; }
std::string GetText() const { return fText; }
void SetPosition(double x, double y)
{
fX = x;
fY = y;
}
double GetX() const { return fX; }
double GetY() const { return fY; }
};
class TextDrawingOpts: public TDrawingOptsBase {
TDrawingAttr<int> fLineWidth{*this, "Text.Line.Width", 3}; ///< The line width.
TDrawingAttr<TColor> fLineColor{*this, "Text.Line.Color", TColor::kBlack}; ///< The line color.
TDrawingAttr<TColor> fFillColor{*this, "Text.Fill.Color", TColor::kInvisible}; ///< The fill color.
public:
/// The color of the line.
void SetLineColor(const TColor &col) { fLineColor = col; }
TColor &GetLineColor() { return fLineColor.Get(); }
const TColor &GetLineColor() const { return fLineColor.Get(); }
/// The width of the line.
void SetLineWidth(int width) { fLineWidth = width; }
int GetLineWidth() { return (int)fLineWidth; }
/// The fill color
void SetFillColor(const TColor &col) { fFillColor = col; }
TColor &GetFillColor() { return fFillColor.Get(); }
const TColor &GetFillColor() const { return fFillColor.Get(); }
};
class TTextDrawable : public TDrawable {
private:
/// Text string to be drawn
Internal::TUniWeakPtr<ROOT::Experimental::TText> fText{};
/// Text attributes
TextDrawingOpts fOpts;
public:
TTextDrawable() = default;
TTextDrawable(const std::shared_ptr<ROOT::Experimental::TText> &txt)
: TDrawable(), fText(txt)
{
}
TextDrawingOpts &GetOptions() { return fOpts; }
const TextDrawingOpts &GetOptions() const { return fOpts; }
void Paint(Internal::TVirtualCanvasPainter &canv) final
{
canv.AddDisplayItem(new ROOT::Experimental::TOrdinaryDisplayItem<ROOT::Experimental::TTextDrawable>(this));
}
};
inline std::unique_ptr<ROOT::Experimental::TTextDrawable>
GetDrawable(const std::shared_ptr<ROOT::Experimental::TText> &text)
{
return std::make_unique<ROOT::Experimental::TTextDrawable>(text);
}
} // namespace Experimental
} // namespace ROOT
#endif
<commit_msg>Inject TDrawableBase.<commit_after>/// \file ROOT/TText.hxx
/// \ingroup Graf ROOT7
/// \author Olivier Couet <[email protected]>
/// \date 2017-10-16
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TText
#define ROOT7_TText
#include <ROOT/TDrawable.hxx>
#include <ROOT/TDrawingAttr.hxx>
#include <ROOT/TDrawingOptsBase.hxx>
#include <ROOT/TPad.hxx>
#include <ROOT/TVirtualCanvasPainter.hxx>
#include <initializer_list>
#include <memory>
#include <string>
namespace ROOT {
namespace Experimental {
/** \class ROOT::Experimental::TText
A text.
*/
class TText {
private:
std::string fText{};
/// Text's X position
double fX{0.};
/// Text's Y position
double fY{0.};
public:
TText() = default;
TText(const std::string &str) : fText(str) {}
void SetText(const std::string &txt) { fText = txt; }
std::string GetText() const { return fText; }
void SetPosition(double x, double y)
{
fX = x;
fY = y;
}
double GetX() const { return fX; }
double GetY() const { return fY; }
};
class TextDrawingOpts: public TDrawingOptsBase {
TDrawingAttr<int> fLineWidth{*this, "Text.Line.Width", 3}; ///< The line width.
TDrawingAttr<TColor> fLineColor{*this, "Text.Line.Color", TColor::kBlack}; ///< The line color.
TDrawingAttr<TColor> fFillColor{*this, "Text.Fill.Color", TColor::kInvisible}; ///< The fill color.
public:
/// The color of the line.
void SetLineColor(const TColor &col) { fLineColor = col; }
TColor &GetLineColor() { return fLineColor.Get(); }
const TColor &GetLineColor() const { return fLineColor.Get(); }
/// The width of the line.
void SetLineWidth(int width) { fLineWidth = width; }
int GetLineWidth() { return (int)fLineWidth; }
/// The fill color
void SetFillColor(const TColor &col) { fFillColor = col; }
TColor &GetFillColor() { return fFillColor.Get(); }
const TColor &GetFillColor() const { return fFillColor.Get(); }
};
class TTextDrawable : public TDrawableBase<TTextDrawable> {
private:
/// Text string to be drawn
Internal::TUniWeakPtr<ROOT::Experimental::TText> fText{};
/// Text attributes
TextDrawingOpts fOpts;
public:
TTextDrawable() = default;
TTextDrawable(const std::shared_ptr<ROOT::Experimental::TText> &txt)
: fText(txt)
{
}
TextDrawingOpts &GetOptions() { return fOpts; }
const TextDrawingOpts &GetOptions() const { return fOpts; }
void Paint(Internal::TVirtualCanvasPainter &canv) final
{
canv.AddDisplayItem(new ROOT::Experimental::TOrdinaryDisplayItem<ROOT::Experimental::TTextDrawable>(this));
}
};
inline std::unique_ptr<ROOT::Experimental::TTextDrawable>
GetDrawable(const std::shared_ptr<ROOT::Experimental::TText> &text)
{
return std::make_unique<ROOT::Experimental::TTextDrawable>(text);
}
} // namespace Experimental
} // namespace ROOT
#endif
<|endoftext|> |
<commit_before>#pragma once
#include <stdint.h>
#include <type_traits>
namespace faze
{
// lets just use 64bits for this
// we can reduce the size later if needed
struct ResourceHandle
{
union
{
struct
{
uint64_t id : 20; // million is too much for id's
uint64_t generation : 8; // generous generation id
uint64_t type : 6; // ... I don't really want to write this much api types
uint64_t gpuid : 16; // this should just be a bitfield, one bit for gpu, starting with modest 16 gpu's =D
uint64_t unused : 14; // honestly could be more bits here, lets just see how things go on
};
uint64_t rawValue;
};
ResourceHandle(uint64_t id, uint64_t generation, uint64_t type, uint64_t gpuID)
: id(id)
, generation(generation)
, type(type)
, gpuid(gpuID)
{
static_assert(std::is_standard_layout<ResourceHandle>::value, "ResourceHandle should be trivial to destroy.");
}
// returns positive value when single gpu
// -1 when every gpu owns its own
// -2 is mysterious error situation.
int ownerGpuId() const
{
uint64_t c_gpuid = gpuid;
uint64_t count = 0;
if (c_gpuid == 65535)
{
return -1;
}
while(count < 16) // valid id's 0-15
{
if (c_gpuid & (1 << count))
{
return int(count);
}
}
return -2;
}
// shared resource means it's a handle that can be opened on another api/gpu device
// otherwise all gpu's have their own version of this resource.
bool sharedResource() const
{
return ownerGpuId() >= 0; // false for now
}
};
/*
Problem is how we allocate these and ...
There probably should be a manager that we can use for checks
Ideally we want to check generation on each access of resource.
So we could have something that gives out id's and offers functions to check if those id's are expired.
So we would need
- Allocate Handle
- get id from pool
- if no id in pool, make a new one
- Delete Handle
- mostly just, return to pool as usable
- check if alive
- array to check current status of the id and match generation for id check
*/
}<commit_msg>some more handle code Just making the utilities on using handles easier. Bit more so that I don't just spend tons of memory upfront for all id's like I do now.... 1 million uint32_t's upfront is kind of sizeful if assuming I use all the bits. Small steps baby steps...<commit_after>#pragma once
#include <core/datastructures/proxy.hpp>
#include <core/global_debug.hpp>
#include <stdint.h>
#include <type_traits>
namespace faze
{
// lets just use 64bits for this
// we can reduce the size later if needed
struct ResourceHandle
{
static const uint64_t InvalidId = (1ull << 20ull) - 1;
union
{
struct
{
uint64_t id : 20; // million is too much for id's
uint64_t generation : 8; // generous generation id
uint64_t type : 6; // ... I don't really want to write this much api types
uint64_t gpuid : 16; // this should just be a bitfield, one bit for gpu, starting with modest 16 gpu's =D
uint64_t unused : 14; // honestly could be more bits here, lets just see how things go on
};
uint64_t rawValue;
};
ResourceHandle(uint64_t id, uint64_t generation, uint64_t type, uint64_t gpuID)
: id(id)
, generation(generation)
, type(type)
, gpuid(gpuID)
{
static_assert(std::is_standard_layout<ResourceHandle>::value, "ResourceHandle should be trivial to destroy.");
}
// returns positive value when single gpu
// -1 when every gpu owns its own
// -2 is mysterious error situation.
int ownerGpuId() const
{
uint64_t c_gpuid = gpuid;
uint64_t count = 0;
if (c_gpuid == 65535)
{
return -1;
}
while(count < 16) // valid id's 0-15
{
if (c_gpuid & (1 << count))
{
return int(count);
}
}
return -2;
}
// shared resource means it's a handle that can be opened on another api/gpu device
// otherwise all gpu's have their own version of this resource.
bool sharedResource() const
{
return ownerGpuId() >= 0; // false for now
}
};
/*
Problem is how we allocate these and ...
There probably should be a manager that we can use for checks
Ideally we want to check generation on each access of resource.
So we could have something that gives out id's and offers functions to check if those id's are expired.
So we would need
- Allocate Handle
- get id from pool
- if no id in pool, make a new one
- Delete Handle
- mostly just, return to pool as usable
- check if alive
- array to check current status of the id and match generation for id check
*/
// we need legopiece to generate id's which knows how to reuse them
// we need "type" amount of these lego pieces, all ranges begin from 0 till something
class HandlePool
{
vector<uint32_t> m_freelist;
vector<uint8_t> m_generation;
uint64_t m_type = 0;
int m_size = 0;
public:
HandlePool(uint64_t type, int size)
: m_type(type)
, m_size(size)
{
for (int i = size; i >= 0; i--)
{
m_freelist.push_back(i);
}
m_generation.resize(m_size);
for (int i = 0; i < m_size; ++i)
{
m_generation[i] = 0;
}
}
ResourceHandle allocate()
{
if (m_freelist.empty())
{
F_ASSERT(false, "No handles left, what.");
return ResourceHandle{ResourceHandle::InvalidId, 0, m_type, 0};
}
auto id = m_freelist.back();
m_freelist.pop_back();
auto generation = m_generation[id]; // take current generation
return ResourceHandle{id, generation, m_type, 0};
}
void release(ResourceHandle val)
{
F_ASSERT(val.id != ResourceHandle::InvalidId
&& val.id < m_size
&& val.generation == m_generation[val.id]
, "Invalid handle was released.");
m_freelist.push_back(val.id);
m_generation[val.id]++; // offset the generation to detect double free's
}
bool valid(ResourceHandle handle)
{
F_ASSERT(handle.id != ResourceHandle::InvalidId
&& handle.id < m_size
, "Invalid handle was passed.");
return handle.generation == m_generation[handle.id];
}
size_t size() const
{
return m_freelist.size();
}
};
}<|endoftext|> |
<commit_before>#pragma once
#include <stdint.h>
#include <type_traits>
namespace faze
{
// lets just use 64bits for this
// we can reduce the size later if needed
struct ResourceHandle
{
union
{
struct
{
uint64_t id : 20; // million is too much for id's
uint64_t generation : 8; // generous generation id
uint64_t type : 6; // ... I don't really want to write this much api types
uint64_t gpuid : 16; // this should just be a bitfield, one bit for gpu, starting with modest 16 gpu's =D
uint64_t unused : 14; // honestly could be more bits here, lets just see how things go on
};
uint64_t rawValue;
};
ResourceHandle(uint64_t id, uint64_t generation, uint64_t type, uint64_t gpuID)
: id(id)
, generation(generation)
, type(type)
, gpuid(gpuID)
{
static_assert(std::is_standard_layout<ResourceHandle>::value, "ResourceHandle should be trivial to destroy.");
}
// returns positive value when single gpu
// -1 when every gpu owns its own
// -2 is mysterious error situation.
int ownerGpuId() const
{
uint64_t c_gpuid = gpuid;
uint64_t count = 0;
if (c_gpuid == 65535)
{
return -1;
}
while(count < 16) // valid id's 0-15
{
if (c_gpuid & (1 << count))
{
return int(count);
}
}
return -2;
}
// shared resource means it's a handle that can be opened on another api/gpu device
// otherwise all gpu's have their own version of this resource.
bool sharedResource() const
{
return ownerGpuId() >= 0; // false for now
}
};
/*
Problem is how we allocate these and ...
There probably should be a manager that we can use for checks
Ideally we want to check generation on each access of resource.
So we could have something that gives out id's and offers functions to check if those id's are expired.
So we would need
- Allocate Handle
- get id from pool
- if no id in pool, make a new one
- Delete Handle
- mostly just, return to pool as usable
- check if alive
- array to check current status of the id and match generation for id check
*/
}<commit_msg>handle updates<commit_after>#pragma once
#include <core/datastructures/proxy.hpp>
#include <core/global_debug.hpp>
#include <stdint.h>
#include <type_traits>
namespace faze
{
// lets just use 64bits for this
// we can reduce the size later if needed
struct ResourceHandle
{
static const uint64_t InvalidId = (1ull << 20ull) - 1;
union
{
struct
{
uint64_t id : 20; // million is too much for id's
uint64_t generation : 8; // generous generation id
uint64_t type : 6; // ... I don't really want to write this much api types
uint64_t gpuid : 16; // this should just be a bitfield, one bit for gpu, starting with modest 16 gpu's =D
uint64_t unused : 14; // honestly could be more bits here, lets just see how things go on
};
uint64_t rawValue;
};
ResourceHandle(uint64_t id, uint64_t generation, uint64_t type, uint64_t gpuID)
: id(id)
, generation(generation)
, type(type)
, gpuid(gpuID)
{
static_assert(std::is_standard_layout<ResourceHandle>::value, "ResourceHandle should be trivial to destroy.");
}
// returns positive value when single gpu
// -1 when every gpu owns its own
// -2 is mysterious error situation.
int ownerGpuId() const
{
uint64_t c_gpuid = gpuid;
uint64_t count = 0;
if (c_gpuid == 65535)
{
return -1;
}
while(count < 16) // valid id's 0-15
{
if (c_gpuid & (1 << count))
{
return int(count);
}
}
return -2;
}
// shared resource means it's a handle that can be opened on another api/gpu device
// otherwise all gpu's have their own version of this resource.
bool sharedResource() const
{
return ownerGpuId() >= 0; // false for now
}
};
/*
Problem is how we allocate these and ...
There probably should be a manager that we can use for checks
Ideally we want to check generation on each access of resource.
So we could have something that gives out id's and offers functions to check if those id's are expired.
So we would need
- Allocate Handle
- get id from pool
- if no id in pool, make a new one
- Delete Handle
- mostly just, return to pool as usable
- check if alive
- array to check current status of the id and match generation for id check
*/
// we need legopiece to generate id's which knows how to reuse them
// we need "type" amount of these lego pieces, all ranges begin from 0 till something
class HandlePool
{
vector<uint32_t> m_freelist;
vector<uint8_t> m_generation;
uint64_t m_type = 0;
int m_size = 0;
public:
HandlePool(uint64_t type, int size)
: m_type(type)
, m_size(size)
{
for (int i = size; i >= 0; i--)
{
m_freelist.push_back(i);
}
m_generation.resize(m_size);
for (int i = 0; i < m_size; ++i)
{
m_generation[i] = 0;
}
}
ResourceHandle allocate()
{
if (m_freelist.empty())
{
F_ASSERT(false, "No handles left, what.");
return ResourceHandle{ResourceHandle::InvalidId, 0, m_type, 0};
}
auto id = m_freelist.back();
m_freelist.pop_back();
auto generation = m_generation[id]; // take current generation
return ResourceHandle{id, generation, m_type, 0};
}
void release(ResourceHandle val)
{
F_ASSERT(val.id != ResourceHandle::InvalidId
&& val.id < m_size
&& val.generation == m_generation[val.id]
, "Invalid handle was released.");
m_freelist.push_back(val.id);
m_generation[val.id]++; // offset the generation to detect double free's
}
bool valid(ResourceHandle handle)
{
F_ASSERT(handle.id != ResourceHandle::InvalidId
&& handle.id < m_size
, "Invalid handle was passed.");
return handle.generation == m_generation[handle.id];
}
size_t size() const
{
return m_freelist.size();
}
};
}<|endoftext|> |
<commit_before>#include <stdint.h>
#ifndef __clockid_t_defined
#define __clockid_t_defined 1
typedef int32_t clockid_t;
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 1
#define CLOCK_PROCESS_CPUTIME_ID 2
#define CLOCK_THREAD_CPUTIME_ID 3
#define CLOCK_MONOTONIC_RAW 4
#define CLOCK_REALTIME_COARSE 5
#define CLOCK_MONOTONIC_COARSE 6
#define CLOCK_BOOTTIME 7
#define CLOCK_REALTIME_ALARM 8
#define CLOCK_BOOTTIME_ALARM 9
#endif // __clockid_t_defined
#ifndef _STRUCT_TIMESPEC
#define _STRUCT_TIMESPEC
struct timespec {
long tv_sec; /* Seconds. */
long tv_nsec; /* Nanoseconds. */
};
#endif // _STRUCT_TIMESPEC
extern "C" {
extern int clock_gettime(clockid_t clk_id, struct timespec *tp);
WEAK bool halide_reference_clock_inited = false;
WEAK timespec halide_reference_clock;
WEAK int halide_start_clock() {
// Guard against multiple calls
if (!halide_reference_clock_inited) {
clock_gettime(CLOCK_REALTIME, &halide_reference_clock);
halide_reference_clock_inited = true;
}
return 0;
}
WEAK int64_t halide_current_time_ns() {
timespec now;
clock_gettime(CLOCK_REALTIME, &now);
int64_t d = int64_t(now.tv_sec - halide_reference_clock.tv_sec)*1000000000;
int64_t nd = (now.tv_nsec - halide_reference_clock.tv_nsec);
return d + nd;
}
}
<commit_msg>Made linux_clock do the syscall directly to dodge linking woes.<commit_after>#include <stdint.h>
#ifndef __clockid_t_defined
#define __clockid_t_defined 1
typedef int32_t clockid_t;
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 1
#define CLOCK_PROCESS_CPUTIME_ID 2
#define CLOCK_THREAD_CPUTIME_ID 3
#define CLOCK_MONOTONIC_RAW 4
#define CLOCK_REALTIME_COARSE 5
#define CLOCK_MONOTONIC_COARSE 6
#define CLOCK_BOOTTIME 7
#define CLOCK_REALTIME_ALARM 8
#define CLOCK_BOOTTIME_ALARM 9
#endif // __clockid_t_defined
#ifndef _STRUCT_TIMESPEC
#define _STRUCT_TIMESPEC
struct timespec {
long tv_sec; /* Seconds. */
long tv_nsec; /* Nanoseconds. */
};
#endif // _STRUCT_TIMESPEC
// Should be safe to include these, given that we know we're on linux
// if we're compiling this file.
#include <sys/syscall.h>
#include <unistd.h>
extern "C" {
WEAK bool halide_reference_clock_inited = false;
WEAK timespec halide_reference_clock;
WEAK int halide_start_clock() {
// Guard against multiple calls
if (!halide_reference_clock_inited) {
syscall(SYS_clock_gettime, CLOCK_REALTIME, &halide_reference_clock);
halide_reference_clock_inited = true;
}
return 0;
}
WEAK int64_t halide_current_time_ns() {
timespec now;
// To avoid requiring people to link -lrt, we just make the syscall directly.
syscall(SYS_clock_gettime, CLOCK_REALTIME, &now);
int64_t d = int64_t(now.tv_sec - halide_reference_clock.tv_sec)*1000000000;
int64_t nd = (now.tv_nsec - halide_reference_clock.tv_nsec);
return d + nd;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.